Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/fmt | repos/gotta-go-fast/src/self-hosted-parser/input_dir/fmt/errol/lookup.zig | pub const HP = struct {
val: f64,
off: f64,
};
pub const lookup_table = [_]HP{
HP{ .val = 1.000000e+308, .off = -1.097906362944045488e+291 },
HP{ .val = 1.000000e+307, .off = 1.396894023974354241e+290 },
HP{ .val = 1.000000e+306, .off = -1.721606459673645508e+289 },
HP{ .val = 1.000000e+305, .off = 6.074644749446353973e+288 },
HP{ .val = 1.000000e+304, .off = 6.074644749446353567e+287 },
HP{ .val = 1.000000e+303, .off = -1.617650767864564452e+284 },
HP{ .val = 1.000000e+302, .off = -7.629703079084895055e+285 },
HP{ .val = 1.000000e+301, .off = -5.250476025520442286e+284 },
HP{ .val = 1.000000e+300, .off = -5.250476025520441956e+283 },
HP{ .val = 1.000000e+299, .off = -5.250476025520441750e+282 },
HP{ .val = 1.000000e+298, .off = 4.043379652465702264e+281 },
HP{ .val = 1.000000e+297, .off = -1.765280146275637946e+280 },
HP{ .val = 1.000000e+296, .off = 1.865132227937699609e+279 },
HP{ .val = 1.000000e+295, .off = 1.865132227937699609e+278 },
HP{ .val = 1.000000e+294, .off = -6.643646774124810287e+277 },
HP{ .val = 1.000000e+293, .off = 7.537651562646039934e+276 },
HP{ .val = 1.000000e+292, .off = -1.325659897835741608e+275 },
HP{ .val = 1.000000e+291, .off = 4.213909764965371606e+274 },
HP{ .val = 1.000000e+290, .off = -6.172783352786715670e+273 },
HP{ .val = 1.000000e+289, .off = -6.172783352786715670e+272 },
HP{ .val = 1.000000e+288, .off = -7.630473539575035471e+270 },
HP{ .val = 1.000000e+287, .off = -7.525217352494018700e+270 },
HP{ .val = 1.000000e+286, .off = -3.298861103408696612e+269 },
HP{ .val = 1.000000e+285, .off = 1.984084207947955778e+268 },
HP{ .val = 1.000000e+284, .off = -7.921438250845767591e+267 },
HP{ .val = 1.000000e+283, .off = 4.460464822646386735e+266 },
HP{ .val = 1.000000e+282, .off = -3.278224598286209647e+265 },
HP{ .val = 1.000000e+281, .off = -3.278224598286209737e+264 },
HP{ .val = 1.000000e+280, .off = -3.278224598286209961e+263 },
HP{ .val = 1.000000e+279, .off = -5.797329227496039232e+262 },
HP{ .val = 1.000000e+278, .off = 3.649313132040821498e+261 },
HP{ .val = 1.000000e+277, .off = -2.867878510995372374e+259 },
HP{ .val = 1.000000e+276, .off = -5.206914080024985409e+259 },
HP{ .val = 1.000000e+275, .off = 4.018322599210230404e+258 },
HP{ .val = 1.000000e+274, .off = 7.862171215558236495e+257 },
HP{ .val = 1.000000e+273, .off = 5.459765830340732821e+256 },
HP{ .val = 1.000000e+272, .off = -6.552261095746788047e+255 },
HP{ .val = 1.000000e+271, .off = 4.709014147460262298e+254 },
HP{ .val = 1.000000e+270, .off = -4.675381888545612729e+253 },
HP{ .val = 1.000000e+269, .off = -4.675381888545612892e+252 },
HP{ .val = 1.000000e+268, .off = 2.656177514583977380e+251 },
HP{ .val = 1.000000e+267, .off = 2.656177514583977190e+250 },
HP{ .val = 1.000000e+266, .off = -3.071603269111014892e+249 },
HP{ .val = 1.000000e+265, .off = -6.651466258920385440e+248 },
HP{ .val = 1.000000e+264, .off = -4.414051890289528972e+247 },
HP{ .val = 1.000000e+263, .off = -1.617283929500958387e+246 },
HP{ .val = 1.000000e+262, .off = -1.617283929500958241e+245 },
HP{ .val = 1.000000e+261, .off = 7.122615947963323868e+244 },
HP{ .val = 1.000000e+260, .off = -6.533477610574617382e+243 },
HP{ .val = 1.000000e+259, .off = 7.122615947963323982e+242 },
HP{ .val = 1.000000e+258, .off = -5.679971763165996225e+241 },
HP{ .val = 1.000000e+257, .off = -3.012765990014054219e+240 },
HP{ .val = 1.000000e+256, .off = -3.012765990014054219e+239 },
HP{ .val = 1.000000e+255, .off = 1.154743030535854616e+238 },
HP{ .val = 1.000000e+254, .off = 6.364129306223240767e+237 },
HP{ .val = 1.000000e+253, .off = 6.364129306223241129e+236 },
HP{ .val = 1.000000e+252, .off = -9.915202805299840595e+235 },
HP{ .val = 1.000000e+251, .off = -4.827911520448877980e+234 },
HP{ .val = 1.000000e+250, .off = 7.890316691678530146e+233 },
HP{ .val = 1.000000e+249, .off = 7.890316691678529484e+232 },
HP{ .val = 1.000000e+248, .off = -4.529828046727141859e+231 },
HP{ .val = 1.000000e+247, .off = 4.785280507077111924e+230 },
HP{ .val = 1.000000e+246, .off = -6.858605185178205305e+229 },
HP{ .val = 1.000000e+245, .off = -4.432795665958347728e+228 },
HP{ .val = 1.000000e+244, .off = -7.465057564983169531e+227 },
HP{ .val = 1.000000e+243, .off = -7.465057564983169741e+226 },
HP{ .val = 1.000000e+242, .off = -5.096102956370027445e+225 },
HP{ .val = 1.000000e+241, .off = -5.096102956370026952e+224 },
HP{ .val = 1.000000e+240, .off = -1.394611380411992474e+223 },
HP{ .val = 1.000000e+239, .off = 9.188208545617793960e+221 },
HP{ .val = 1.000000e+238, .off = -4.864759732872650359e+221 },
HP{ .val = 1.000000e+237, .off = 5.979453868566904629e+220 },
HP{ .val = 1.000000e+236, .off = -5.316601966265964857e+219 },
HP{ .val = 1.000000e+235, .off = -5.316601966265964701e+218 },
HP{ .val = 1.000000e+234, .off = -1.786584517880693123e+217 },
HP{ .val = 1.000000e+233, .off = 2.625937292600896716e+216 },
HP{ .val = 1.000000e+232, .off = -5.647541102052084079e+215 },
HP{ .val = 1.000000e+231, .off = -5.647541102052083888e+214 },
HP{ .val = 1.000000e+230, .off = -9.956644432600511943e+213 },
HP{ .val = 1.000000e+229, .off = 8.161138937705571862e+211 },
HP{ .val = 1.000000e+228, .off = 7.549087847752475275e+211 },
HP{ .val = 1.000000e+227, .off = -9.283347037202319948e+210 },
HP{ .val = 1.000000e+226, .off = 3.866992716668613820e+209 },
HP{ .val = 1.000000e+225, .off = 7.154577655136347262e+208 },
HP{ .val = 1.000000e+224, .off = 3.045096482051680688e+207 },
HP{ .val = 1.000000e+223, .off = -4.660180717482069567e+206 },
HP{ .val = 1.000000e+222, .off = -4.660180717482070101e+205 },
HP{ .val = 1.000000e+221, .off = -4.660180717482069544e+204 },
HP{ .val = 1.000000e+220, .off = 3.562757926310489022e+202 },
HP{ .val = 1.000000e+219, .off = 3.491561111451748149e+202 },
HP{ .val = 1.000000e+218, .off = -8.265758834125874135e+201 },
HP{ .val = 1.000000e+217, .off = 3.981449442517482365e+200 },
HP{ .val = 1.000000e+216, .off = -2.142154695804195936e+199 },
HP{ .val = 1.000000e+215, .off = 9.339603063548950188e+198 },
HP{ .val = 1.000000e+214, .off = 4.555537330485139746e+197 },
HP{ .val = 1.000000e+213, .off = 1.565496247320257804e+196 },
HP{ .val = 1.000000e+212, .off = 9.040598955232462036e+195 },
HP{ .val = 1.000000e+211, .off = 4.368659762787334780e+194 },
HP{ .val = 1.000000e+210, .off = 7.288621758065539072e+193 },
HP{ .val = 1.000000e+209, .off = -7.311188218325485628e+192 },
HP{ .val = 1.000000e+208, .off = 1.813693016918905189e+191 },
HP{ .val = 1.000000e+207, .off = -3.889357755108838992e+190 },
HP{ .val = 1.000000e+206, .off = -3.889357755108838992e+189 },
HP{ .val = 1.000000e+205, .off = -1.661603547285501360e+188 },
HP{ .val = 1.000000e+204, .off = 1.123089212493670643e+187 },
HP{ .val = 1.000000e+203, .off = 1.123089212493670643e+186 },
HP{ .val = 1.000000e+202, .off = 9.825254086803583029e+185 },
HP{ .val = 1.000000e+201, .off = -3.771878529305654999e+184 },
HP{ .val = 1.000000e+200, .off = 3.026687778748963675e+183 },
HP{ .val = 1.000000e+199, .off = -9.720624048853446693e+182 },
HP{ .val = 1.000000e+198, .off = -1.753554156601940139e+181 },
HP{ .val = 1.000000e+197, .off = 4.885670753607648963e+180 },
HP{ .val = 1.000000e+196, .off = 4.885670753607648963e+179 },
HP{ .val = 1.000000e+195, .off = 2.292223523057028076e+178 },
HP{ .val = 1.000000e+194, .off = 5.534032561245303825e+177 },
HP{ .val = 1.000000e+193, .off = -6.622751331960730683e+176 },
HP{ .val = 1.000000e+192, .off = -4.090088020876139692e+175 },
HP{ .val = 1.000000e+191, .off = -7.255917159731877552e+174 },
HP{ .val = 1.000000e+190, .off = -7.255917159731877992e+173 },
HP{ .val = 1.000000e+189, .off = -2.309309130269787104e+172 },
HP{ .val = 1.000000e+188, .off = -2.309309130269787019e+171 },
HP{ .val = 1.000000e+187, .off = 9.284303438781988230e+170 },
HP{ .val = 1.000000e+186, .off = 2.038295583124628364e+169 },
HP{ .val = 1.000000e+185, .off = 2.038295583124628532e+168 },
HP{ .val = 1.000000e+184, .off = -1.735666841696912925e+167 },
HP{ .val = 1.000000e+183, .off = 5.340512704843477241e+166 },
HP{ .val = 1.000000e+182, .off = -6.453119872723839321e+165 },
HP{ .val = 1.000000e+181, .off = 8.288920849235306587e+164 },
HP{ .val = 1.000000e+180, .off = -9.248546019891598293e+162 },
HP{ .val = 1.000000e+179, .off = 1.954450226518486016e+162 },
HP{ .val = 1.000000e+178, .off = -5.243811844750628197e+161 },
HP{ .val = 1.000000e+177, .off = -7.448980502074320639e+159 },
HP{ .val = 1.000000e+176, .off = -7.448980502074319858e+158 },
HP{ .val = 1.000000e+175, .off = 6.284654753766312753e+158 },
HP{ .val = 1.000000e+174, .off = -6.895756753684458388e+157 },
HP{ .val = 1.000000e+173, .off = -1.403918625579970616e+156 },
HP{ .val = 1.000000e+172, .off = -8.268716285710580522e+155 },
HP{ .val = 1.000000e+171, .off = 4.602779327034313170e+154 },
HP{ .val = 1.000000e+170, .off = -3.441905430931244940e+153 },
HP{ .val = 1.000000e+169, .off = 6.613950516525702884e+152 },
HP{ .val = 1.000000e+168, .off = 6.613950516525702652e+151 },
HP{ .val = 1.000000e+167, .off = -3.860899428741951187e+150 },
HP{ .val = 1.000000e+166, .off = 5.959272394946474605e+149 },
HP{ .val = 1.000000e+165, .off = 1.005101065481665103e+149 },
HP{ .val = 1.000000e+164, .off = -1.783349948587918355e+146 },
HP{ .val = 1.000000e+163, .off = 6.215006036188360099e+146 },
HP{ .val = 1.000000e+162, .off = 6.215006036188360099e+145 },
HP{ .val = 1.000000e+161, .off = -3.774589324822814903e+144 },
HP{ .val = 1.000000e+160, .off = -6.528407745068226929e+142 },
HP{ .val = 1.000000e+159, .off = 7.151530601283157561e+142 },
HP{ .val = 1.000000e+158, .off = 4.712664546348788765e+141 },
HP{ .val = 1.000000e+157, .off = 1.664081977680827856e+140 },
HP{ .val = 1.000000e+156, .off = 1.664081977680827750e+139 },
HP{ .val = 1.000000e+155, .off = -7.176231540910168265e+137 },
HP{ .val = 1.000000e+154, .off = -3.694754568805822650e+137 },
HP{ .val = 1.000000e+153, .off = 2.665969958768462622e+134 },
HP{ .val = 1.000000e+152, .off = -4.625108135904199522e+135 },
HP{ .val = 1.000000e+151, .off = -1.717753238721771919e+134 },
HP{ .val = 1.000000e+150, .off = 1.916440382756262433e+133 },
HP{ .val = 1.000000e+149, .off = -4.897672657515052040e+132 },
HP{ .val = 1.000000e+148, .off = -4.897672657515052198e+131 },
HP{ .val = 1.000000e+147, .off = 2.200361759434233991e+130 },
HP{ .val = 1.000000e+146, .off = 6.636633270027537273e+129 },
HP{ .val = 1.000000e+145, .off = 1.091293881785907977e+128 },
HP{ .val = 1.000000e+144, .off = -2.374543235865110597e+127 },
HP{ .val = 1.000000e+143, .off = -2.374543235865110537e+126 },
HP{ .val = 1.000000e+142, .off = -5.082228484029969099e+125 },
HP{ .val = 1.000000e+141, .off = -1.697621923823895943e+124 },
HP{ .val = 1.000000e+140, .off = -5.928380124081487212e+123 },
HP{ .val = 1.000000e+139, .off = -3.284156248920492522e+122 },
HP{ .val = 1.000000e+138, .off = -3.284156248920492706e+121 },
HP{ .val = 1.000000e+137, .off = -3.284156248920492476e+120 },
HP{ .val = 1.000000e+136, .off = -5.866406127007401066e+119 },
HP{ .val = 1.000000e+135, .off = 3.817030915818506056e+118 },
HP{ .val = 1.000000e+134, .off = 7.851796350329300951e+117 },
HP{ .val = 1.000000e+133, .off = -2.235117235947686077e+116 },
HP{ .val = 1.000000e+132, .off = 9.170432597638723691e+114 },
HP{ .val = 1.000000e+131, .off = 8.797444499042767883e+114 },
HP{ .val = 1.000000e+130, .off = -5.978307824605161274e+113 },
HP{ .val = 1.000000e+129, .off = 1.782556435814758516e+111 },
HP{ .val = 1.000000e+128, .off = -7.517448691651820362e+111 },
HP{ .val = 1.000000e+127, .off = 4.507089332150205498e+110 },
HP{ .val = 1.000000e+126, .off = 7.513223838100711695e+109 },
HP{ .val = 1.000000e+125, .off = 7.513223838100712113e+108 },
HP{ .val = 1.000000e+124, .off = 5.164681255326878494e+107 },
HP{ .val = 1.000000e+123, .off = 2.229003026859587122e+106 },
HP{ .val = 1.000000e+122, .off = -1.440594758724527399e+105 },
HP{ .val = 1.000000e+121, .off = -3.734093374714598783e+104 },
HP{ .val = 1.000000e+120, .off = 1.999653165260579757e+103 },
HP{ .val = 1.000000e+119, .off = 5.583244752745066693e+102 },
HP{ .val = 1.000000e+118, .off = 3.343500010567262234e+101 },
HP{ .val = 1.000000e+117, .off = -5.055542772599503556e+100 },
HP{ .val = 1.000000e+116, .off = -1.555941612946684331e+99 },
HP{ .val = 1.000000e+115, .off = -1.555941612946684331e+98 },
HP{ .val = 1.000000e+114, .off = -1.555941612946684293e+97 },
HP{ .val = 1.000000e+113, .off = -1.555941612946684246e+96 },
HP{ .val = 1.000000e+112, .off = 6.988006530736955847e+95 },
HP{ .val = 1.000000e+111, .off = 4.318022735835818244e+94 },
HP{ .val = 1.000000e+110, .off = -2.356936751417025578e+93 },
HP{ .val = 1.000000e+109, .off = 1.814912928116001926e+92 },
HP{ .val = 1.000000e+108, .off = -3.399899171300282744e+91 },
HP{ .val = 1.000000e+107, .off = 3.118615952970072913e+90 },
HP{ .val = 1.000000e+106, .off = -9.103599905036843605e+89 },
HP{ .val = 1.000000e+105, .off = 6.174169917471802325e+88 },
HP{ .val = 1.000000e+104, .off = -1.915675085734668657e+86 },
HP{ .val = 1.000000e+103, .off = -1.915675085734668864e+85 },
HP{ .val = 1.000000e+102, .off = 2.295048673475466221e+85 },
HP{ .val = 1.000000e+101, .off = 2.295048673475466135e+84 },
HP{ .val = 1.000000e+100, .off = -1.590289110975991792e+83 },
HP{ .val = 1.000000e+99, .off = 3.266383119588331155e+82 },
HP{ .val = 1.000000e+98, .off = 2.309629754856292029e+80 },
HP{ .val = 1.000000e+97, .off = -7.357587384771124533e+80 },
HP{ .val = 1.000000e+96, .off = -4.986165397190889509e+79 },
HP{ .val = 1.000000e+95, .off = -2.021887912715594741e+78 },
HP{ .val = 1.000000e+94, .off = -2.021887912715594638e+77 },
HP{ .val = 1.000000e+93, .off = -4.337729697461918675e+76 },
HP{ .val = 1.000000e+92, .off = -4.337729697461918997e+75 },
HP{ .val = 1.000000e+91, .off = -7.956232486128049702e+74 },
HP{ .val = 1.000000e+90, .off = 3.351588728453609882e+73 },
HP{ .val = 1.000000e+89, .off = 5.246334248081951113e+71 },
HP{ .val = 1.000000e+88, .off = 4.058327554364963672e+71 },
HP{ .val = 1.000000e+87, .off = 4.058327554364963918e+70 },
HP{ .val = 1.000000e+86, .off = -1.463069523067487266e+69 },
HP{ .val = 1.000000e+85, .off = -1.463069523067487314e+68 },
HP{ .val = 1.000000e+84, .off = -5.776660989811589441e+67 },
HP{ .val = 1.000000e+83, .off = -3.080666323096525761e+66 },
HP{ .val = 1.000000e+82, .off = 3.659320343691134468e+65 },
HP{ .val = 1.000000e+81, .off = 7.871812010433421235e+64 },
HP{ .val = 1.000000e+80, .off = -2.660986470836727449e+61 },
HP{ .val = 1.000000e+79, .off = 3.264399249934044627e+62 },
HP{ .val = 1.000000e+78, .off = -8.493621433689703070e+60 },
HP{ .val = 1.000000e+77, .off = 1.721738727445414063e+60 },
HP{ .val = 1.000000e+76, .off = -4.706013449590547218e+59 },
HP{ .val = 1.000000e+75, .off = 7.346021882351880518e+58 },
HP{ .val = 1.000000e+74, .off = 4.835181188197207515e+57 },
HP{ .val = 1.000000e+73, .off = 1.696630320503867482e+56 },
HP{ .val = 1.000000e+72, .off = 5.619818905120542959e+55 },
HP{ .val = 1.000000e+71, .off = -4.188152556421145598e+54 },
HP{ .val = 1.000000e+70, .off = -7.253143638152923145e+53 },
HP{ .val = 1.000000e+69, .off = -7.253143638152923145e+52 },
HP{ .val = 1.000000e+68, .off = 4.719477774861832896e+51 },
HP{ .val = 1.000000e+67, .off = 1.726322421608144052e+50 },
HP{ .val = 1.000000e+66, .off = 5.467766613175255107e+49 },
HP{ .val = 1.000000e+65, .off = 7.909613737163661911e+47 },
HP{ .val = 1.000000e+64, .off = -2.132041900945439564e+47 },
HP{ .val = 1.000000e+63, .off = -5.785795994272697265e+46 },
HP{ .val = 1.000000e+62, .off = -3.502199685943161329e+45 },
HP{ .val = 1.000000e+61, .off = 5.061286470292598274e+44 },
HP{ .val = 1.000000e+60, .off = 5.061286470292598472e+43 },
HP{ .val = 1.000000e+59, .off = 2.831211950439536034e+42 },
HP{ .val = 1.000000e+58, .off = 5.618805100255863927e+41 },
HP{ .val = 1.000000e+57, .off = -4.834669211555366251e+40 },
HP{ .val = 1.000000e+56, .off = -9.190283508143378583e+39 },
HP{ .val = 1.000000e+55, .off = -1.023506702040855158e+38 },
HP{ .val = 1.000000e+54, .off = -7.829154040459624616e+37 },
HP{ .val = 1.000000e+53, .off = 6.779051325638372659e+35 },
HP{ .val = 1.000000e+52, .off = 6.779051325638372290e+34 },
HP{ .val = 1.000000e+51, .off = 6.779051325638371598e+33 },
HP{ .val = 1.000000e+50, .off = -7.629769841091887392e+33 },
HP{ .val = 1.000000e+49, .off = 5.350972305245182400e+32 },
HP{ .val = 1.000000e+48, .off = -4.384584304507619764e+31 },
HP{ .val = 1.000000e+47, .off = -4.384584304507619876e+30 },
HP{ .val = 1.000000e+46, .off = 6.860180964052978705e+28 },
HP{ .val = 1.000000e+45, .off = 7.024271097546444878e+28 },
HP{ .val = 1.000000e+44, .off = -8.821361405306422641e+27 },
HP{ .val = 1.000000e+43, .off = -1.393721169594140991e+26 },
HP{ .val = 1.000000e+42, .off = -4.488571267807591679e+25 },
HP{ .val = 1.000000e+41, .off = -6.200086450407783195e+23 },
HP{ .val = 1.000000e+40, .off = -3.037860284270036669e+23 },
HP{ .val = 1.000000e+39, .off = 6.029083362839682141e+22 },
HP{ .val = 1.000000e+38, .off = 2.251190176543965970e+21 },
HP{ .val = 1.000000e+37, .off = 4.612373417978788577e+20 },
HP{ .val = 1.000000e+36, .off = -4.242063737401796198e+19 },
HP{ .val = 1.000000e+35, .off = 3.136633892082024448e+18 },
HP{ .val = 1.000000e+34, .off = 5.442476901295718400e+17 },
HP{ .val = 1.000000e+33, .off = 5.442476901295718400e+16 },
HP{ .val = 1.000000e+32, .off = -5.366162204393472000e+15 },
HP{ .val = 1.000000e+31, .off = 3.641037050347520000e+14 },
HP{ .val = 1.000000e+30, .off = -1.988462483865600000e+13 },
HP{ .val = 1.000000e+29, .off = 8.566849142784000000e+12 },
HP{ .val = 1.000000e+28, .off = 4.168802631680000000e+11 },
HP{ .val = 1.000000e+27, .off = -1.328755507200000000e+10 },
HP{ .val = 1.000000e+26, .off = -4.764729344000000000e+09 },
HP{ .val = 1.000000e+25, .off = -9.059696640000000000e+08 },
HP{ .val = 1.000000e+24, .off = 1.677721600000000000e+07 },
HP{ .val = 1.000000e+23, .off = 8.388608000000000000e+06 },
HP{ .val = 1.000000e+22, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+21, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+20, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+19, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+18, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+17, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+16, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+15, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+14, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+13, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+12, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+11, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+10, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+09, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+08, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+07, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+06, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+05, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+04, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+03, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+02, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+01, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e+00, .off = 0.000000000000000000e+00 },
HP{ .val = 1.000000e-01, .off = -5.551115123125783010e-18 },
HP{ .val = 1.000000e-02, .off = -2.081668171172168436e-19 },
HP{ .val = 1.000000e-03, .off = -2.081668171172168557e-20 },
HP{ .val = 1.000000e-04, .off = -4.792173602385929943e-21 },
HP{ .val = 1.000000e-05, .off = -8.180305391403130547e-22 },
HP{ .val = 1.000000e-06, .off = 4.525188817411374069e-23 },
HP{ .val = 1.000000e-07, .off = 4.525188817411373922e-24 },
HP{ .val = 1.000000e-08, .off = -2.092256083012847109e-25 },
HP{ .val = 1.000000e-09, .off = -6.228159145777985254e-26 },
HP{ .val = 1.000000e-10, .off = -3.643219731549774344e-27 },
HP{ .val = 1.000000e-11, .off = 6.050303071806019080e-28 },
HP{ .val = 1.000000e-12, .off = 2.011335237074438524e-29 },
HP{ .val = 1.000000e-13, .off = -3.037374556340037101e-30 },
HP{ .val = 1.000000e-14, .off = 1.180690645440101289e-32 },
HP{ .val = 1.000000e-15, .off = -7.770539987666107583e-32 },
HP{ .val = 1.000000e-16, .off = 2.090221327596539779e-33 },
HP{ .val = 1.000000e-17, .off = -7.154242405462192144e-34 },
HP{ .val = 1.000000e-18, .off = -7.154242405462192572e-35 },
HP{ .val = 1.000000e-19, .off = 2.475407316473986894e-36 },
HP{ .val = 1.000000e-20, .off = 5.484672854579042914e-37 },
HP{ .val = 1.000000e-21, .off = 9.246254777210362522e-38 },
HP{ .val = 1.000000e-22, .off = -4.859677432657087182e-39 },
HP{ .val = 1.000000e-23, .off = 3.956530198510069291e-40 },
HP{ .val = 1.000000e-24, .off = 7.629950044829717753e-41 },
HP{ .val = 1.000000e-25, .off = -3.849486974919183692e-42 },
HP{ .val = 1.000000e-26, .off = -3.849486974919184170e-43 },
HP{ .val = 1.000000e-27, .off = -3.849486974919184070e-44 },
HP{ .val = 1.000000e-28, .off = 2.876745653839937870e-45 },
HP{ .val = 1.000000e-29, .off = 5.679342582489572168e-46 },
HP{ .val = 1.000000e-30, .off = -8.333642060758598930e-47 },
HP{ .val = 1.000000e-31, .off = -8.333642060758597958e-48 },
HP{ .val = 1.000000e-32, .off = -5.596730997624190224e-49 },
HP{ .val = 1.000000e-33, .off = -5.596730997624190604e-50 },
HP{ .val = 1.000000e-34, .off = 7.232539610818348498e-51 },
HP{ .val = 1.000000e-35, .off = -7.857545194582380514e-53 },
HP{ .val = 1.000000e-36, .off = 5.896157255772251528e-53 },
HP{ .val = 1.000000e-37, .off = -6.632427322784915796e-54 },
HP{ .val = 1.000000e-38, .off = 3.808059826012723592e-55 },
HP{ .val = 1.000000e-39, .off = 7.070712060011985131e-56 },
HP{ .val = 1.000000e-40, .off = 7.070712060011985584e-57 },
HP{ .val = 1.000000e-41, .off = -5.761291134237854167e-59 },
HP{ .val = 1.000000e-42, .off = -3.762312935688689794e-59 },
HP{ .val = 1.000000e-43, .off = -7.745042713519821150e-60 },
HP{ .val = 1.000000e-44, .off = 4.700987842202462817e-61 },
HP{ .val = 1.000000e-45, .off = 1.589480203271891964e-62 },
HP{ .val = 1.000000e-46, .off = -2.299904345391321765e-63 },
HP{ .val = 1.000000e-47, .off = 2.561826340437695261e-64 },
HP{ .val = 1.000000e-48, .off = 2.561826340437695345e-65 },
HP{ .val = 1.000000e-49, .off = 6.360053438741614633e-66 },
HP{ .val = 1.000000e-50, .off = -7.616223705782342295e-68 },
HP{ .val = 1.000000e-51, .off = -7.616223705782343324e-69 },
HP{ .val = 1.000000e-52, .off = -7.616223705782342295e-70 },
HP{ .val = 1.000000e-53, .off = -3.079876214757872338e-70 },
HP{ .val = 1.000000e-54, .off = -3.079876214757872821e-71 },
HP{ .val = 1.000000e-55, .off = 5.423954167728123147e-73 },
HP{ .val = 1.000000e-56, .off = -3.985444122640543680e-73 },
HP{ .val = 1.000000e-57, .off = 4.504255013759498850e-74 },
HP{ .val = 1.000000e-58, .off = -2.570494266573869991e-75 },
HP{ .val = 1.000000e-59, .off = -2.570494266573869930e-76 },
HP{ .val = 1.000000e-60, .off = 2.956653608686574324e-77 },
HP{ .val = 1.000000e-61, .off = -3.952281235388981376e-78 },
HP{ .val = 1.000000e-62, .off = -3.952281235388981376e-79 },
HP{ .val = 1.000000e-63, .off = -6.651083908855995172e-80 },
HP{ .val = 1.000000e-64, .off = 3.469426116645307030e-81 },
HP{ .val = 1.000000e-65, .off = 7.686305293937516319e-82 },
HP{ .val = 1.000000e-66, .off = 2.415206322322254927e-83 },
HP{ .val = 1.000000e-67, .off = 5.709643179581793251e-84 },
HP{ .val = 1.000000e-68, .off = -6.644495035141475923e-85 },
HP{ .val = 1.000000e-69, .off = 3.650620143794581913e-86 },
HP{ .val = 1.000000e-70, .off = 4.333966503770636492e-88 },
HP{ .val = 1.000000e-71, .off = 8.476455383920859113e-88 },
HP{ .val = 1.000000e-72, .off = 3.449543675455986564e-89 },
HP{ .val = 1.000000e-73, .off = 3.077238576654418974e-91 },
HP{ .val = 1.000000e-74, .off = 4.234998629903623140e-91 },
HP{ .val = 1.000000e-75, .off = 4.234998629903623412e-92 },
HP{ .val = 1.000000e-76, .off = 7.303182045714702338e-93 },
HP{ .val = 1.000000e-77, .off = 7.303182045714701699e-94 },
HP{ .val = 1.000000e-78, .off = 1.121271649074855759e-96 },
HP{ .val = 1.000000e-79, .off = 1.121271649074855863e-97 },
HP{ .val = 1.000000e-80, .off = 3.857468248661243988e-97 },
HP{ .val = 1.000000e-81, .off = 3.857468248661244248e-98 },
HP{ .val = 1.000000e-82, .off = 3.857468248661244410e-99 },
HP{ .val = 1.000000e-83, .off = -3.457651055545315679e-100 },
HP{ .val = 1.000000e-84, .off = -3.457651055545315933e-101 },
HP{ .val = 1.000000e-85, .off = 2.257285900866059216e-102 },
HP{ .val = 1.000000e-86, .off = -8.458220892405268345e-103 },
HP{ .val = 1.000000e-87, .off = -1.761029146610688867e-104 },
HP{ .val = 1.000000e-88, .off = 6.610460535632536565e-105 },
HP{ .val = 1.000000e-89, .off = -3.853901567171494935e-106 },
HP{ .val = 1.000000e-90, .off = 5.062493089968513723e-108 },
HP{ .val = 1.000000e-91, .off = -2.218844988608365240e-108 },
HP{ .val = 1.000000e-92, .off = 1.187522883398155383e-109 },
HP{ .val = 1.000000e-93, .off = 9.703442563414457296e-110 },
HP{ .val = 1.000000e-94, .off = 4.380992763404268896e-111 },
HP{ .val = 1.000000e-95, .off = 1.054461638397900823e-112 },
HP{ .val = 1.000000e-96, .off = 9.370789450913819736e-113 },
HP{ .val = 1.000000e-97, .off = -3.623472756142303998e-114 },
HP{ .val = 1.000000e-98, .off = 6.122223899149788839e-115 },
HP{ .val = 1.000000e-99, .off = -1.999189980260288281e-116 },
HP{ .val = 1.000000e-100, .off = -1.999189980260288281e-117 },
HP{ .val = 1.000000e-101, .off = -5.171617276904849634e-118 },
HP{ .val = 1.000000e-102, .off = 6.724985085512256320e-119 },
HP{ .val = 1.000000e-103, .off = 4.246526260008692213e-120 },
HP{ .val = 1.000000e-104, .off = 7.344599791888147003e-121 },
HP{ .val = 1.000000e-105, .off = 3.472007877038828407e-122 },
HP{ .val = 1.000000e-106, .off = 5.892377823819652194e-123 },
HP{ .val = 1.000000e-107, .off = -1.585470431324073925e-125 },
HP{ .val = 1.000000e-108, .off = -3.940375084977444795e-125 },
HP{ .val = 1.000000e-109, .off = 7.869099673288519908e-127 },
HP{ .val = 1.000000e-110, .off = -5.122196348054018581e-127 },
HP{ .val = 1.000000e-111, .off = -8.815387795168313713e-128 },
HP{ .val = 1.000000e-112, .off = 5.034080131510290214e-129 },
HP{ .val = 1.000000e-113, .off = 2.148774313452247863e-130 },
HP{ .val = 1.000000e-114, .off = -5.064490231692858416e-131 },
HP{ .val = 1.000000e-115, .off = -5.064490231692858166e-132 },
HP{ .val = 1.000000e-116, .off = 5.708726942017560559e-134 },
HP{ .val = 1.000000e-117, .off = -2.951229134482377772e-134 },
HP{ .val = 1.000000e-118, .off = 1.451398151372789513e-135 },
HP{ .val = 1.000000e-119, .off = -1.300243902286690040e-136 },
HP{ .val = 1.000000e-120, .off = 2.139308664787659449e-137 },
HP{ .val = 1.000000e-121, .off = 2.139308664787659329e-138 },
HP{ .val = 1.000000e-122, .off = -5.922142664292847471e-139 },
HP{ .val = 1.000000e-123, .off = -5.922142664292846912e-140 },
HP{ .val = 1.000000e-124, .off = 6.673875037395443799e-141 },
HP{ .val = 1.000000e-125, .off = -1.198636026159737932e-142 },
HP{ .val = 1.000000e-126, .off = 5.361789860136246995e-143 },
HP{ .val = 1.000000e-127, .off = -2.838742497733733936e-144 },
HP{ .val = 1.000000e-128, .off = -5.401408859568103261e-145 },
HP{ .val = 1.000000e-129, .off = 7.411922949603743011e-146 },
HP{ .val = 1.000000e-130, .off = -8.604741811861064385e-147 },
HP{ .val = 1.000000e-131, .off = 1.405673664054439890e-148 },
HP{ .val = 1.000000e-132, .off = 1.405673664054439933e-149 },
HP{ .val = 1.000000e-133, .off = -6.414963426504548053e-150 },
HP{ .val = 1.000000e-134, .off = -3.971014335704864578e-151 },
HP{ .val = 1.000000e-135, .off = -3.971014335704864748e-152 },
HP{ .val = 1.000000e-136, .off = -1.523438813303585576e-154 },
HP{ .val = 1.000000e-137, .off = 2.234325152653707766e-154 },
HP{ .val = 1.000000e-138, .off = -6.715683724786540160e-155 },
HP{ .val = 1.000000e-139, .off = -2.986513359186437306e-156 },
HP{ .val = 1.000000e-140, .off = 1.674949597813692102e-157 },
HP{ .val = 1.000000e-141, .off = -4.151879098436469092e-158 },
HP{ .val = 1.000000e-142, .off = -4.151879098436469295e-159 },
HP{ .val = 1.000000e-143, .off = 4.952540739454407825e-160 },
HP{ .val = 1.000000e-144, .off = 4.952540739454407667e-161 },
HP{ .val = 1.000000e-145, .off = 8.508954738630531443e-162 },
HP{ .val = 1.000000e-146, .off = -2.604839008794855481e-163 },
HP{ .val = 1.000000e-147, .off = 2.952057864917838382e-164 },
HP{ .val = 1.000000e-148, .off = 6.425118410988271757e-165 },
HP{ .val = 1.000000e-149, .off = 2.083792728400229858e-166 },
HP{ .val = 1.000000e-150, .off = -6.295358232172964237e-168 },
HP{ .val = 1.000000e-151, .off = 6.153785555826519421e-168 },
HP{ .val = 1.000000e-152, .off = -6.564942029880634994e-169 },
HP{ .val = 1.000000e-153, .off = -3.915207116191644540e-170 },
HP{ .val = 1.000000e-154, .off = 2.709130168030831503e-171 },
HP{ .val = 1.000000e-155, .off = -1.431080634608215966e-172 },
HP{ .val = 1.000000e-156, .off = -4.018712386257620994e-173 },
HP{ .val = 1.000000e-157, .off = 5.684906682427646782e-174 },
HP{ .val = 1.000000e-158, .off = -6.444617153428937489e-175 },
HP{ .val = 1.000000e-159, .off = 1.136335243981427681e-176 },
HP{ .val = 1.000000e-160, .off = 1.136335243981427725e-177 },
HP{ .val = 1.000000e-161, .off = -2.812077463003137395e-178 },
HP{ .val = 1.000000e-162, .off = 4.591196362592922204e-179 },
HP{ .val = 1.000000e-163, .off = 7.675893789924613703e-180 },
HP{ .val = 1.000000e-164, .off = 3.820022005759999543e-181 },
HP{ .val = 1.000000e-165, .off = -9.998177244457686588e-183 },
HP{ .val = 1.000000e-166, .off = -4.012217555824373639e-183 },
HP{ .val = 1.000000e-167, .off = -2.467177666011174334e-185 },
HP{ .val = 1.000000e-168, .off = -4.953592503130188139e-185 },
HP{ .val = 1.000000e-169, .off = -2.011795792799518887e-186 },
HP{ .val = 1.000000e-170, .off = 1.665450095113817423e-187 },
HP{ .val = 1.000000e-171, .off = 1.665450095113817487e-188 },
HP{ .val = 1.000000e-172, .off = -4.080246604750770577e-189 },
HP{ .val = 1.000000e-173, .off = -4.080246604750770677e-190 },
HP{ .val = 1.000000e-174, .off = 4.085789420184387951e-192 },
HP{ .val = 1.000000e-175, .off = 4.085789420184388146e-193 },
HP{ .val = 1.000000e-176, .off = 4.085789420184388146e-194 },
HP{ .val = 1.000000e-177, .off = 4.792197640035244894e-194 },
HP{ .val = 1.000000e-178, .off = 4.792197640035244742e-195 },
HP{ .val = 1.000000e-179, .off = -2.057206575616014662e-196 },
HP{ .val = 1.000000e-180, .off = -2.057206575616014662e-197 },
HP{ .val = 1.000000e-181, .off = -4.732755097354788053e-198 },
HP{ .val = 1.000000e-182, .off = -4.732755097354787867e-199 },
HP{ .val = 1.000000e-183, .off = -5.522105321379546765e-201 },
HP{ .val = 1.000000e-184, .off = -5.777891238658996019e-201 },
HP{ .val = 1.000000e-185, .off = 7.542096444923057046e-203 },
HP{ .val = 1.000000e-186, .off = 8.919335748431433483e-203 },
HP{ .val = 1.000000e-187, .off = -1.287071881492476028e-204 },
HP{ .val = 1.000000e-188, .off = 5.091932887209967018e-205 },
HP{ .val = 1.000000e-189, .off = -6.868701054107114024e-206 },
HP{ .val = 1.000000e-190, .off = -1.885103578558330118e-207 },
HP{ .val = 1.000000e-191, .off = -1.885103578558330205e-208 },
HP{ .val = 1.000000e-192, .off = -9.671974634103305058e-209 },
HP{ .val = 1.000000e-193, .off = -4.805180224387695640e-210 },
HP{ .val = 1.000000e-194, .off = -1.763433718315439838e-211 },
HP{ .val = 1.000000e-195, .off = -9.367799983496079132e-212 },
HP{ .val = 1.000000e-196, .off = -4.615071067758179837e-213 },
HP{ .val = 1.000000e-197, .off = 1.325840076914194777e-214 },
HP{ .val = 1.000000e-198, .off = 8.751979007754662425e-215 },
HP{ .val = 1.000000e-199, .off = 1.789973760091724198e-216 },
HP{ .val = 1.000000e-200, .off = 1.789973760091724077e-217 },
HP{ .val = 1.000000e-201, .off = 5.416018159916171171e-218 },
HP{ .val = 1.000000e-202, .off = -3.649092839644947067e-219 },
HP{ .val = 1.000000e-203, .off = -3.649092839644947067e-220 },
HP{ .val = 1.000000e-204, .off = -1.080338554413850956e-222 },
HP{ .val = 1.000000e-205, .off = -1.080338554413850841e-223 },
HP{ .val = 1.000000e-206, .off = -2.874486186850417807e-223 },
HP{ .val = 1.000000e-207, .off = 7.499710055933455072e-224 },
HP{ .val = 1.000000e-208, .off = -9.790617015372999087e-225 },
HP{ .val = 1.000000e-209, .off = -4.387389805589732612e-226 },
HP{ .val = 1.000000e-210, .off = -4.387389805589732612e-227 },
HP{ .val = 1.000000e-211, .off = -8.608661063232909897e-228 },
HP{ .val = 1.000000e-212, .off = 4.582811616902018972e-229 },
HP{ .val = 1.000000e-213, .off = 4.582811616902019155e-230 },
HP{ .val = 1.000000e-214, .off = 8.705146829444184930e-231 },
HP{ .val = 1.000000e-215, .off = -4.177150709750081830e-232 },
HP{ .val = 1.000000e-216, .off = -4.177150709750082366e-233 },
HP{ .val = 1.000000e-217, .off = -8.202868690748290237e-234 },
HP{ .val = 1.000000e-218, .off = -3.170721214500530119e-235 },
HP{ .val = 1.000000e-219, .off = -3.170721214500529857e-236 },
HP{ .val = 1.000000e-220, .off = 7.606440013180328441e-238 },
HP{ .val = 1.000000e-221, .off = -1.696459258568569049e-238 },
HP{ .val = 1.000000e-222, .off = -4.767838333426821244e-239 },
HP{ .val = 1.000000e-223, .off = 2.910609353718809138e-240 },
HP{ .val = 1.000000e-224, .off = -1.888420450747209784e-241 },
HP{ .val = 1.000000e-225, .off = 4.110366804835314035e-242 },
HP{ .val = 1.000000e-226, .off = 7.859608839574391006e-243 },
HP{ .val = 1.000000e-227, .off = 5.516332567862468419e-244 },
HP{ .val = 1.000000e-228, .off = -3.270953451057244613e-245 },
HP{ .val = 1.000000e-229, .off = -6.932322625607124670e-246 },
HP{ .val = 1.000000e-230, .off = -4.643966891513449762e-247 },
HP{ .val = 1.000000e-231, .off = 1.076922443720738305e-248 },
HP{ .val = 1.000000e-232, .off = -2.498633390800628939e-249 },
HP{ .val = 1.000000e-233, .off = 4.205533798926934891e-250 },
HP{ .val = 1.000000e-234, .off = 4.205533798926934891e-251 },
HP{ .val = 1.000000e-235, .off = 4.205533798926934697e-252 },
HP{ .val = 1.000000e-236, .off = -4.523850562697497656e-253 },
HP{ .val = 1.000000e-237, .off = 9.320146633177728298e-255 },
HP{ .val = 1.000000e-238, .off = 9.320146633177728062e-256 },
HP{ .val = 1.000000e-239, .off = -7.592774752331086440e-256 },
HP{ .val = 1.000000e-240, .off = 3.063212017229987840e-257 },
HP{ .val = 1.000000e-241, .off = 3.063212017229987562e-258 },
HP{ .val = 1.000000e-242, .off = 3.063212017229987562e-259 },
HP{ .val = 1.000000e-243, .off = 4.616527473176159842e-261 },
HP{ .val = 1.000000e-244, .off = 6.965550922098544975e-261 },
HP{ .val = 1.000000e-245, .off = 6.965550922098544749e-262 },
HP{ .val = 1.000000e-246, .off = 4.424965697574744679e-263 },
HP{ .val = 1.000000e-247, .off = -1.926497363734756420e-264 },
HP{ .val = 1.000000e-248, .off = 2.043167049583681740e-265 },
HP{ .val = 1.000000e-249, .off = -5.399953725388390154e-266 },
HP{ .val = 1.000000e-250, .off = -5.399953725388389982e-267 },
HP{ .val = 1.000000e-251, .off = -1.523328321757102663e-268 },
HP{ .val = 1.000000e-252, .off = 5.745344310051561161e-269 },
HP{ .val = 1.000000e-253, .off = -6.369110076296211879e-270 },
HP{ .val = 1.000000e-254, .off = 8.773957906638504842e-271 },
HP{ .val = 1.000000e-255, .off = -6.904595826956931908e-273 },
HP{ .val = 1.000000e-256, .off = 2.267170882721243669e-273 },
HP{ .val = 1.000000e-257, .off = 2.267170882721243669e-274 },
HP{ .val = 1.000000e-258, .off = 4.577819683828225398e-275 },
HP{ .val = 1.000000e-259, .off = -6.975424321706684210e-276 },
HP{ .val = 1.000000e-260, .off = 3.855741933482293648e-277 },
HP{ .val = 1.000000e-261, .off = 1.599248963651256552e-278 },
HP{ .val = 1.000000e-262, .off = -1.221367248637539543e-279 },
HP{ .val = 1.000000e-263, .off = -1.221367248637539494e-280 },
HP{ .val = 1.000000e-264, .off = -1.221367248637539647e-281 },
HP{ .val = 1.000000e-265, .off = 1.533140771175737943e-282 },
HP{ .val = 1.000000e-266, .off = 1.533140771175737895e-283 },
HP{ .val = 1.000000e-267, .off = 1.533140771175738074e-284 },
HP{ .val = 1.000000e-268, .off = 4.223090009274641634e-285 },
HP{ .val = 1.000000e-269, .off = 4.223090009274641634e-286 },
HP{ .val = 1.000000e-270, .off = -4.183001359784432924e-287 },
HP{ .val = 1.000000e-271, .off = 3.697709298708449474e-288 },
HP{ .val = 1.000000e-272, .off = 6.981338739747150474e-289 },
HP{ .val = 1.000000e-273, .off = -9.436808465446354751e-290 },
HP{ .val = 1.000000e-274, .off = 3.389869038611071740e-291 },
HP{ .val = 1.000000e-275, .off = 6.596538414625427829e-292 },
HP{ .val = 1.000000e-276, .off = -9.436808465446354618e-293 },
HP{ .val = 1.000000e-277, .off = 3.089243784609725523e-294 },
HP{ .val = 1.000000e-278, .off = 6.220756847123745836e-295 },
HP{ .val = 1.000000e-279, .off = -5.522417137303829470e-296 },
HP{ .val = 1.000000e-280, .off = 4.263561183052483059e-297 },
HP{ .val = 1.000000e-281, .off = -1.852675267170212272e-298 },
HP{ .val = 1.000000e-282, .off = -1.852675267170212378e-299 },
HP{ .val = 1.000000e-283, .off = 5.314789322934508480e-300 },
HP{ .val = 1.000000e-284, .off = -3.644541414696392675e-301 },
HP{ .val = 1.000000e-285, .off = -7.377595888709267777e-302 },
HP{ .val = 1.000000e-286, .off = -5.044436842451220838e-303 },
HP{ .val = 1.000000e-287, .off = -2.127988034628661760e-304 },
HP{ .val = 1.000000e-288, .off = -5.773549044406860911e-305 },
HP{ .val = 1.000000e-289, .off = -1.216597782184112068e-306 },
HP{ .val = 1.000000e-290, .off = -6.912786859962547924e-307 },
HP{ .val = 1.000000e-291, .off = 3.767567660872018813e-308 },
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/rwlock.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Loop = std.event.Loop;
const Allocator = std.mem.Allocator;
/// Thread-safe async/await lock.
/// Functions which are waiting for the lock are suspended, and
/// are resumed when the lock is released, in order.
/// Many readers can hold the lock at the same time; however locking for writing is exclusive.
/// When a read lock is held, it will not be released until the reader queue is empty.
/// When a write lock is held, it will not be released until the writer queue is empty.
/// TODO: make this API also work in blocking I/O mode
pub const RwLock = struct {
shared_state: State,
writer_queue: Queue,
reader_queue: Queue,
writer_queue_empty: bool,
reader_queue_empty: bool,
reader_lock_count: usize,
const State = enum(u8) {
Unlocked,
WriteLock,
ReadLock,
};
const Queue = std.atomic.Queue(anyframe);
const global_event_loop = Loop.instance orelse
@compileError("std.event.RwLock currently only works with event-based I/O");
pub const HeldRead = struct {
lock: *RwLock,
pub fn release(self: HeldRead) void {
// If other readers still hold the lock, we're done.
if (@atomicRmw(usize, &self.lock.reader_lock_count, .Sub, 1, .SeqCst) != 1) {
return;
}
@atomicStore(bool, &self.lock.reader_queue_empty, true, .SeqCst);
if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
self.lock.commonPostUnlock();
}
};
pub const HeldWrite = struct {
lock: *RwLock,
pub fn release(self: HeldWrite) void {
// See if we can leave it locked for writing, and pass the lock to the next writer
// in the queue to grab the lock.
if (self.lock.writer_queue.get()) |node| {
global_event_loop.onNextTick(node);
return;
}
// We need to release the write lock. Check if any readers are waiting to grab the lock.
if (!@atomicLoad(bool, &self.lock.reader_queue_empty, .SeqCst)) {
// Switch to a read lock.
@atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);
while (self.lock.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
return;
}
@atomicStore(bool, &self.lock.writer_queue_empty, true, .SeqCst);
@atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);
self.lock.commonPostUnlock();
}
};
pub fn init() RwLock {
return .{
.shared_state = .Unlocked,
.writer_queue = Queue.init(),
.writer_queue_empty = true,
.reader_queue = Queue.init(),
.reader_queue_empty = true,
.reader_lock_count = 0,
};
}
/// Must be called when not locked. Not thread safe.
/// All calls to acquire() and release() must complete before calling deinit().
pub fn deinit(self: *RwLock) void {
assert(self.shared_state == .Unlocked);
while (self.writer_queue.get()) |node| resume node.data;
while (self.reader_queue.get()) |node| resume node.data;
}
pub fn acquireRead(self: *RwLock) callconv(.Async) HeldRead {
_ = @atomicRmw(usize, &self.reader_lock_count, .Add, 1, .SeqCst);
suspend {
var my_tick_node = Loop.NextTickNode{
.data = @frame(),
.prev = undefined,
.next = undefined,
};
self.reader_queue.put(&my_tick_node);
// At this point, we are in the reader_queue, so we might have already been resumed.
// We set this bit so that later we can rely on the fact, that if reader_queue_empty == true,
// some actor will attempt to grab the lock.
@atomicStore(bool, &self.reader_queue_empty, false, .SeqCst);
// Here we don't care if we are the one to do the locking or if it was already locked for reading.
const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true;
if (have_read_lock) {
// Give out all the read locks.
if (self.reader_queue.get()) |first_node| {
while (self.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
resume first_node.data;
}
}
}
return HeldRead{ .lock = self };
}
pub fn acquireWrite(self: *RwLock) callconv(.Async) HeldWrite {
suspend {
var my_tick_node = Loop.NextTickNode{
.data = @frame(),
.prev = undefined,
.next = undefined,
};
self.writer_queue.put(&my_tick_node);
// At this point, we are in the writer_queue, so we might have already been resumed.
// We set this bit so that later we can rely on the fact, that if writer_queue_empty == true,
// some actor will attempt to grab the lock.
@atomicStore(bool, &self.writer_queue_empty, false, .SeqCst);
// Here we must be the one to acquire the write lock. It cannot already be locked.
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {
// We now have a write lock.
if (self.writer_queue.get()) |node| {
// Whether this node is us or someone else, we tail resume it.
resume node.data;
}
}
}
return HeldWrite{ .lock = self };
}
fn commonPostUnlock(self: *RwLock) void {
while (true) {
// There might be a writer_queue item or a reader_queue item
// If we check and both are empty, we can be done, because the other actors will try to
// obtain the lock.
// But if there's a writer_queue item or a reader_queue item,
// we are the actor which must loop and attempt to grab the lock again.
if (!@atomicLoad(bool, &self.writer_queue_empty, .SeqCst)) {
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
// If there's an item in the writer queue, give them the lock, and we're done.
if (self.writer_queue.get()) |node| {
global_event_loop.onNextTick(node);
return;
}
// Release the lock again.
@atomicStore(bool, &self.writer_queue_empty, true, .SeqCst);
@atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);
continue;
}
if (!@atomicLoad(bool, &self.reader_queue_empty, .SeqCst)) {
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
// If there are any items in the reader queue, give out all the reader locks, and we're done.
if (self.reader_queue.get()) |first_node| {
global_event_loop.onNextTick(first_node);
while (self.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
return;
}
// Release the lock again.
@atomicStore(bool, &self.reader_queue_empty, true, .SeqCst);
if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
continue;
}
return;
}
}
};
test "std.event.RwLock" {
// https://github.com/ziglang/zig/issues/2377
if (true) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// TODO provide a way to run tests in evented I/O mode
if (!std.io.is_async) return error.SkipZigTest;
var lock = RwLock.init();
defer lock.deinit();
_ = testLock(std.heap.page_allocator, &lock);
const expected_result = [1]i32{shared_it_count * @as(i32, @intCast(shared_test_data.len))} ** shared_test_data.len;
try testing.expectEqualSlices(i32, expected_result, shared_test_data);
}
fn testLock(allocator: *Allocator, lock: *RwLock) callconv(.Async) void {
var read_nodes: [100]Loop.NextTickNode = undefined;
for (read_nodes) |*read_node| {
const frame = allocator.create(@Frame(readRunner)) catch @panic("memory");
read_node.data = frame;
frame.* = async readRunner(lock);
Loop.instance.?.onNextTick(read_node);
}
var write_nodes: [shared_it_count]Loop.NextTickNode = undefined;
for (write_nodes) |*write_node| {
const frame = allocator.create(@Frame(writeRunner)) catch @panic("memory");
write_node.data = frame;
frame.* = async writeRunner(lock);
Loop.instance.?.onNextTick(write_node);
}
for (write_nodes) |*write_node| {
const casted = @as(*const @Frame(writeRunner), @ptrCast(write_node.data));
await casted;
allocator.destroy(casted);
}
for (read_nodes) |*read_node| {
const casted = @as(*const @Frame(readRunner), @ptrCast(read_node.data));
await casted;
allocator.destroy(casted);
}
}
const shared_it_count = 10;
var shared_test_data = [1]i32{0} ** 10;
var shared_test_index: usize = 0;
var shared_count: usize = 0;
fn writeRunner(lock: *RwLock) callconv(.Async) void {
suspend {} // resumed by onNextTick
var i: usize = 0;
while (i < shared_test_data.len) : (i += 1) {
std.time.sleep(100 * std.time.microsecond);
const lock_promise = async lock.acquireWrite();
const handle = await lock_promise;
defer handle.release();
shared_count += 1;
while (shared_test_index < shared_test_data.len) : (shared_test_index += 1) {
shared_test_data[shared_test_index] = shared_test_data[shared_test_index] + 1;
}
shared_test_index = 0;
}
}
fn readRunner(lock: *RwLock) callconv(.Async) void {
suspend {} // resumed by onNextTick
std.time.sleep(1);
var i: usize = 0;
while (i < shared_test_data.len) : (i += 1) {
const lock_promise = async lock.acquireRead();
const handle = await lock_promise;
defer handle.release();
try testing.expect(shared_test_index == 0);
try testing.expect(shared_test_data[i] == @as(i32, @intCast(shared_count)));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/wait_group.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const Loop = std.event.Loop;
/// A WaitGroup keeps track and waits for a group of async tasks to finish.
/// Call `begin` when creating new tasks, and have tasks call `finish` when done.
/// You can provide a count for both operations to perform them in bulk.
/// Call `wait` to suspend until all tasks are completed.
/// Multiple waiters are supported.
///
/// WaitGroup is an instance of WaitGroupGeneric, which takes in a bitsize
/// for the internal counter. WaitGroup defaults to a `usize` counter.
/// It's also possible to define a max value for the counter so that
/// `begin` will return error.Overflow when the limit is reached, even
/// if the integer type has not has not overflowed.
/// By default `max_value` is set to std.math.maxInt(CounterType).
pub const WaitGroup = WaitGroupGeneric(std.meta.bitCount(usize));
pub fn WaitGroupGeneric(comptime counter_size: u16) type {
const CounterType = std.meta.Int(.unsigned, counter_size);
const global_event_loop = Loop.instance orelse
@compileError("std.event.WaitGroup currently only works with event-based I/O");
return struct {
counter: CounterType = 0,
max_counter: CounterType = std.math.maxInt(CounterType),
mutex: std.Thread.Mutex = .{},
waiters: ?*Waiter = null,
const Waiter = struct {
next: ?*Waiter,
tail: *Waiter,
node: Loop.NextTickNode,
};
const Self = @This();
pub fn begin(self: *Self, count: CounterType) error{Overflow}!void {
const held = self.mutex.acquire();
defer held.release();
const new_counter = try std.math.add(CounterType, self.counter, count);
if (new_counter > self.max_counter) return error.Overflow;
self.counter = new_counter;
}
pub fn finish(self: *Self, count: CounterType) void {
var waiters = blk: {
const held = self.mutex.acquire();
defer held.release();
self.counter = std.math.sub(CounterType, self.counter, count) catch unreachable;
if (self.counter == 0) {
const temp = self.waiters;
self.waiters = null;
break :blk temp;
}
break :blk null;
};
// We don't need to hold the lock to reschedule any potential waiter.
while (waiters) |w| {
const temp_w = w;
waiters = w.next;
global_event_loop.onNextTick(&temp_w.node);
}
}
pub fn wait(self: *Self) void {
const held = self.mutex.acquire();
if (self.counter == 0) {
held.release();
return;
}
var self_waiter: Waiter = undefined;
self_waiter.node.data = @frame();
if (self.waiters) |head| {
head.tail.next = &self_waiter;
head.tail = &self_waiter;
} else {
self.waiters = &self_waiter;
self_waiter.tail = &self_waiter;
self_waiter.next = null;
}
suspend {
held.release();
}
}
};
}
test "basic WaitGroup usage" {
if (!std.io.is_async) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/3251
if (builtin.os.tag == .freebsd) return error.SkipZigTest;
var initial_wg = WaitGroup{};
var final_wg = WaitGroup{};
try initial_wg.begin(1);
try final_wg.begin(1);
var task_frame = async task(&initial_wg, &final_wg);
initial_wg.finish(1);
final_wg.wait();
await task_frame;
}
fn task(wg_i: *WaitGroup, wg_f: *WaitGroup) void {
wg_i.wait();
wg_f.finish(1);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/lock.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Loop = std.event.Loop;
/// Thread-safe async/await lock.
/// Functions which are waiting for the lock are suspended, and
/// are resumed when the lock is released, in order.
/// Allows only one actor to hold the lock.
/// TODO: make this API also work in blocking I/O mode.
pub const Lock = struct {
mutex: std.Thread.Mutex = std.Thread.Mutex{},
head: usize = UNLOCKED,
const UNLOCKED = 0;
const LOCKED = 1;
const global_event_loop = Loop.instance orelse
@compileError("std.event.Lock currently only works with event-based I/O");
const Waiter = struct {
// forced Waiter alignment to ensure it doesn't clash with LOCKED
next: ?*Waiter align(2),
tail: *Waiter,
node: Loop.NextTickNode,
};
pub fn initLocked() Lock {
return Lock{ .head = LOCKED };
}
pub fn acquire(self: *Lock) Held {
const held = self.mutex.acquire();
// self.head transitions from multiple stages depending on the value:
// UNLOCKED -> LOCKED:
// acquire Lock ownership when theres no waiters
// LOCKED -> <Waiter head ptr>:
// Lock is already owned, enqueue first Waiter
// <head ptr> -> <head ptr>:
// Lock is owned with pending waiters. Push our waiter to the queue.
if (self.head == UNLOCKED) {
self.head = LOCKED;
held.release();
return Held{ .lock = self };
}
var waiter: Waiter = undefined;
waiter.next = null;
waiter.tail = &waiter;
const head = switch (self.head) {
UNLOCKED => unreachable,
LOCKED => null,
else => @as(*Waiter, @ptrFromInt(self.head)),
};
if (head) |h| {
h.tail.next = &waiter;
h.tail = &waiter;
} else {
self.head = @intFromPtr(&waiter);
}
suspend {
waiter.node = Loop.NextTickNode{
.prev = undefined,
.next = undefined,
.data = @frame(),
};
held.release();
}
return Held{ .lock = self };
}
pub const Held = struct {
lock: *Lock,
pub fn release(self: Held) void {
const waiter = blk: {
const held = self.lock.mutex.acquire();
defer held.release();
// self.head goes through the reverse transition from acquire():
// <head ptr> -> <new head ptr>:
// pop a waiter from the queue to give Lock ownership when theres still others pending
// <head ptr> -> LOCKED:
// pop the laster waiter from the queue, while also giving it lock ownership when awaken
// LOCKED -> UNLOCKED:
// last lock owner releases lock while no one else is waiting for it
switch (self.lock.head) {
UNLOCKED => {
unreachable; // Lock unlocked while unlocking
},
LOCKED => {
self.lock.head = UNLOCKED;
break :blk null;
},
else => {
const waiter = @as(*Waiter, @ptrFromInt(self.lock.head));
self.lock.head = if (waiter.next == null) LOCKED else @intFromPtr(waiter.next);
if (waiter.next) |next|
next.tail = waiter.tail;
break :blk waiter;
},
}
};
if (waiter) |w| {
global_event_loop.onNextTick(&w.node);
}
}
};
};
test "std.event.Lock" {
if (!std.io.is_async) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/3251
if (builtin.os.tag == .freebsd) return error.SkipZigTest;
var lock = Lock{};
testLock(&lock);
const expected_result = [1]i32{3 * @as(i32, @intCast(shared_test_data.len))} ** shared_test_data.len;
try testing.expectEqualSlices(i32, &expected_result, &shared_test_data);
}
fn testLock(lock: *Lock) void {
var handle1 = async lockRunner(lock);
var handle2 = async lockRunner(lock);
var handle3 = async lockRunner(lock);
await handle1;
await handle2;
await handle3;
}
var shared_test_data = [1]i32{0} ** 10;
var shared_test_index: usize = 0;
fn lockRunner(lock: *Lock) void {
Lock.global_event_loop.yield();
var i: usize = 0;
while (i < shared_test_data.len) : (i += 1) {
const handle = lock.acquire();
defer handle.release();
shared_test_index = 0;
while (shared_test_index < shared_test_data.len) : (shared_test_index += 1) {
shared_test_data[shared_test_index] = shared_test_data[shared_test_index] + 1;
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/locked.zig | const std = @import("../std.zig");
const Lock = std.event.Lock;
/// Thread-safe async/await lock that protects one piece of data.
/// Functions which are waiting for the lock are suspended, and
/// are resumed when the lock is released, in order.
pub fn Locked(comptime T: type) type {
return struct {
lock: Lock,
private_data: T,
const Self = @This();
pub const HeldLock = struct {
value: *T,
held: Lock.Held,
pub fn release(self: HeldLock) void {
self.held.release();
}
};
pub fn init(data: T) Self {
return Self{
.lock = Lock.init(),
.private_data = data,
};
}
pub fn deinit(self: *Self) void {
self.lock.deinit();
}
pub fn acquire(self: *Self) callconv(.Async) HeldLock {
return HeldLock{
// TODO guaranteed allocation elision
.held = self.lock.acquire(),
.value = &self.private_data,
};
}
};
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/batch.zig | const std = @import("../std.zig");
const testing = std.testing;
/// Performs multiple async functions in parallel, without heap allocation.
/// Async function frames are managed externally to this abstraction, and
/// passed in via the `add` function. Once all the jobs are added, call `wait`.
/// This API is *not* thread-safe. The object must be accessed from one thread at
/// a time, however, it need not be the same thread.
pub fn Batch(
/// The return value for each job.
/// If a job slot was re-used due to maxed out concurrency, then its result
/// value will be overwritten. The values can be accessed with the `results` field.
comptime Result: type,
/// How many jobs to run in parallel.
comptime max_jobs: comptime_int,
/// Controls whether the `add` and `wait` functions will be async functions.
comptime async_behavior: enum {
/// Observe the value of `std.io.is_async` to decide whether `add`
/// and `wait` will be async functions. Asserts that the jobs do not suspend when
/// `std.io.mode == .blocking`. This is a generally safe assumption, and the
/// usual recommended option for this parameter.
auto_async,
/// Always uses the `nosuspend` keyword when using `await` on the jobs,
/// making `add` and `wait` non-async functions. Asserts that the jobs do not suspend.
never_async,
/// `add` and `wait` use regular `await` keyword, making them async functions.
always_async,
},
) type {
return struct {
jobs: [max_jobs]Job,
next_job_index: usize,
collected_result: CollectedResult,
const Job = struct {
frame: ?anyframe->Result,
result: Result,
};
const Self = @This();
const CollectedResult = switch (@typeInfo(Result)) {
.ErrorUnion => Result,
else => void,
};
const async_ok = switch (async_behavior) {
.auto_async => std.io.is_async,
.never_async => false,
.always_async => true,
};
pub fn init() Self {
return Self{
.jobs = [1]Job{
.{
.frame = null,
.result = undefined,
},
} ** max_jobs,
.next_job_index = 0,
.collected_result = {},
};
}
/// Add a frame to the Batch. If all jobs are in-flight, then this function
/// waits until one completes.
/// This function is *not* thread-safe. It must be called from one thread at
/// a time, however, it need not be the same thread.
/// TODO: "select" language feature to use the next available slot, rather than
/// awaiting the next index.
pub fn add(self: *Self, frame: anyframe->Result) void {
const job = &self.jobs[self.next_job_index];
self.next_job_index = (self.next_job_index + 1) % max_jobs;
if (job.frame) |existing| {
job.result = if (async_ok) await existing else nosuspend await existing;
if (CollectedResult != void) {
job.result catch |err| {
self.collected_result = err;
};
}
}
job.frame = frame;
}
/// Wait for all the jobs to complete.
/// Safe to call any number of times.
/// If `Result` is an error union, this function returns the last error that occurred, if any.
/// Unlike the `results` field, the return value of `wait` will report any error that occurred;
/// hitting max parallelism will not compromise the result.
/// This function is *not* thread-safe. It must be called from one thread at
/// a time, however, it need not be the same thread.
pub fn wait(self: *Self) CollectedResult {
for (self.jobs) |*job|
if (job.frame) |f| {
job.result = if (async_ok) await f else nosuspend await f;
if (CollectedResult != void) {
job.result catch |err| {
self.collected_result = err;
};
}
job.frame = null;
};
return self.collected_result;
}
};
}
test "std.event.Batch" {
var count: usize = 0;
var batch = Batch(void, 2, .auto_async).init();
batch.add(&async sleepALittle(&count));
batch.add(&async increaseByTen(&count));
batch.wait();
try testing.expect(count == 11);
var another = Batch(anyerror!void, 2, .auto_async).init();
another.add(&async somethingElse());
another.add(&async doSomethingThatFails());
try testing.expectError(error.ItBroke, another.wait());
}
fn sleepALittle(count: *usize) void {
std.time.sleep(1 * std.time.ns_per_ms);
_ = @atomicRmw(usize, count, .Add, 1, .SeqCst);
}
fn increaseByTen(count: *usize) void {
var i: usize = 0;
while (i < 10) : (i += 1) {
_ = @atomicRmw(usize, count, .Add, 1, .SeqCst);
}
}
fn doSomethingThatFails() anyerror!void {}
fn somethingElse() anyerror!void {
return error.ItBroke;
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/channel.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const Loop = std.event.Loop;
/// Many producer, many consumer, thread-safe, runtime configurable buffer size.
/// When buffer is empty, consumers suspend and are resumed by producers.
/// When buffer is full, producers suspend and are resumed by consumers.
pub fn Channel(comptime T: type) type {
return struct {
getters: std.atomic.Queue(GetNode),
or_null_queue: std.atomic.Queue(*std.atomic.Queue(GetNode).Node),
putters: std.atomic.Queue(PutNode),
get_count: usize,
put_count: usize,
dispatch_lock: bool,
need_dispatch: bool,
// simple fixed size ring buffer
buffer_nodes: []T,
buffer_index: usize,
buffer_len: usize,
const SelfChannel = @This();
const GetNode = struct {
tick_node: *Loop.NextTickNode,
data: Data,
const Data = union(enum) {
Normal: Normal,
OrNull: OrNull,
};
const Normal = struct {
ptr: *T,
};
const OrNull = struct {
ptr: *?T,
or_null: *std.atomic.Queue(*std.atomic.Queue(GetNode).Node).Node,
};
};
const PutNode = struct {
data: T,
tick_node: *Loop.NextTickNode,
};
const global_event_loop = Loop.instance orelse
@compileError("std.event.Channel currently only works with event-based I/O");
/// Call `deinit` to free resources when done.
/// `buffer` must live until `deinit` is called.
/// For a zero length buffer, use `[0]T{}`.
/// TODO https://github.com/ziglang/zig/issues/2765
pub fn init(self: *SelfChannel, buffer: []T) void {
// The ring buffer implementation only works with power of 2 buffer sizes
// because of relying on subtracting across zero. For example (0 -% 1) % 10 == 5
assert(buffer.len == 0 or @popCount(buffer.len) == 1);
self.* = SelfChannel{
.buffer_len = 0,
.buffer_nodes = buffer,
.buffer_index = 0,
.dispatch_lock = false,
.need_dispatch = false,
.getters = std.atomic.Queue(GetNode).init(),
.putters = std.atomic.Queue(PutNode).init(),
.or_null_queue = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).init(),
.get_count = 0,
.put_count = 0,
};
}
/// Must be called when all calls to put and get have suspended and no more calls occur.
/// This can be omitted if caller can guarantee that the suspended putters and getters
/// do not need to be run to completion. Note that this may leave awaiters hanging.
pub fn deinit(self: *SelfChannel) void {
while (self.getters.get()) |get_node| {
resume get_node.data.tick_node.data;
}
while (self.putters.get()) |put_node| {
resume put_node.data.tick_node.data;
}
self.* = undefined;
}
/// puts a data item in the channel. The function returns when the value has been added to the
/// buffer, or in the case of a zero size buffer, when the item has been retrieved by a getter.
/// Or when the channel is destroyed.
pub fn put(self: *SelfChannel, data: T) void {
var my_tick_node = Loop.NextTickNode{ .data = @frame() };
var queue_node = std.atomic.Queue(PutNode).Node{
.data = PutNode{
.tick_node = &my_tick_node,
.data = data,
},
};
suspend {
self.putters.put(&queue_node);
_ = @atomicRmw(usize, &self.put_count, .Add, 1, .SeqCst);
self.dispatch();
}
}
/// await this function to get an item from the channel. If the buffer is empty, the frame will
/// complete when the next item is put in the channel.
pub fn get(self: *SelfChannel) callconv(.Async) T {
// TODO https://github.com/ziglang/zig/issues/2765
var result: T = undefined;
var my_tick_node = Loop.NextTickNode{ .data = @frame() };
var queue_node = std.atomic.Queue(GetNode).Node{
.data = GetNode{
.tick_node = &my_tick_node,
.data = GetNode.Data{
.Normal = GetNode.Normal{ .ptr = &result },
},
},
};
suspend {
self.getters.put(&queue_node);
_ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst);
self.dispatch();
}
return result;
}
//pub async fn select(comptime EnumUnion: type, channels: ...) EnumUnion {
// assert(@memberCount(EnumUnion) == channels.len); // enum union and channels mismatch
// assert(channels.len != 0); // enum unions cannot have 0 fields
// if (channels.len == 1) {
// const result = await (async channels[0].get() catch unreachable);
// return @unionInit(EnumUnion, @memberName(EnumUnion, 0), result);
// }
//}
/// Get an item from the channel. If the buffer is empty and there are no
/// puts waiting, this returns `null`.
pub fn getOrNull(self: *SelfChannel) ?T {
// TODO integrate this function with named return values
// so we can get rid of this extra result copy
var result: ?T = null;
var my_tick_node = Loop.NextTickNode{ .data = @frame() };
var or_null_node = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).Node{ .data = undefined };
var queue_node = std.atomic.Queue(GetNode).Node{
.data = GetNode{
.tick_node = &my_tick_node,
.data = GetNode.Data{
.OrNull = GetNode.OrNull{
.ptr = &result,
.or_null = &or_null_node,
},
},
},
};
or_null_node.data = &queue_node;
suspend {
self.getters.put(&queue_node);
_ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst);
self.or_null_queue.put(&or_null_node);
self.dispatch();
}
return result;
}
fn dispatch(self: *SelfChannel) void {
// set the "need dispatch" flag
@atomicStore(bool, &self.need_dispatch, true, .SeqCst);
lock: while (true) {
// set the lock flag
if (@atomicRmw(bool, &self.dispatch_lock, .Xchg, true, .SeqCst)) return;
// clear the need_dispatch flag since we're about to do it
@atomicStore(bool, &self.need_dispatch, false, .SeqCst);
while (true) {
one_dispatch: {
// later we correct these extra subtractions
var get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst);
var put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst);
// transfer self.buffer to self.getters
while (self.buffer_len != 0) {
if (get_count == 0) break :one_dispatch;
const get_node = &self.getters.get().?.data;
switch (get_node.data) {
GetNode.Data.Normal => |info| {
info.ptr.* = self.buffer_nodes[(self.buffer_index -% self.buffer_len) % self.buffer_nodes.len];
},
GetNode.Data.OrNull => |info| {
_ = self.or_null_queue.remove(info.or_null);
info.ptr.* = self.buffer_nodes[(self.buffer_index -% self.buffer_len) % self.buffer_nodes.len];
},
}
global_event_loop.onNextTick(get_node.tick_node);
self.buffer_len -= 1;
get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst);
}
// direct transfer self.putters to self.getters
while (get_count != 0 and put_count != 0) {
const get_node = &self.getters.get().?.data;
const put_node = &self.putters.get().?.data;
switch (get_node.data) {
GetNode.Data.Normal => |info| {
info.ptr.* = put_node.data;
},
GetNode.Data.OrNull => |info| {
_ = self.or_null_queue.remove(info.or_null);
info.ptr.* = put_node.data;
},
}
global_event_loop.onNextTick(get_node.tick_node);
global_event_loop.onNextTick(put_node.tick_node);
get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst);
put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst);
}
// transfer self.putters to self.buffer
while (self.buffer_len != self.buffer_nodes.len and put_count != 0) {
const put_node = &self.putters.get().?.data;
self.buffer_nodes[self.buffer_index % self.buffer_nodes.len] = put_node.data;
global_event_loop.onNextTick(put_node.tick_node);
self.buffer_index +%= 1;
self.buffer_len += 1;
put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst);
}
}
// undo the extra subtractions
_ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst);
_ = @atomicRmw(usize, &self.put_count, .Add, 1, .SeqCst);
// All the "get or null" functions should resume now.
var remove_count: usize = 0;
while (self.or_null_queue.get()) |or_null_node| {
remove_count += @intFromBool(self.getters.remove(or_null_node.data));
global_event_loop.onNextTick(or_null_node.data.data.tick_node);
}
if (remove_count != 0) {
_ = @atomicRmw(usize, &self.get_count, .Sub, remove_count, .SeqCst);
}
// clear need-dispatch flag
if (@atomicRmw(bool, &self.need_dispatch, .Xchg, false, .SeqCst)) continue;
assert(@atomicRmw(bool, &self.dispatch_lock, .Xchg, false, .SeqCst));
// we have to check again now that we unlocked
if (@atomicLoad(bool, &self.need_dispatch, .SeqCst)) continue :lock;
return;
}
}
}
};
}
test "std.event.Channel" {
if (!std.io.is_async) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/3251
if (builtin.os.tag == .freebsd) return error.SkipZigTest;
var channel: Channel(i32) = undefined;
channel.init(&[0]i32{});
defer channel.deinit();
var handle = async testChannelGetter(&channel);
var putter = async testChannelPutter(&channel);
await handle;
await putter;
}
test "std.event.Channel wraparound" {
// TODO provide a way to run tests in evented I/O mode
if (!std.io.is_async) return error.SkipZigTest;
const channel_size = 2;
var buf: [channel_size]i32 = undefined;
var channel: Channel(i32) = undefined;
channel.init(&buf);
defer channel.deinit();
// add items to channel and pull them out until
// the buffer wraps around, make sure it doesn't crash.
channel.put(5);
try testing.expectEqual(@as(i32, 5), channel.get());
channel.put(6);
try testing.expectEqual(@as(i32, 6), channel.get());
channel.put(7);
try testing.expectEqual(@as(i32, 7), channel.get());
}
fn testChannelGetter(channel: *Channel(i32)) callconv(.Async) void {
const value1 = channel.get();
try testing.expect(value1 == 1234);
const value2 = channel.get();
try testing.expect(value2 == 4567);
const value3 = channel.getOrNull();
try testing.expect(value3 == null);
var last_put = async testPut(channel, 4444);
const value4 = channel.getOrNull();
try testing.expect(value4.? == 4444);
await last_put;
}
fn testChannelPutter(channel: *Channel(i32)) callconv(.Async) void {
channel.put(1234);
channel.put(4567);
}
fn testPut(channel: *Channel(i32), value: i32) callconv(.Async) void {
channel.put(value);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/group.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const Lock = std.event.Lock;
const testing = std.testing;
const Allocator = std.mem.Allocator;
/// ReturnType must be `void` or `E!void`
/// TODO This API was created back with the old design of async/await, when calling any
/// async function required an allocator. There is an ongoing experiment to transition
/// all uses of this API to the simpler and more resource-aware `std.event.Batch` API.
/// If the transition goes well, all usages of `Group` will be gone, and this API
/// will be deleted.
pub fn Group(comptime ReturnType: type) type {
return struct {
frame_stack: Stack,
alloc_stack: AllocStack,
lock: Lock,
allocator: *Allocator,
const Self = @This();
const Error = switch (@typeInfo(ReturnType)) {
.ErrorUnion => |payload| payload.error_set,
else => void,
};
const Stack = std.atomic.Stack(anyframe->ReturnType);
const AllocStack = std.atomic.Stack(Node);
pub const Node = struct {
bytes: []const u8 = &[0]u8{},
handle: anyframe->ReturnType,
};
pub fn init(allocator: *Allocator) Self {
return Self{
.frame_stack = Stack.init(),
.alloc_stack = AllocStack.init(),
.lock = Lock.init(),
.allocator = allocator,
};
}
/// Add a frame to the group. Thread-safe.
pub fn add(self: *Self, handle: anyframe->ReturnType) (error{OutOfMemory}!void) {
const node = try self.allocator.create(AllocStack.Node);
node.* = AllocStack.Node{
.next = undefined,
.data = Node{
.handle = handle,
},
};
self.alloc_stack.push(node);
}
/// Add a node to the group. Thread-safe. Cannot fail.
/// `node.data` should be the frame handle to add to the group.
/// The node's memory should be in the function frame of
/// the handle that is in the node, or somewhere guaranteed to live
/// at least as long.
pub fn addNode(self: *Self, node: *Stack.Node) void {
self.frame_stack.push(node);
}
/// This is equivalent to adding a frame to the group but the memory of its frame is
/// allocated by the group and freed by `wait`.
/// `func` must be async and have return type `ReturnType`.
/// Thread-safe.
pub fn call(self: *Self, comptime func: anytype, args: anytype) error{OutOfMemory}!void {
var frame = try self.allocator.create(@TypeOf(@call(.{ .modifier = .async_kw }, func, args)));
errdefer self.allocator.destroy(frame);
const node = try self.allocator.create(AllocStack.Node);
errdefer self.allocator.destroy(node);
node.* = AllocStack.Node{
.next = undefined,
.data = Node{
.handle = frame,
.bytes = std.mem.asBytes(frame),
},
};
frame.* = @call(.{ .modifier = .async_kw }, func, args);
self.alloc_stack.push(node);
}
/// Wait for all the calls and promises of the group to complete.
/// Thread-safe.
/// Safe to call any number of times.
pub fn wait(self: *Self) callconv(.Async) ReturnType {
const held = self.lock.acquire();
defer held.release();
var result: ReturnType = {};
while (self.frame_stack.pop()) |node| {
if (Error == void) {
await node.data;
} else {
(await node.data) catch |err| {
result = err;
};
}
}
while (self.alloc_stack.pop()) |node| {
const handle = node.data.handle;
if (Error == void) {
await handle;
} else {
(await handle) catch |err| {
result = err;
};
}
self.allocator.free(node.data.bytes);
self.allocator.destroy(node);
}
return result;
}
};
}
test "std.event.Group" {
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
if (!std.io.is_async) return error.SkipZigTest;
// TODO this file has bit-rotted. repair it
if (true) return error.SkipZigTest;
_ = async testGroup(std.heap.page_allocator);
}
fn testGroup(allocator: *Allocator) callconv(.Async) void {
var count: usize = 0;
var group = Group(void).init(allocator);
var sleep_a_little_frame = async sleepALittle(&count);
group.add(&sleep_a_little_frame) catch @panic("memory");
var increase_by_ten_frame = async increaseByTen(&count);
group.add(&increase_by_ten_frame) catch @panic("memory");
group.wait();
try testing.expect(count == 11);
var another = Group(anyerror!void).init(allocator);
var something_else_frame = async somethingElse();
another.add(&something_else_frame) catch @panic("memory");
var something_that_fails_frame = async doSomethingThatFails();
another.add(&something_that_fails_frame) catch @panic("memory");
try testing.expectError(error.ItBroke, another.wait());
}
fn sleepALittle(count: *usize) callconv(.Async) void {
std.time.sleep(1 * std.time.ns_per_ms);
_ = @atomicRmw(usize, count, .Add, 1, .SeqCst);
}
fn increaseByTen(count: *usize) callconv(.Async) void {
var i: usize = 0;
while (i < 10) : (i += 1) {
_ = @atomicRmw(usize, count, .Add, 1, .SeqCst);
}
}
fn doSomethingThatFails() callconv(.Async) anyerror!void {}
fn somethingElse() callconv(.Async) anyerror!void {
return error.ItBroke;
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/future.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const Lock = std.event.Lock;
/// This is a value that starts out unavailable, until resolve() is called
/// While it is unavailable, functions suspend when they try to get() it,
/// and then are resumed when resolve() is called.
/// At this point the value remains forever available, and another resolve() is not allowed.
pub fn Future(comptime T: type) type {
return struct {
lock: Lock,
data: T,
available: Available,
const Available = enum(u8) {
NotStarted,
Started,
Finished,
};
const Self = @This();
const Queue = std.atomic.Queue(anyframe);
pub fn init() Self {
return Self{
.lock = Lock.initLocked(),
.available = .NotStarted,
.data = undefined,
};
}
/// Obtain the value. If it's not available, wait until it becomes
/// available.
/// Thread-safe.
pub fn get(self: *Self) callconv(.Async) *T {
if (@atomicLoad(Available, &self.available, .SeqCst) == .Finished) {
return &self.data;
}
const held = self.lock.acquire();
held.release();
return &self.data;
}
/// Gets the data without waiting for it. If it's available, a pointer is
/// returned. Otherwise, null is returned.
pub fn getOrNull(self: *Self) ?*T {
if (@atomicLoad(Available, &self.available, .SeqCst) == .Finished) {
return &self.data;
} else {
return null;
}
}
/// If someone else has started working on the data, wait for them to complete
/// and return a pointer to the data. Otherwise, return null, and the caller
/// should start working on the data.
/// It's not required to call start() before resolve() but it can be useful since
/// this method is thread-safe.
pub fn start(self: *Self) callconv(.Async) ?*T {
const state = @cmpxchgStrong(Available, &self.available, .NotStarted, .Started, .SeqCst, .SeqCst) orelse return null;
switch (state) {
.Started => {
const held = self.lock.acquire();
held.release();
return &self.data;
},
.Finished => return &self.data,
else => unreachable,
}
}
/// Make the data become available. May be called only once.
/// Before calling this, modify the `data` property.
pub fn resolve(self: *Self) void {
const prev = @atomicRmw(Available, &self.available, .Xchg, .Finished, .SeqCst);
assert(prev != .Finished); // resolve() called twice
Lock.Held.release(Lock.Held{ .lock = &self.lock });
}
};
}
test "std.event.Future" {
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/3251
if (builtin.os.tag == .freebsd) return error.SkipZigTest;
// TODO provide a way to run tests in evented I/O mode
if (!std.io.is_async) return error.SkipZigTest;
testFuture();
}
fn testFuture() void {
var future = Future(i32).init();
var a = async waitOnFuture(&future);
var b = async waitOnFuture(&future);
resolveFuture(&future);
const result = (await a) + (await b);
try testing.expect(result == 12);
}
fn waitOnFuture(future: *Future(i32)) i32 {
return future.get().*;
}
fn resolveFuture(future: *Future(i32)) void {
future.data = 6;
future.resolve();
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/loop.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const root = @import("root");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const os = std.os;
const windows = os.windows;
const maxInt = std.math.maxInt;
const Thread = std.Thread;
const is_windows = builtin.os.tag == .windows;
pub const Loop = struct {
next_tick_queue: std.atomic.Queue(anyframe),
os_data: OsData,
final_resume_node: ResumeNode,
pending_event_count: usize,
extra_threads: []Thread,
/// TODO change this to a pool of configurable number of threads
/// and rename it to be not file-system-specific. it will become
/// a thread pool for turning non-CPU-bound blocking things into
/// async things. A fallback for any missing OS-specific API.
fs_thread: Thread,
fs_queue: std.atomic.Queue(Request),
fs_end_request: Request.Node,
fs_thread_wakeup: std.Thread.ResetEvent,
/// For resources that have the same lifetime as the `Loop`.
/// This is only used by `Loop` for the thread pool and associated resources.
arena: std.heap.ArenaAllocator,
/// State which manages frames that are sleeping on timers
delay_queue: DelayQueue,
/// Pre-allocated eventfds. All permanently active.
/// This is how `Loop` sends promises to be resumed on other threads.
available_eventfd_resume_nodes: std.atomic.Stack(ResumeNode.EventFd),
eventfd_resume_nodes: []std.atomic.Stack(ResumeNode.EventFd).Node,
pub const NextTickNode = std.atomic.Queue(anyframe).Node;
pub const ResumeNode = struct {
id: Id,
handle: anyframe,
overlapped: Overlapped,
pub const overlapped_init = switch (builtin.os.tag) {
.windows => windows.OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = 0,
.OffsetHigh = 0,
},
},
.hEvent = null,
},
else => {},
};
pub const Overlapped = @TypeOf(overlapped_init);
pub const Id = enum {
Basic,
Stop,
EventFd,
};
pub const EventFd = switch (builtin.os.tag) {
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventFd,
.linux => struct {
base: ResumeNode,
epoll_op: u32,
eventfd: i32,
},
.windows => struct {
base: ResumeNode,
completion_key: usize,
},
else => struct {},
};
const KEventFd = struct {
base: ResumeNode,
kevent: os.Kevent,
};
pub const Basic = switch (builtin.os.tag) {
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventBasic,
.linux => struct {
base: ResumeNode,
},
.windows => struct {
base: ResumeNode,
},
else => @compileError("unsupported OS"),
};
const KEventBasic = struct {
base: ResumeNode,
kev: os.Kevent,
};
};
var global_instance_state: Loop = undefined;
const default_instance: ?*Loop = switch (std.io.mode) {
.blocking => null,
.evented => &global_instance_state,
};
pub const instance: ?*Loop = if (@hasDecl(root, "event_loop")) root.event_loop else default_instance;
/// TODO copy elision / named return values so that the threads referencing *Loop
/// have the correct pointer value.
/// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765
pub fn init(self: *Loop) !void {
if (builtin.single_threaded or
(@hasDecl(root, "event_loop_mode") and root.event_loop_mode == .single_threaded))
{
return self.initSingleThreaded();
} else {
return self.initMultiThreaded();
}
}
/// After initialization, call run().
/// TODO copy elision / named return values so that the threads referencing *Loop
/// have the correct pointer value.
/// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765
pub fn initSingleThreaded(self: *Loop) !void {
return self.initThreadPool(1);
}
/// After initialization, call run().
/// This is the same as `initThreadPool` using `Thread.getCpuCount` to determine the thread
/// pool size.
/// TODO copy elision / named return values so that the threads referencing *Loop
/// have the correct pointer value.
/// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765
pub fn initMultiThreaded(self: *Loop) !void {
if (builtin.single_threaded)
@compileError("initMultiThreaded unavailable when building in single-threaded mode");
const core_count = try Thread.getCpuCount();
return self.initThreadPool(core_count);
}
/// Thread count is the total thread count. The thread pool size will be
/// max(thread_count - 1, 0)
pub fn initThreadPool(self: *Loop, thread_count: usize) !void {
self.* = Loop{
.arena = std.heap.ArenaAllocator.init(std.heap.page_allocator),
.pending_event_count = 1,
.os_data = undefined,
.next_tick_queue = std.atomic.Queue(anyframe).init(),
.extra_threads = undefined,
.available_eventfd_resume_nodes = std.atomic.Stack(ResumeNode.EventFd).init(),
.eventfd_resume_nodes = undefined,
.final_resume_node = ResumeNode{
.id = ResumeNode.Id.Stop,
.handle = undefined,
.overlapped = ResumeNode.overlapped_init,
},
.fs_end_request = .{ .data = .{ .msg = .end, .finish = .NoAction } },
.fs_queue = std.atomic.Queue(Request).init(),
.fs_thread = undefined,
.fs_thread_wakeup = undefined,
.delay_queue = undefined,
};
try self.fs_thread_wakeup.init();
errdefer self.fs_thread_wakeup.deinit();
errdefer self.arena.deinit();
// We need at least one of these in case the fs thread wants to use onNextTick
const extra_thread_count = thread_count - 1;
const resume_node_count = std.math.max(extra_thread_count, 1);
self.eventfd_resume_nodes = try self.arena.allocator.alloc(
std.atomic.Stack(ResumeNode.EventFd).Node,
resume_node_count,
);
self.extra_threads = try self.arena.allocator.alloc(Thread, extra_thread_count);
try self.initOsData(extra_thread_count);
errdefer self.deinitOsData();
if (!builtin.single_threaded) {
self.fs_thread = try Thread.spawn(.{}, posixFsRun, .{self});
}
errdefer if (!builtin.single_threaded) {
self.posixFsRequest(&self.fs_end_request);
self.fs_thread.join();
};
if (!builtin.single_threaded)
try self.delay_queue.init();
}
pub fn deinit(self: *Loop) void {
self.deinitOsData();
self.fs_thread_wakeup.deinit();
self.arena.deinit();
self.* = undefined;
}
const InitOsDataError = os.EpollCreateError || mem.Allocator.Error || os.EventFdError ||
Thread.SpawnError || os.EpollCtlError || os.KEventError ||
windows.CreateIoCompletionPortError;
const wakeup_bytes = [_]u8{0x1} ** 8;
fn initOsData(self: *Loop, extra_thread_count: usize) InitOsDataError!void {
nosuspend switch (builtin.os.tag) {
.linux => {
errdefer {
while (self.available_eventfd_resume_nodes.pop()) |node| os.close(node.data.eventfd);
}
for (self.eventfd_resume_nodes) |*eventfd_node| {
eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{
.data = ResumeNode.EventFd{
.base = ResumeNode{
.id = .EventFd,
.handle = undefined,
.overlapped = ResumeNode.overlapped_init,
},
.eventfd = try os.eventfd(1, os.linux.EFD.CLOEXEC | os.linux.EFD.NONBLOCK),
.epoll_op = os.linux.EPOLL.CTL_ADD,
},
.next = undefined,
};
self.available_eventfd_resume_nodes.push(eventfd_node);
}
self.os_data.epollfd = try os.epoll_create1(os.linux.EPOLL.CLOEXEC);
errdefer os.close(self.os_data.epollfd);
self.os_data.final_eventfd = try os.eventfd(0, os.linux.EFD.CLOEXEC | os.linux.EFD.NONBLOCK);
errdefer os.close(self.os_data.final_eventfd);
self.os_data.final_eventfd_event = os.linux.epoll_event{
.events = os.linux.EPOLL.IN,
.data = os.linux.epoll_data{ .ptr = @intFromPtr(&self.final_resume_node) },
};
try os.epoll_ctl(
self.os_data.epollfd,
os.linux.EPOLL.CTL_ADD,
self.os_data.final_eventfd,
&self.os_data.final_eventfd_event,
);
if (builtin.single_threaded) {
assert(extra_thread_count == 0);
return;
}
var extra_thread_index: usize = 0;
errdefer {
// writing 8 bytes to an eventfd cannot fail
const amt = os.write(self.os_data.final_eventfd, &wakeup_bytes) catch unreachable;
assert(amt == wakeup_bytes.len);
while (extra_thread_index != 0) {
extra_thread_index -= 1;
self.extra_threads[extra_thread_index].join();
}
}
while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) {
self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self});
}
},
.macos, .freebsd, .netbsd, .dragonfly => {
self.os_data.kqfd = try os.kqueue();
errdefer os.close(self.os_data.kqfd);
const empty_kevs = &[0]os.Kevent{};
for (self.eventfd_resume_nodes, 0..) |*eventfd_node, i| {
eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{
.data = ResumeNode.EventFd{
.base = ResumeNode{
.id = ResumeNode.Id.EventFd,
.handle = undefined,
.overlapped = ResumeNode.overlapped_init,
},
// this one is for sending events
.kevent = os.Kevent{
.ident = i,
.filter = os.system.EVFILT_USER,
.flags = os.system.EV_CLEAR | os.system.EV_ADD | os.system.EV_DISABLE,
.fflags = 0,
.data = 0,
.udata = @intFromPtr(&eventfd_node.data.base),
},
},
.next = undefined,
};
self.available_eventfd_resume_nodes.push(eventfd_node);
const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.data.kevent);
_ = try os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null);
eventfd_node.data.kevent.flags = os.system.EV_CLEAR | os.system.EV_ENABLE;
eventfd_node.data.kevent.fflags = os.system.NOTE_TRIGGER;
}
// Pre-add so that we cannot get error.SystemResources
// later when we try to activate it.
self.os_data.final_kevent = os.Kevent{
.ident = extra_thread_count,
.filter = os.system.EVFILT_USER,
.flags = os.system.EV_ADD | os.system.EV_DISABLE,
.fflags = 0,
.data = 0,
.udata = @intFromPtr(&self.final_resume_node),
};
const final_kev_arr = @as(*const [1]os.Kevent, &self.os_data.final_kevent);
_ = try os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null);
self.os_data.final_kevent.flags = os.system.EV_ENABLE;
self.os_data.final_kevent.fflags = os.system.NOTE_TRIGGER;
if (builtin.single_threaded) {
assert(extra_thread_count == 0);
return;
}
var extra_thread_index: usize = 0;
errdefer {
_ = os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null) catch unreachable;
while (extra_thread_index != 0) {
extra_thread_index -= 1;
self.extra_threads[extra_thread_index].join();
}
}
while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) {
self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self});
}
},
.openbsd => {
self.os_data.kqfd = try os.kqueue();
errdefer os.close(self.os_data.kqfd);
const empty_kevs = &[0]os.Kevent{};
for (self.eventfd_resume_nodes, 0..) |*eventfd_node, i| {
eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{
.data = ResumeNode.EventFd{
.base = ResumeNode{
.id = ResumeNode.Id.EventFd,
.handle = undefined,
.overlapped = ResumeNode.overlapped_init,
},
// this one is for sending events
.kevent = os.Kevent{
.ident = i,
.filter = os.system.EVFILT_TIMER,
.flags = os.system.EV_CLEAR | os.system.EV_ADD | os.system.EV_DISABLE | os.system.EV_ONESHOT,
.fflags = 0,
.data = 0,
.udata = @intFromPtr(&eventfd_node.data.base),
},
},
.next = undefined,
};
self.available_eventfd_resume_nodes.push(eventfd_node);
const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.data.kevent);
_ = try os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null);
eventfd_node.data.kevent.flags = os.system.EV_CLEAR | os.system.EV_ENABLE;
}
// Pre-add so that we cannot get error.SystemResources
// later when we try to activate it.
self.os_data.final_kevent = os.Kevent{
.ident = extra_thread_count,
.filter = os.system.EVFILT_TIMER,
.flags = os.system.EV_ADD | os.system.EV_ONESHOT | os.system.EV_DISABLE,
.fflags = 0,
.data = 0,
.udata = @intFromPtr(&self.final_resume_node),
};
const final_kev_arr = @as(*const [1]os.Kevent, &self.os_data.final_kevent);
_ = try os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null);
self.os_data.final_kevent.flags = os.system.EV_ENABLE;
if (builtin.single_threaded) {
assert(extra_thread_count == 0);
return;
}
var extra_thread_index: usize = 0;
errdefer {
_ = os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null) catch unreachable;
while (extra_thread_index != 0) {
extra_thread_index -= 1;
self.extra_threads[extra_thread_index].join();
}
}
while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) {
self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self});
}
},
.windows => {
self.os_data.io_port = try windows.CreateIoCompletionPort(
windows.INVALID_HANDLE_VALUE,
null,
undefined,
maxInt(windows.DWORD),
);
errdefer windows.CloseHandle(self.os_data.io_port);
for (self.eventfd_resume_nodes) |*eventfd_node| {
eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{
.data = ResumeNode.EventFd{
.base = ResumeNode{
.id = ResumeNode.Id.EventFd,
.handle = undefined,
.overlapped = ResumeNode.overlapped_init,
},
// this one is for sending events
.completion_key = @intFromPtr(&eventfd_node.data.base),
},
.next = undefined,
};
self.available_eventfd_resume_nodes.push(eventfd_node);
}
if (builtin.single_threaded) {
assert(extra_thread_count == 0);
return;
}
var extra_thread_index: usize = 0;
errdefer {
var i: usize = 0;
while (i < extra_thread_index) : (i += 1) {
while (true) {
const overlapped = &self.final_resume_node.overlapped;
windows.PostQueuedCompletionStatus(self.os_data.io_port, undefined, undefined, overlapped) catch continue;
break;
}
}
while (extra_thread_index != 0) {
extra_thread_index -= 1;
self.extra_threads[extra_thread_index].join();
}
}
while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) {
self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self});
}
},
else => {},
};
}
fn deinitOsData(self: *Loop) void {
nosuspend switch (builtin.os.tag) {
.linux => {
os.close(self.os_data.final_eventfd);
while (self.available_eventfd_resume_nodes.pop()) |node| os.close(node.data.eventfd);
os.close(self.os_data.epollfd);
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
os.close(self.os_data.kqfd);
},
.windows => {
windows.CloseHandle(self.os_data.io_port);
},
else => {},
};
}
/// resume_node must live longer than the anyframe that it holds a reference to.
/// flags must contain EPOLLET
pub fn linuxAddFd(self: *Loop, fd: i32, resume_node: *ResumeNode, flags: u32) !void {
assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET);
self.beginOneEvent();
errdefer self.finishOneEvent();
try self.linuxModFd(
fd,
os.linux.EPOLL.CTL_ADD,
flags,
resume_node,
);
}
pub fn linuxModFd(self: *Loop, fd: i32, op: u32, flags: u32, resume_node: *ResumeNode) !void {
assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET);
var ev = os.linux.epoll_event{
.events = flags,
.data = os.linux.epoll_data{ .ptr = @intFromPtr(resume_node) },
};
try os.epoll_ctl(self.os_data.epollfd, op, fd, &ev);
}
pub fn linuxRemoveFd(self: *Loop, fd: i32) void {
os.epoll_ctl(self.os_data.epollfd, os.linux.EPOLL.CTL_DEL, fd, null) catch {};
self.finishOneEvent();
}
pub fn linuxWaitFd(self: *Loop, fd: i32, flags: u32) void {
assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET);
assert(flags & os.linux.EPOLL.ONESHOT == os.linux.EPOLL.ONESHOT);
var resume_node = ResumeNode.Basic{
.base = ResumeNode{
.id = .Basic,
.handle = @frame(),
.overlapped = ResumeNode.overlapped_init,
},
};
var need_to_delete = true;
defer if (need_to_delete) self.linuxRemoveFd(fd);
suspend {
self.linuxAddFd(fd, &resume_node.base, flags) catch |err| switch (err) {
error.FileDescriptorNotRegistered => unreachable,
error.OperationCausesCircularLoop => unreachable,
error.FileDescriptorIncompatibleWithEpoll => unreachable,
error.FileDescriptorAlreadyPresentInSet => unreachable, // evented writes to the same fd is not thread-safe
error.SystemResources,
error.UserResourceLimitReached,
error.Unexpected,
=> {
need_to_delete = false;
// Fall back to a blocking poll(). Ideally this codepath is never hit, since
// epoll should be just fine. But this is better than incorrect behavior.
var poll_flags: i16 = 0;
if ((flags & os.linux.EPOLL.IN) != 0) poll_flags |= os.POLL.IN;
if ((flags & os.linux.EPOLL.OUT) != 0) poll_flags |= os.POLL.OUT;
var pfd = [1]os.pollfd{os.pollfd{
.fd = fd,
.events = poll_flags,
.revents = undefined,
}};
_ = os.poll(&pfd, -1) catch |poll_err| switch (poll_err) {
error.NetworkSubsystemFailed => unreachable, // only possible on windows
error.SystemResources,
error.Unexpected,
=> {
// Even poll() didn't work. The best we can do now is sleep for a
// small duration and then hope that something changed.
std.time.sleep(1 * std.time.ns_per_ms);
},
};
resume @frame();
},
};
}
}
pub fn waitUntilFdReadable(self: *Loop, fd: os.fd_t) void {
switch (builtin.os.tag) {
.linux => {
self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.IN);
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_READ, os.system.EV_ONESHOT);
},
else => @compileError("Unsupported OS"),
}
}
pub fn waitUntilFdWritable(self: *Loop, fd: os.fd_t) void {
switch (builtin.os.tag) {
.linux => {
self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.OUT);
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_WRITE, os.system.EV_ONESHOT);
},
else => @compileError("Unsupported OS"),
}
}
pub fn waitUntilFdWritableOrReadable(self: *Loop, fd: os.fd_t) void {
switch (builtin.os.tag) {
.linux => {
self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.OUT | os.linux.EPOLL.IN);
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_READ, os.system.EV_ONESHOT);
self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_WRITE, os.system.EV_ONESHOT);
},
else => @compileError("Unsupported OS"),
}
}
pub fn bsdWaitKev(self: *Loop, ident: usize, filter: i16, flags: u16) void {
var resume_node = ResumeNode.Basic{
.base = ResumeNode{
.id = ResumeNode.Id.Basic,
.handle = @frame(),
.overlapped = ResumeNode.overlapped_init,
},
.kev = undefined,
};
defer {
// If the kevent was set to be ONESHOT, it doesn't need to be deleted manually.
if (flags & os.system.EV_ONESHOT != 0) {
self.bsdRemoveKev(ident, filter);
}
}
suspend {
self.bsdAddKev(&resume_node, ident, filter, flags) catch unreachable;
}
}
/// resume_node must live longer than the anyframe that it holds a reference to.
pub fn bsdAddKev(self: *Loop, resume_node: *ResumeNode.Basic, ident: usize, filter: i16, flags: u16) !void {
self.beginOneEvent();
errdefer self.finishOneEvent();
var kev = [1]os.Kevent{os.Kevent{
.ident = ident,
.filter = filter,
.flags = os.system.EV_ADD | os.system.EV_ENABLE | os.system.EV_CLEAR | flags,
.fflags = 0,
.data = 0,
.udata = @intFromPtr(&resume_node.base),
}};
const empty_kevs = &[0]os.Kevent{};
_ = try os.kevent(self.os_data.kqfd, &kev, empty_kevs, null);
}
pub fn bsdRemoveKev(self: *Loop, ident: usize, filter: i16) void {
var kev = [1]os.Kevent{os.Kevent{
.ident = ident,
.filter = filter,
.flags = os.system.EV_DELETE,
.fflags = 0,
.data = 0,
.udata = 0,
}};
const empty_kevs = &[0]os.Kevent{};
_ = os.kevent(self.os_data.kqfd, &kev, empty_kevs, null) catch undefined;
self.finishOneEvent();
}
fn dispatch(self: *Loop) void {
while (self.available_eventfd_resume_nodes.pop()) |resume_stack_node| {
const next_tick_node = self.next_tick_queue.get() orelse {
self.available_eventfd_resume_nodes.push(resume_stack_node);
return;
};
const eventfd_node = &resume_stack_node.data;
eventfd_node.base.handle = next_tick_node.data;
switch (builtin.os.tag) {
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.kevent);
const empty_kevs = &[0]os.Kevent{};
_ = os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null) catch {
self.next_tick_queue.unget(next_tick_node);
self.available_eventfd_resume_nodes.push(resume_stack_node);
return;
};
},
.linux => {
// the pending count is already accounted for
const epoll_events = os.linux.EPOLL.ONESHOT | os.linux.EPOLL.IN | os.linux.EPOLL.OUT |
os.linux.EPOLL.ET;
self.linuxModFd(
eventfd_node.eventfd,
eventfd_node.epoll_op,
epoll_events,
&eventfd_node.base,
) catch {
self.next_tick_queue.unget(next_tick_node);
self.available_eventfd_resume_nodes.push(resume_stack_node);
return;
};
},
.windows => {
windows.PostQueuedCompletionStatus(
self.os_data.io_port,
undefined,
undefined,
&eventfd_node.base.overlapped,
) catch {
self.next_tick_queue.unget(next_tick_node);
self.available_eventfd_resume_nodes.push(resume_stack_node);
return;
};
},
else => @compileError("unsupported OS"),
}
}
}
/// Bring your own linked list node. This means it can't fail.
pub fn onNextTick(self: *Loop, node: *NextTickNode) void {
self.beginOneEvent(); // finished in dispatch()
self.next_tick_queue.put(node);
self.dispatch();
}
pub fn cancelOnNextTick(self: *Loop, node: *NextTickNode) void {
if (self.next_tick_queue.remove(node)) {
self.finishOneEvent();
}
}
pub fn run(self: *Loop) void {
self.finishOneEvent(); // the reference we start with
self.workerRun();
if (!builtin.single_threaded) {
switch (builtin.os.tag) {
.linux,
.macos,
.freebsd,
.netbsd,
.dragonfly,
.openbsd,
=> self.fs_thread.join(),
else => {},
}
}
for (self.extra_threads) |extra_thread| {
extra_thread.join();
}
@atomicStore(bool, &self.delay_queue.is_running, false, .SeqCst);
self.delay_queue.event.set();
self.delay_queue.thread.join();
}
/// Runs the provided function asynchronously. The function's frame is allocated
/// with `allocator` and freed when the function returns.
/// `func` must return void and it can be an async function.
/// Yields to the event loop, running the function on the next tick.
pub fn runDetached(self: *Loop, alloc: *mem.Allocator, comptime func: anytype, args: anytype) error{OutOfMemory}!void {
if (!std.io.is_async) @compileError("Can't use runDetached in non-async mode!");
if (@TypeOf(@call(.{}, func, args)) != void) {
@compileError("`func` must not have a return value");
}
const Wrapper = struct {
const Args = @TypeOf(args);
fn run(func_args: Args, loop: *Loop, allocator: *mem.Allocator) void {
loop.beginOneEvent();
loop.yield();
@call(.{}, func, func_args); // compile error when called with non-void ret type
suspend {
loop.finishOneEvent();
allocator.destroy(@frame());
}
}
};
var run_frame = try alloc.create(@Frame(Wrapper.run));
run_frame.* = async Wrapper.run(args, self, alloc);
}
/// Yielding lets the event loop run, starting any unstarted async operations.
/// Note that async operations automatically start when a function yields for any other reason,
/// for example, when async I/O is performed. This function is intended to be used only when
/// CPU bound tasks would be waiting in the event loop but never get started because no async I/O
/// is performed.
pub fn yield(self: *Loop) void {
suspend {
var my_tick_node = NextTickNode{
.prev = undefined,
.next = undefined,
.data = @frame(),
};
self.onNextTick(&my_tick_node);
}
}
/// If the build is multi-threaded and there is an event loop, then it calls `yield`. Otherwise,
/// does nothing.
pub fn startCpuBoundOperation() void {
if (builtin.single_threaded) {
return;
} else if (instance) |event_loop| {
event_loop.yield();
}
}
/// call finishOneEvent when done
pub fn beginOneEvent(self: *Loop) void {
_ = @atomicRmw(usize, &self.pending_event_count, .Add, 1, .SeqCst);
}
pub fn finishOneEvent(self: *Loop) void {
nosuspend {
const prev = @atomicRmw(usize, &self.pending_event_count, .Sub, 1, .SeqCst);
if (prev != 1) return;
// cause all the threads to stop
self.posixFsRequest(&self.fs_end_request);
switch (builtin.os.tag) {
.linux => {
// writing to the eventfd will only wake up one thread, thus multiple writes
// are needed to wakeup all the threads
var i: usize = 0;
while (i < self.extra_threads.len + 1) : (i += 1) {
// writing 8 bytes to an eventfd cannot fail
const amt = os.write(self.os_data.final_eventfd, &wakeup_bytes) catch unreachable;
assert(amt == wakeup_bytes.len);
}
return;
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
const final_kevent = @as(*const [1]os.Kevent, &self.os_data.final_kevent);
const empty_kevs = &[0]os.Kevent{};
// cannot fail because we already added it and this just enables it
_ = os.kevent(self.os_data.kqfd, final_kevent, empty_kevs, null) catch unreachable;
return;
},
.windows => {
var i: usize = 0;
while (i < self.extra_threads.len + 1) : (i += 1) {
while (true) {
const overlapped = &self.final_resume_node.overlapped;
windows.PostQueuedCompletionStatus(self.os_data.io_port, undefined, undefined, overlapped) catch continue;
break;
}
}
return;
},
else => @compileError("unsupported OS"),
}
}
}
pub fn sleep(self: *Loop, nanoseconds: u64) void {
if (builtin.single_threaded)
@compileError("TODO: integrate timers with epoll/kevent/iocp for single-threaded");
suspend {
const now = self.delay_queue.timer.read();
var entry: DelayQueue.Waiters.Entry = undefined;
entry.init(@frame(), now + nanoseconds);
self.delay_queue.waiters.insert(&entry);
// Speculatively wake up the timer thread when we add a new entry.
// If the timer thread is sleeping on a longer entry, we need to
// interrupt it so that our entry can be expired in time.
self.delay_queue.event.set();
}
}
const DelayQueue = struct {
timer: std.time.Timer,
waiters: Waiters,
thread: std.Thread,
event: std.Thread.AutoResetEvent,
is_running: bool,
/// Initialize the delay queue by spawning the timer thread
/// and starting any timer resources.
fn init(self: *DelayQueue) !void {
self.* = DelayQueue{
.timer = try std.time.Timer.start(),
.waiters = DelayQueue.Waiters{
.entries = std.atomic.Queue(anyframe).init(),
},
.event = std.Thread.AutoResetEvent{},
.is_running = true,
// Must be last so that it can read the other state, such as `is_running`.
.thread = try std.Thread.spawn(.{}, DelayQueue.run, .{self}),
};
}
/// Entry point for the timer thread
/// which waits for timer entries to expire and reschedules them.
fn run(self: *DelayQueue) void {
const loop = @fieldParentPtr(Loop, "delay_queue", self);
while (@atomicLoad(bool, &self.is_running, .SeqCst)) {
const now = self.timer.read();
if (self.waiters.popExpired(now)) |entry| {
loop.onNextTick(&entry.node);
continue;
}
if (self.waiters.nextExpire()) |expires| {
if (now >= expires)
continue;
self.event.timedWait(expires - now) catch {};
} else {
self.event.wait();
}
}
}
// TODO: use a tickless heirarchical timer wheel:
// https://github.com/wahern/timeout/
const Waiters = struct {
entries: std.atomic.Queue(anyframe),
const Entry = struct {
node: NextTickNode,
expires: u64,
fn init(self: *Entry, frame: anyframe, expires: u64) void {
self.node.data = frame;
self.expires = expires;
}
};
/// Registers the entry into the queue of waiting frames
fn insert(self: *Waiters, entry: *Entry) void {
self.entries.put(&entry.node);
}
/// Dequeues one expired event relative to `now`
fn popExpired(self: *Waiters, now: u64) ?*Entry {
const entry = self.peekExpiringEntry() orelse return null;
if (entry.expires > now)
return null;
assert(self.entries.remove(&entry.node));
return entry;
}
/// Returns an estimate for the amount of time
/// to wait until the next waiting entry expires.
fn nextExpire(self: *Waiters) ?u64 {
const entry = self.peekExpiringEntry() orelse return null;
return entry.expires;
}
fn peekExpiringEntry(self: *Waiters) ?*Entry {
const held = self.entries.mutex.acquire();
defer held.release();
// starting from the head
var head = self.entries.head orelse return null;
// traverse the list of waiting entires to
// find the Node with the smallest `expires` field
var min = head;
while (head.next) |node| {
const minEntry = @fieldParentPtr(Entry, "node", min);
const nodeEntry = @fieldParentPtr(Entry, "node", node);
if (nodeEntry.expires < minEntry.expires)
min = node;
head = node;
}
return @fieldParentPtr(Entry, "node", min);
}
};
};
/// ------- I/0 APIs -------
pub fn accept(
self: *Loop,
/// This argument is a socket that has been created with `socket`, bound to a local address
/// with `bind`, and is listening for connections after a `listen`.
sockfd: os.socket_t,
/// This argument is a pointer to a sockaddr structure. This structure is filled in with the
/// address of the peer socket, as known to the communications layer. The exact format of the
/// address returned addr is determined by the socket's address family (see `socket` and the
/// respective protocol man pages).
addr: *os.sockaddr,
/// This argument is a value-result argument: the caller must initialize it to contain the
/// size (in bytes) of the structure pointed to by addr; on return it will contain the actual size
/// of the peer address.
///
/// The returned address is truncated if the buffer provided is too small; in this case, `addr_size`
/// will return a value greater than was supplied to the call.
addr_size: *os.socklen_t,
/// The following values can be bitwise ORed in flags to obtain different behavior:
/// * `SOCK.CLOEXEC` - Set the close-on-exec (`FD_CLOEXEC`) flag on the new file descriptor. See the
/// description of the `O.CLOEXEC` flag in `open` for reasons why this may be useful.
flags: u32,
) os.AcceptError!os.socket_t {
while (true) {
return os.accept(sockfd, addr, addr_size, flags | os.SOCK.NONBLOCK) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(sockfd);
continue;
},
else => return err,
};
}
}
pub fn connect(self: *Loop, sockfd: os.socket_t, sock_addr: *const os.sockaddr, len: os.socklen_t) os.ConnectError!void {
os.connect(sockfd, sock_addr, len) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(sockfd);
return os.getsockoptError(sockfd);
},
else => return err,
};
}
/// Performs an async `os.open` using a separate thread.
pub fn openZ(self: *Loop, file_path: [*:0]const u8, flags: u32, mode: os.mode_t) os.OpenError!os.fd_t {
var req_node = Request.Node{
.data = .{
.msg = .{
.open = .{
.path = file_path,
.flags = flags,
.mode = mode,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.open.result;
}
/// Performs an async `os.opent` using a separate thread.
pub fn openatZ(self: *Loop, fd: os.fd_t, file_path: [*:0]const u8, flags: u32, mode: os.mode_t) os.OpenError!os.fd_t {
var req_node = Request.Node{
.data = .{
.msg = .{
.openat = .{
.fd = fd,
.path = file_path,
.flags = flags,
.mode = mode,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.openat.result;
}
/// Performs an async `os.close` using a separate thread.
pub fn close(self: *Loop, fd: os.fd_t) void {
var req_node = Request.Node{
.data = .{
.msg = .{ .close = .{ .fd = fd } },
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
}
/// Performs an async `os.read` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn read(self: *Loop, fd: os.fd_t, buf: []u8, simulate_evented: bool) os.ReadError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.read = .{
.fd = fd,
.buf = buf,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.read.result;
} else {
while (true) {
return os.read(fd, buf) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.readv` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn readv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, simulate_evented: bool) os.ReadError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.readv = .{
.fd = fd,
.iov = iov,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.readv.result;
} else {
while (true) {
return os.readv(fd, iov) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.pread` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn pread(self: *Loop, fd: os.fd_t, buf: []u8, offset: u64, simulate_evented: bool) os.PReadError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.pread = .{
.fd = fd,
.buf = buf,
.offset = offset,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.pread.result;
} else {
while (true) {
return os.pread(fd, buf, offset) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.preadv` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn preadv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, offset: u64, simulate_evented: bool) os.ReadError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.preadv = .{
.fd = fd,
.iov = iov,
.offset = offset,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.preadv.result;
} else {
while (true) {
return os.preadv(fd, iov, offset) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.write` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn write(self: *Loop, fd: os.fd_t, bytes: []const u8, simulate_evented: bool) os.WriteError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.write = .{
.fd = fd,
.bytes = bytes,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.write.result;
} else {
while (true) {
return os.write(fd, bytes) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.writev` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn writev(self: *Loop, fd: os.fd_t, iov: []const os.iovec_const, simulate_evented: bool) os.WriteError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.writev = .{
.fd = fd,
.iov = iov,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.writev.result;
} else {
while (true) {
return os.writev(fd, iov) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.pwrite` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn pwrite(self: *Loop, fd: os.fd_t, bytes: []const u8, offset: u64, simulate_evented: bool) os.PerformsWriteError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.pwrite = .{
.fd = fd,
.bytes = bytes,
.offset = offset,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.pwrite.result;
} else {
while (true) {
return os.pwrite(fd, bytes, offset) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(fd);
continue;
},
else => return err,
};
}
}
}
/// Performs an async `os.pwritev` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn pwritev(self: *Loop, fd: os.fd_t, iov: []const os.iovec_const, offset: u64, simulate_evented: bool) os.PWriteError!usize {
if (simulate_evented) {
var req_node = Request.Node{
.data = .{
.msg = .{
.pwritev = .{
.fd = fd,
.iov = iov,
.offset = offset,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.pwritev.result;
} else {
while (true) {
return os.pwritev(fd, iov, offset) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(fd);
continue;
},
else => return err,
};
}
}
}
pub fn sendto(
self: *Loop,
/// The file descriptor of the sending socket.
sockfd: os.fd_t,
/// Message to send.
buf: []const u8,
flags: u32,
dest_addr: ?*const os.sockaddr,
addrlen: os.socklen_t,
) os.SendToError!usize {
while (true) {
return os.sendto(sockfd, buf, flags, dest_addr, addrlen) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdWritable(sockfd);
continue;
},
else => return err,
};
}
}
pub fn recvfrom(
self: *Loop,
sockfd: os.fd_t,
buf: []u8,
flags: u32,
src_addr: ?*os.sockaddr,
addrlen: ?*os.socklen_t,
) os.RecvFromError!usize {
while (true) {
return os.recvfrom(sockfd, buf, flags, src_addr, addrlen) catch |err| switch (err) {
error.WouldBlock => {
self.waitUntilFdReadable(sockfd);
continue;
},
else => return err,
};
}
}
/// Performs an async `os.faccessatZ` using a separate thread.
/// `fd` must block and not return EAGAIN.
pub fn faccessatZ(
self: *Loop,
dirfd: os.fd_t,
path_z: [*:0]const u8,
mode: u32,
flags: u32,
) os.AccessError!void {
var req_node = Request.Node{
.data = .{
.msg = .{
.faccessat = .{
.dirfd = dirfd,
.path = path_z,
.mode = mode,
.flags = flags,
.result = undefined,
},
},
.finish = .{ .TickNode = .{ .data = @frame() } },
},
};
suspend {
self.posixFsRequest(&req_node);
}
return req_node.data.msg.faccessat.result;
}
fn workerRun(self: *Loop) void {
while (true) {
while (true) {
const next_tick_node = self.next_tick_queue.get() orelse break;
self.dispatch();
resume next_tick_node.data;
self.finishOneEvent();
}
switch (builtin.os.tag) {
.linux => {
// only process 1 event so we don't steal from other threads
var events: [1]os.linux.epoll_event = undefined;
const count = os.epoll_wait(self.os_data.epollfd, events[0..], -1);
for (events[0..count]) |ev| {
const resume_node = @as(*ResumeNode, @ptrFromInt(ev.data.ptr));
const handle = resume_node.handle;
const resume_node_id = resume_node.id;
switch (resume_node_id) {
.Basic => {},
.Stop => return,
.EventFd => {
const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node);
event_fd_node.epoll_op = os.linux.EPOLL.CTL_MOD;
const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node);
self.available_eventfd_resume_nodes.push(stack_node);
},
}
resume handle;
if (resume_node_id == ResumeNode.Id.EventFd) {
self.finishOneEvent();
}
}
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
var eventlist: [1]os.Kevent = undefined;
const empty_kevs = &[0]os.Kevent{};
const count = os.kevent(self.os_data.kqfd, empty_kevs, eventlist[0..], null) catch unreachable;
for (eventlist[0..count]) |ev| {
const resume_node = @as(*ResumeNode, @ptrFromInt(ev.udata));
const handle = resume_node.handle;
const resume_node_id = resume_node.id;
switch (resume_node_id) {
.Basic => {
const basic_node = @fieldParentPtr(ResumeNode.Basic, "base", resume_node);
basic_node.kev = ev;
},
.Stop => return,
.EventFd => {
const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node);
const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node);
self.available_eventfd_resume_nodes.push(stack_node);
},
}
resume handle;
if (resume_node_id == ResumeNode.Id.EventFd) {
self.finishOneEvent();
}
}
},
.windows => {
var completion_key: usize = undefined;
const overlapped = while (true) {
var nbytes: windows.DWORD = undefined;
var overlapped: ?*windows.OVERLAPPED = undefined;
switch (windows.GetQueuedCompletionStatus(self.os_data.io_port, &nbytes, &completion_key, &overlapped, windows.INFINITE)) {
.Aborted => return,
.Normal => {},
.EOF => {},
.Cancelled => continue,
}
if (overlapped) |o| break o;
} else unreachable; // TODO else unreachable should not be necessary
const resume_node = @fieldParentPtr(ResumeNode, "overlapped", overlapped);
const handle = resume_node.handle;
const resume_node_id = resume_node.id;
switch (resume_node_id) {
.Basic => {},
.Stop => return,
.EventFd => {
const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node);
const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node);
self.available_eventfd_resume_nodes.push(stack_node);
},
}
resume handle;
self.finishOneEvent();
},
else => @compileError("unsupported OS"),
}
}
}
fn posixFsRequest(self: *Loop, request_node: *Request.Node) void {
self.beginOneEvent(); // finished in posixFsRun after processing the msg
self.fs_queue.put(request_node);
self.fs_thread_wakeup.set();
}
fn posixFsCancel(self: *Loop, request_node: *Request.Node) void {
if (self.fs_queue.remove(request_node)) {
self.finishOneEvent();
}
}
fn posixFsRun(self: *Loop) void {
nosuspend while (true) {
self.fs_thread_wakeup.reset();
while (self.fs_queue.get()) |node| {
switch (node.data.msg) {
.end => return,
.read => |*msg| {
msg.result = os.read(msg.fd, msg.buf);
},
.readv => |*msg| {
msg.result = os.readv(msg.fd, msg.iov);
},
.write => |*msg| {
msg.result = os.write(msg.fd, msg.bytes);
},
.writev => |*msg| {
msg.result = os.writev(msg.fd, msg.iov);
},
.pwrite => |*msg| {
msg.result = os.pwrite(msg.fd, msg.bytes, msg.offset);
},
.pwritev => |*msg| {
msg.result = os.pwritev(msg.fd, msg.iov, msg.offset);
},
.pread => |*msg| {
msg.result = os.pread(msg.fd, msg.buf, msg.offset);
},
.preadv => |*msg| {
msg.result = os.preadv(msg.fd, msg.iov, msg.offset);
},
.open => |*msg| {
if (is_windows) unreachable; // TODO
msg.result = os.openZ(msg.path, msg.flags, msg.mode);
},
.openat => |*msg| {
if (is_windows) unreachable; // TODO
msg.result = os.openatZ(msg.fd, msg.path, msg.flags, msg.mode);
},
.faccessat => |*msg| {
msg.result = os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags);
},
.close => |*msg| os.close(msg.fd),
}
switch (node.data.finish) {
.TickNode => |*tick_node| self.onNextTick(tick_node),
.NoAction => {},
}
self.finishOneEvent();
}
self.fs_thread_wakeup.wait();
};
}
const OsData = switch (builtin.os.tag) {
.linux => LinuxOsData,
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventData,
.windows => struct {
io_port: windows.HANDLE,
extra_thread_count: usize,
},
else => struct {},
};
const KEventData = struct {
kqfd: i32,
final_kevent: os.Kevent,
};
const LinuxOsData = struct {
epollfd: i32,
final_eventfd: i32,
final_eventfd_event: os.linux.epoll_event,
};
pub const Request = struct {
msg: Msg,
finish: Finish,
pub const Node = std.atomic.Queue(Request).Node;
pub const Finish = union(enum) {
TickNode: Loop.NextTickNode,
NoAction,
};
pub const Msg = union(enum) {
read: Read,
readv: ReadV,
write: Write,
writev: WriteV,
pwrite: PWrite,
pwritev: PWriteV,
pread: PRead,
preadv: PReadV,
open: Open,
openat: OpenAt,
close: Close,
faccessat: FAccessAt,
/// special - means the fs thread should exit
end,
pub const Read = struct {
fd: os.fd_t,
buf: []u8,
result: Error!usize,
pub const Error = os.ReadError;
};
pub const ReadV = struct {
fd: os.fd_t,
iov: []const os.iovec,
result: Error!usize,
pub const Error = os.ReadError;
};
pub const Write = struct {
fd: os.fd_t,
bytes: []const u8,
result: Error!usize,
pub const Error = os.WriteError;
};
pub const WriteV = struct {
fd: os.fd_t,
iov: []const os.iovec_const,
result: Error!usize,
pub const Error = os.WriteError;
};
pub const PWrite = struct {
fd: os.fd_t,
bytes: []const u8,
offset: usize,
result: Error!usize,
pub const Error = os.PWriteError;
};
pub const PWriteV = struct {
fd: os.fd_t,
iov: []const os.iovec_const,
offset: usize,
result: Error!usize,
pub const Error = os.PWriteError;
};
pub const PRead = struct {
fd: os.fd_t,
buf: []u8,
offset: usize,
result: Error!usize,
pub const Error = os.PReadError;
};
pub const PReadV = struct {
fd: os.fd_t,
iov: []const os.iovec,
offset: usize,
result: Error!usize,
pub const Error = os.PReadError;
};
pub const Open = struct {
path: [*:0]const u8,
flags: u32,
mode: os.mode_t,
result: Error!os.fd_t,
pub const Error = os.OpenError;
};
pub const OpenAt = struct {
fd: os.fd_t,
path: [*:0]const u8,
flags: u32,
mode: os.mode_t,
result: Error!os.fd_t,
pub const Error = os.OpenError;
};
pub const Close = struct {
fd: os.fd_t,
};
pub const FAccessAt = struct {
dirfd: os.fd_t,
path: [*:0]const u8,
mode: u32,
flags: u32,
result: Error!void,
pub const Error = os.AccessError;
};
};
};
};
test "std.event.Loop - basic" {
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
if (true) {
// https://github.com/ziglang/zig/issues/4922
return error.SkipZigTest;
}
var loop: Loop = undefined;
try loop.initMultiThreaded();
defer loop.deinit();
loop.run();
}
fn testEventLoop() i32 {
return 1234;
}
fn testEventLoop2(h: anyframe->i32, did_it: *bool) void {
const value = await h;
try testing.expect(value == 1234);
did_it.* = true;
}
var testRunDetachedData: usize = 0;
test "std.event.Loop - runDetached" {
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
if (!std.io.is_async) return error.SkipZigTest;
if (true) {
// https://github.com/ziglang/zig/issues/4922
return error.SkipZigTest;
}
var loop: Loop = undefined;
try loop.initMultiThreaded();
defer loop.deinit();
// Schedule the execution, won't actually start until we start the
// event loop.
try loop.runDetached(std.testing.allocator, testRunDetached, .{});
// Now we can start the event loop. The function will return only
// after all tasks have been completed, allowing us to synchonize
// with the previous runDetached.
loop.run();
try testing.expect(testRunDetachedData == 1);
}
fn testRunDetached() void {
testRunDetachedData += 1;
}
test "std.event.Loop - sleep" {
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
if (!std.io.is_async) return error.SkipZigTest;
const frames = try testing.allocator.alloc(@Frame(testSleep), 10);
defer testing.allocator.free(frames);
const wait_time = 100 * std.time.ns_per_ms;
var sleep_count: usize = 0;
for (frames) |*frame|
frame.* = async testSleep(wait_time, &sleep_count);
for (frames) |*frame|
await frame;
try testing.expect(sleep_count == frames.len);
}
fn testSleep(wait_ns: u64, sleep_count: *usize) void {
Loop.instance.?.sleep(wait_ns);
_ = @atomicRmw(usize, sleep_count, .Add, 1, .SeqCst);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/event/rwlocked.zig | const std = @import("../std.zig");
const RwLock = std.event.RwLock;
/// Thread-safe async/await RW lock that protects one piece of data.
/// Functions which are waiting for the lock are suspended, and
/// are resumed when the lock is released, in order.
pub fn RwLocked(comptime T: type) type {
return struct {
lock: RwLock,
locked_data: T,
const Self = @This();
pub const HeldReadLock = struct {
value: *const T,
held: RwLock.HeldRead,
pub fn release(self: HeldReadLock) void {
self.held.release();
}
};
pub const HeldWriteLock = struct {
value: *T,
held: RwLock.HeldWrite,
pub fn release(self: HeldWriteLock) void {
self.held.release();
}
};
pub fn init(data: T) Self {
return Self{
.lock = RwLock.init(),
.locked_data = data,
};
}
pub fn deinit(self: *Self) void {
self.lock.deinit();
}
pub fn acquireRead(self: *Self) callconv(.Async) HeldReadLock {
return HeldReadLock{
.held = self.lock.acquireRead(),
.value = &self.locked_data,
};
}
pub fn acquireWrite(self: *Self) callconv(.Async) HeldWriteLock {
return HeldWriteLock{
.held = self.lock.acquireWrite(),
.value = &self.locked_data,
};
}
};
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/os/io.zig | const std = @import("../../std.zig");
const builtin = @import("builtin");
const os = std.os;
const mem = std.mem;
const testing = std.testing;
const native_os = builtin.os;
const linux = std.os.linux;
/// POSIX `iovec`, or Windows `WSABUF`. The difference between the two are the ordering
/// of fields, alongside the length being represented as either a ULONG or a size_t.
pub const Buffer = if (native_os.tag == .windows)
extern struct {
len: c_ulong,
ptr: usize,
pub fn from(slice: []const u8) Buffer {
return .{ .len = @as(c_ulong, @intCast(slice.len)), .ptr = @intFromPtr(slice.ptr) };
}
pub fn into(self: Buffer) []const u8 {
return @as([*]const u8, @ptrFromInt(self.ptr))[0..self.len];
}
pub fn intoMutable(self: Buffer) []u8 {
return @as([*]u8, @ptrFromInt(self.ptr))[0..self.len];
}
}
else
extern struct {
ptr: usize,
len: usize,
pub fn from(slice: []const u8) Buffer {
return .{ .ptr = @intFromPtr(slice.ptr), .len = slice.len };
}
pub fn into(self: Buffer) []const u8 {
return @as([*]const u8, @ptrFromInt(self.ptr))[0..self.len];
}
pub fn intoMutable(self: Buffer) []u8 {
return @as([*]u8, @ptrFromInt(self.ptr))[0..self.len];
}
};
pub const Reactor = struct {
pub const InitFlags = enum {
close_on_exec,
};
pub const Event = struct {
data: usize,
is_error: bool,
is_hup: bool,
is_readable: bool,
is_writable: bool,
};
pub const Interest = struct {
hup: bool = false,
oneshot: bool = false,
readable: bool = false,
writable: bool = false,
};
fd: os.fd_t,
pub fn init(flags: std.enums.EnumFieldStruct(Reactor.InitFlags, bool, false)) !Reactor {
var raw_flags: u32 = 0;
const set = std.EnumSet(Reactor.InitFlags).init(flags);
if (set.contains(.close_on_exec)) raw_flags |= linux.EPOLL.CLOEXEC;
return Reactor{ .fd = try os.epoll_create1(raw_flags) };
}
pub fn deinit(self: Reactor) void {
os.close(self.fd);
}
pub fn update(self: Reactor, fd: os.fd_t, identifier: usize, interest: Reactor.Interest) !void {
var flags: u32 = 0;
flags |= if (interest.oneshot) linux.EPOLL.ONESHOT else linux.EPOLL.ET;
if (interest.hup) flags |= linux.EPOLL.RDHUP;
if (interest.readable) flags |= linux.EPOLL.IN;
if (interest.writable) flags |= linux.EPOLL.OUT;
const event = &linux.epoll_event{
.events = flags,
.data = .{ .ptr = identifier },
};
os.epoll_ctl(self.fd, linux.EPOLL.CTL_MOD, fd, event) catch |err| switch (err) {
error.FileDescriptorNotRegistered => try os.epoll_ctl(self.fd, linux.EPOLL.CTL_ADD, fd, event),
else => return err,
};
}
pub fn poll(self: Reactor, comptime max_num_events: comptime_int, closure: anytype, timeout_milliseconds: ?u64) !void {
var events: [max_num_events]linux.epoll_event = undefined;
const num_events = os.epoll_wait(self.fd, &events, if (timeout_milliseconds) |ms| @as(i32, @intCast(ms)) else -1);
for (events[0..num_events]) |ev| {
const is_error = ev.events & linux.EPOLL.ERR != 0;
const is_hup = ev.events & (linux.EPOLL.HUP | linux.EPOLL.RDHUP) != 0;
const is_readable = ev.events & linux.EPOLL.IN != 0;
const is_writable = ev.events & linux.EPOLL.OUT != 0;
try closure.call(Reactor.Event{
.data = ev.data.ptr,
.is_error = is_error,
.is_hup = is_hup,
.is_readable = is_readable,
.is_writable = is_writable,
});
}
}
};
test "reactor/linux: drive async tcp client/listener pair" {
if (native_os.tag != .linux) return error.SkipZigTest;
const ip = std.x.net.ip;
const tcp = std.x.net.tcp;
const IPv4 = std.x.os.IPv4;
const IPv6 = std.x.os.IPv6;
const reactor = try Reactor.init(.{ .close_on_exec = true });
defer reactor.deinit();
const listener = try tcp.Listener.init(.ip, .{
.close_on_exec = true,
.nonblocking = true,
});
defer listener.deinit();
try reactor.update(listener.socket.fd, 0, .{ .readable = true });
try reactor.poll(1, struct {
fn call(event: Reactor.Event) !void {
try testing.expectEqual(Reactor.Event{
.data = 0,
.is_error = false,
.is_hup = true,
.is_readable = false,
.is_writable = false,
}, event);
}
}, null);
try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0));
try listener.listen(128);
var binded_address = try listener.getLocalAddress();
switch (binded_address) {
.ipv4 => |*ipv4| ipv4.host = IPv4.localhost,
.ipv6 => |*ipv6| ipv6.host = IPv6.localhost,
}
const client = try tcp.Client.init(.ip, .{
.close_on_exec = true,
.nonblocking = true,
});
defer client.deinit();
try reactor.update(client.socket.fd, 1, .{ .readable = true, .writable = true });
try reactor.poll(1, struct {
fn call(event: Reactor.Event) !void {
try testing.expectEqual(Reactor.Event{
.data = 1,
.is_error = false,
.is_hup = true,
.is_readable = false,
.is_writable = true,
}, event);
}
}, null);
client.connect(binded_address) catch |err| switch (err) {
error.WouldBlock => {},
else => return err,
};
try reactor.poll(1, struct {
fn call(event: Reactor.Event) !void {
try testing.expectEqual(Reactor.Event{
.data = 1,
.is_error = false,
.is_hup = false,
.is_readable = false,
.is_writable = true,
}, event);
}
}, null);
try reactor.poll(1, struct {
fn call(event: Reactor.Event) !void {
try testing.expectEqual(Reactor.Event{
.data = 0,
.is_error = false,
.is_hup = false,
.is_readable = true,
.is_writable = false,
}, event);
}
}, null);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/os/socket_posix.zig | const std = @import("../../std.zig");
const os = std.os;
const mem = std.mem;
const time = std.time;
pub fn Mixin(comptime Socket: type) type {
return struct {
/// Open a new socket.
pub fn init(domain: u32, socket_type: u32, protocol: u32, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Socket {
var raw_flags: u32 = socket_type;
const set = std.EnumSet(Socket.InitFlags).init(flags);
if (set.contains(.close_on_exec)) raw_flags |= os.SOCK.CLOEXEC;
if (set.contains(.nonblocking)) raw_flags |= os.SOCK.NONBLOCK;
return Socket{ .fd = try os.socket(domain, raw_flags, protocol) };
}
/// Closes the socket.
pub fn deinit(self: Socket) void {
os.closeSocket(self.fd);
}
/// Shutdown either the read side, write side, or all side of the socket.
pub fn shutdown(self: Socket, how: os.ShutdownHow) !void {
return os.shutdown(self.fd, how);
}
/// Binds the socket to an address.
pub fn bind(self: Socket, address: Socket.Address) !void {
return os.bind(self.fd, @as(*const os.sockaddr, @ptrCast(&address.toNative())), address.getNativeSize());
}
/// Start listening for incoming connections on the socket.
pub fn listen(self: Socket, max_backlog_size: u31) !void {
return os.listen(self.fd, max_backlog_size);
}
/// Have the socket attempt to the connect to an address.
pub fn connect(self: Socket, address: Socket.Address) !void {
return os.connect(self.fd, @as(*const os.sockaddr, @ptrCast(&address.toNative())), address.getNativeSize());
}
/// Accept a pending incoming connection queued to the kernel backlog
/// of the socket.
pub fn accept(self: Socket, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Socket.Connection {
var address: Socket.Address.Native.Storage = undefined;
var address_len: u32 = @sizeOf(Socket.Address.Native.Storage);
var raw_flags: u32 = 0;
const set = std.EnumSet(Socket.InitFlags).init(flags);
if (set.contains(.close_on_exec)) raw_flags |= os.SOCK.CLOEXEC;
if (set.contains(.nonblocking)) raw_flags |= os.SOCK.NONBLOCK;
const socket = Socket{ .fd = try os.accept(self.fd, @as(*os.sockaddr, @ptrCast(&address)), &address_len, raw_flags) };
const socket_address = Socket.Address.fromNative(@as(*os.sockaddr, @ptrCast(&address)));
return Socket.Connection.from(socket, socket_address);
}
/// Read data from the socket into the buffer provided with a set of flags
/// specified. It returns the number of bytes read into the buffer provided.
pub fn read(self: Socket, buf: []u8, flags: u32) !usize {
return os.recv(self.fd, buf, flags);
}
/// Write a buffer of data provided to the socket with a set of flags specified.
/// It returns the number of bytes that are written to the socket.
pub fn write(self: Socket, buf: []const u8, flags: u32) !usize {
return os.send(self.fd, buf, flags);
}
/// Writes multiple I/O vectors with a prepended message header to the socket
/// with a set of flags specified. It returns the number of bytes that are
/// written to the socket.
pub fn writeMessage(self: Socket, msg: Socket.Message, flags: u32) !usize {
while (true) {
const rc = os.system.sendmsg(self.fd, &msg, @as(c_int, @intCast(flags)));
return switch (os.errno(rc)) {
.SUCCESS => return @as(usize, @intCast(rc)),
.ACCES => error.AccessDenied,
.AGAIN => error.WouldBlock,
.ALREADY => error.FastOpenAlreadyInProgress,
.BADF => unreachable, // always a race condition
.CONNRESET => error.ConnectionResetByPeer,
.DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
.FAULT => unreachable, // An invalid user space address was specified for an argument.
.INTR => continue,
.INVAL => unreachable, // Invalid argument passed.
.ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
.MSGSIZE => error.MessageTooBig,
.NOBUFS => error.SystemResources,
.NOMEM => error.SystemResources,
.NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
.OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
.PIPE => error.BrokenPipe,
.AFNOSUPPORT => error.AddressFamilyNotSupported,
.LOOP => error.SymLinkLoop,
.NAMETOOLONG => error.NameTooLong,
.NOENT => error.FileNotFound,
.NOTDIR => error.NotDir,
.HOSTUNREACH => error.NetworkUnreachable,
.NETUNREACH => error.NetworkUnreachable,
.NOTCONN => error.SocketNotConnected,
.NETDOWN => error.NetworkSubsystemFailed,
else => |err| os.unexpectedErrno(err),
};
}
}
/// Read multiple I/O vectors with a prepended message header from the socket
/// with a set of flags specified. It returns the number of bytes that were
/// read into the buffer provided.
pub fn readMessage(self: Socket, msg: *Socket.Message, flags: u32) !usize {
while (true) {
const rc = os.system.recvmsg(self.fd, msg, @as(c_int, @intCast(flags)));
return switch (os.errno(rc)) {
.SUCCESS => @as(usize, @intCast(rc)),
.BADF => unreachable, // always a race condition
.FAULT => unreachable,
.INVAL => unreachable,
.NOTCONN => unreachable,
.NOTSOCK => unreachable,
.INTR => continue,
.AGAIN => error.WouldBlock,
.NOMEM => error.SystemResources,
.CONNREFUSED => error.ConnectionRefused,
.CONNRESET => error.ConnectionResetByPeer,
else => |err| os.unexpectedErrno(err),
};
}
}
/// Query the address that the socket is locally bounded to.
pub fn getLocalAddress(self: Socket) !Socket.Address {
var address: Socket.Address.Native.Storage = undefined;
var address_len: u32 = @sizeOf(Socket.Address.Native.Storage);
try os.getsockname(self.fd, @as(*os.sockaddr, @ptrCast(&address)), &address_len);
return Socket.Address.fromNative(@as(*os.sockaddr, @ptrCast(&address)));
}
/// Query the address that the socket is connected to.
pub fn getRemoteAddress(self: Socket) !Socket.Address {
var address: Socket.Address.Native.Storage = undefined;
var address_len: u32 = @sizeOf(Socket.Address.Native.Storage);
try os.getpeername(self.fd, @as(*os.sockaddr, @ptrCast(&address)), &address_len);
return Socket.Address.fromNative(@as(*os.sockaddr, @ptrCast(&address)));
}
/// Query and return the latest cached error on the socket.
pub fn getError(self: Socket) !void {
return os.getsockoptError(self.fd);
}
/// Query the read buffer size of the socket.
pub fn getReadBufferSize(self: Socket) !u32 {
var value: u32 = undefined;
var value_len: u32 = @sizeOf(u32);
const rc = os.system.getsockopt(self.fd, os.SOL.SOCKET, os.SO.RCVBUF, mem.asBytes(&value), &value_len);
return switch (os.errno(rc)) {
.SUCCESS => value,
.BADF => error.BadFileDescriptor,
.FAULT => error.InvalidAddressSpace,
.INVAL => error.InvalidSocketOption,
.NOPROTOOPT => error.UnknownSocketOption,
.NOTSOCK => error.NotASocket,
else => |err| os.unexpectedErrno(err),
};
}
/// Query the write buffer size of the socket.
pub fn getWriteBufferSize(self: Socket) !u32 {
var value: u32 = undefined;
var value_len: u32 = @sizeOf(u32);
const rc = os.system.getsockopt(self.fd, os.SOL.SOCKET, os.SO.SNDBUF, mem.asBytes(&value), &value_len);
return switch (os.errno(rc)) {
.SUCCESS => value,
.BADF => error.BadFileDescriptor,
.FAULT => error.InvalidAddressSpace,
.INVAL => error.InvalidSocketOption,
.NOPROTOOPT => error.UnknownSocketOption,
.NOTSOCK => error.NotASocket,
else => |err| os.unexpectedErrno(err),
};
}
/// Set a socket option.
pub fn setOption(self: Socket, level: u32, code: u32, value: []const u8) !void {
return os.setsockopt(self.fd, level, code, value);
}
/// Have close() or shutdown() syscalls block until all queued messages in the socket have been successfully
/// sent, or if the timeout specified in seconds has been reached. It returns `error.UnsupportedSocketOption`
/// if the host does not support the option for a socket to linger around up until a timeout specified in
/// seconds.
pub fn setLinger(self: Socket, timeout_seconds: ?u16) !void {
if (@hasDecl(os.SO, "LINGER")) {
const settings = Socket.Linger.init(timeout_seconds);
return self.setOption(os.SOL.SOCKET, os.SO.LINGER, mem.asBytes(&settings));
}
return error.UnsupportedSocketOption;
}
/// On connection-oriented sockets, have keep-alive messages be sent periodically. The timing in which keep-alive
/// messages are sent are dependant on operating system settings. It returns `error.UnsupportedSocketOption` if
/// the host does not support periodically sending keep-alive messages on connection-oriented sockets.
pub fn setKeepAlive(self: Socket, enabled: bool) !void {
if (@hasDecl(os.SO, "KEEPALIVE")) {
return self.setOption(os.SOL.SOCKET, os.SO.KEEPALIVE, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
return error.UnsupportedSocketOption;
}
/// Allow multiple sockets on the same host to listen on the same address. It returns `error.UnsupportedSocketOption` if
/// the host does not support sockets listening the same address.
pub fn setReuseAddress(self: Socket, enabled: bool) !void {
if (@hasDecl(os.SO, "REUSEADDR")) {
return self.setOption(os.SOL.SOCKET, os.SO.REUSEADDR, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
return error.UnsupportedSocketOption;
}
/// Allow multiple sockets on the same host to listen on the same port. It returns `error.UnsupportedSocketOption` if
/// the host does not supports sockets listening on the same port.
pub fn setReusePort(self: Socket, enabled: bool) !void {
if (@hasDecl(os.SO, "REUSEPORT")) {
return self.setOption(os.SOL.SOCKET, os.SO.REUSEPORT, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
return error.UnsupportedSocketOption;
}
/// Set the write buffer size of the socket.
pub fn setWriteBufferSize(self: Socket, size: u32) !void {
return self.setOption(os.SOL.SOCKET, os.SO.SNDBUF, mem.asBytes(&size));
}
/// Set the read buffer size of the socket.
pub fn setReadBufferSize(self: Socket, size: u32) !void {
return self.setOption(os.SOL.SOCKET, os.SO.RCVBUF, mem.asBytes(&size));
}
/// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is
/// set on a non-blocking socket.
///
/// Set a timeout on the socket that is to occur if no messages are successfully written
/// to its bound destination after a specified number of milliseconds. A subsequent write
/// to the socket will thereafter return `error.WouldBlock` should the timeout be exceeded.
pub fn setWriteTimeout(self: Socket, milliseconds: usize) !void {
const timeout = os.timeval{
.tv_sec = @as(i32, @intCast(milliseconds / time.ms_per_s)),
.tv_usec = @as(i32, @intCast((milliseconds % time.ms_per_s) * time.us_per_ms)),
};
return self.setOption(os.SOL.SOCKET, os.SO.SNDTIMEO, mem.asBytes(&timeout));
}
/// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is
/// set on a non-blocking socket.
///
/// Set a timeout on the socket that is to occur if no messages are successfully read
/// from its bound destination after a specified number of milliseconds. A subsequent
/// read from the socket will thereafter return `error.WouldBlock` should the timeout be
/// exceeded.
pub fn setReadTimeout(self: Socket, milliseconds: usize) !void {
const timeout = os.timeval{
.tv_sec = @as(i32, @intCast(milliseconds / time.ms_per_s)),
.tv_usec = @as(i32, @intCast((milliseconds % time.ms_per_s) * time.us_per_ms)),
};
return self.setOption(os.SOL.SOCKET, os.SO.RCVTIMEO, mem.asBytes(&timeout));
}
};
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/os/socket.zig | const std = @import("../../std.zig");
const builtin = @import("builtin");
const net = @import("net.zig");
const os = std.os;
const fmt = std.fmt;
const mem = std.mem;
const time = std.time;
const meta = std.meta;
const native_os = builtin.os;
const native_endian = builtin.cpu.arch.endian();
const Buffer = std.x.os.Buffer;
const assert = std.debug.assert;
/// A generic, cross-platform socket abstraction.
pub const Socket = struct {
/// A socket-address pair.
pub const Connection = struct {
socket: Socket,
address: Socket.Address,
/// Enclose a socket and address into a socket-address pair.
pub fn from(socket: Socket, address: Socket.Address) Socket.Connection {
return .{ .socket = socket, .address = address };
}
};
/// A generic socket address abstraction. It is safe to directly access and modify
/// the fields of a `Socket.Address`.
pub const Address = union(enum) {
pub const Native = struct {
pub const requires_prepended_length = native_os.getVersionRange() == .semver;
pub const Length = if (requires_prepended_length) u8 else [0]u8;
pub const Family = if (requires_prepended_length) u8 else c_ushort;
/// POSIX `sockaddr.storage`. The expected size and alignment is specified in IETF RFC 2553.
pub const Storage = extern struct {
pub const expected_size = os.sockaddr.SS_MAXSIZE;
pub const expected_alignment = 8;
pub const padding_size = expected_size -
mem.alignForward(@sizeOf(Address.Native.Length), expected_alignment) -
mem.alignForward(@sizeOf(Address.Native.Family), expected_alignment);
len: Address.Native.Length align(expected_alignment) = undefined,
family: Address.Native.Family align(expected_alignment) = undefined,
padding: [padding_size]u8 align(expected_alignment) = undefined,
comptime {
assert(@sizeOf(Storage) == Storage.expected_size);
assert(@alignOf(Storage) == Storage.expected_alignment);
}
};
};
ipv4: net.IPv4.Address,
ipv6: net.IPv6.Address,
/// Instantiate a new address with a IPv4 host and port.
pub fn initIPv4(host: net.IPv4, port: u16) Socket.Address {
return .{ .ipv4 = .{ .host = host, .port = port } };
}
/// Instantiate a new address with a IPv6 host and port.
pub fn initIPv6(host: net.IPv6, port: u16) Socket.Address {
return .{ .ipv6 = .{ .host = host, .port = port } };
}
/// Parses a `sockaddr` into a generic socket address.
pub fn fromNative(address: *align(4) const os.sockaddr) Socket.Address {
switch (address.family) {
os.AF.INET => {
const info = @as(*const os.sockaddr.in, @ptrCast(address));
const host = net.IPv4{ .octets = @as([4]u8, @bitCast(info.addr)) };
const port = mem.bigToNative(u16, info.port);
return Socket.Address.initIPv4(host, port);
},
os.AF.INET6 => {
const info = @as(*const os.sockaddr.in6, @ptrCast(address));
const host = net.IPv6{ .octets = info.addr, .scope_id = info.scope_id };
const port = mem.bigToNative(u16, info.port);
return Socket.Address.initIPv6(host, port);
},
else => unreachable,
}
}
/// Encodes a generic socket address into an extern union that may be reliably
/// casted into a `sockaddr` which may be passed into socket syscalls.
pub fn toNative(self: Socket.Address) extern union {
ipv4: os.sockaddr.in,
ipv6: os.sockaddr.in6,
} {
return switch (self) {
.ipv4 => |address| .{
.ipv4 = .{
.addr = @as(u32, @bitCast(address.host.octets)),
.port = mem.nativeToBig(u16, address.port),
},
},
.ipv6 => |address| .{
.ipv6 = .{
.addr = address.host.octets,
.port = mem.nativeToBig(u16, address.port),
.scope_id = address.host.scope_id,
.flowinfo = 0,
},
},
};
}
/// Returns the number of bytes that make up the `sockaddr` equivalent to the address.
pub fn getNativeSize(self: Socket.Address) u32 {
return switch (self) {
.ipv4 => @sizeOf(os.sockaddr.in),
.ipv6 => @sizeOf(os.sockaddr.in6),
};
}
/// Implements the `std.fmt.format` API.
pub fn format(
self: Socket.Address,
comptime layout: []const u8,
opts: fmt.FormatOptions,
writer: anytype,
) !void {
_ = opts;
_ = layout;
switch (self) {
.ipv4 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }),
.ipv6 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }),
}
}
};
/// POSIX `msghdr`. Denotes a destination address, set of buffers, control data, and flags. Ported
/// directly from musl.
pub const Message = if (native_os.isAtLeast(.windows, .vista) != null and native_os.isAtLeast(.windows, .vista).?)
extern struct {
name: usize = @intFromPtr(@as(?[*]u8, null)),
name_len: c_int = 0,
buffers: usize = undefined,
buffers_len: c_ulong = undefined,
control: Buffer = .{
.ptr = @intFromPtr(@as(?[*]u8, null)),
.len = 0,
},
flags: c_ulong = 0,
pub usingnamespace MessageMixin(Message);
}
else if (native_os.tag == .windows)
extern struct {
name: usize = @intFromPtr(@as(?[*]u8, null)),
name_len: c_int = 0,
buffers: usize = undefined,
buffers_len: u32 = undefined,
control: Buffer = .{
.ptr = @intFromPtr(@as(?[*]u8, null)),
.len = 0,
},
flags: u32 = 0,
pub usingnamespace MessageMixin(Message);
}
else if (@sizeOf(usize) > 4 and native_endian == .Big)
extern struct {
name: usize = @intFromPtr(@as(?[*]u8, null)),
name_len: c_uint = 0,
buffers: usize = undefined,
_pad_1: c_int = 0,
buffers_len: c_int = undefined,
control: usize = @intFromPtr(@as(?[*]u8, null)),
_pad_2: c_int = 0,
control_len: c_uint = 0,
flags: c_int = 0,
pub usingnamespace MessageMixin(Message);
}
else if (@sizeOf(usize) > 4 and native_endian == .Little)
extern struct {
name: usize = @intFromPtr(@as(?[*]u8, null)),
name_len: c_uint = 0,
buffers: usize = undefined,
buffers_len: c_int = undefined,
_pad_1: c_int = 0,
control: usize = @intFromPtr(@as(?[*]u8, null)),
control_len: c_uint = 0,
_pad_2: c_int = 0,
flags: c_int = 0,
pub usingnamespace MessageMixin(Message);
}
else
extern struct {
name: usize = @intFromPtr(@as(?[*]u8, null)),
name_len: c_uint = 0,
buffers: usize = undefined,
buffers_len: c_int = undefined,
control: usize = @intFromPtr(@as(?[*]u8, null)),
control_len: c_uint = 0,
flags: c_int = 0,
pub usingnamespace MessageMixin(Message);
};
fn MessageMixin(comptime Self: type) type {
return struct {
pub fn fromBuffers(buffers: []const Buffer) Self {
var self: Self = .{};
self.setBuffers(buffers);
return self;
}
pub fn setName(self: *Self, name: []const u8) void {
self.name = @intFromPtr(name.ptr);
self.name_len = @as(meta.fieldInfo(Self, .name_len).field_type, @intCast(name.len));
}
pub fn setBuffers(self: *Self, buffers: []const Buffer) void {
self.buffers = @intFromPtr(buffers.ptr);
self.buffers_len = @as(meta.fieldInfo(Self, .buffers_len).field_type, @intCast(buffers.len));
}
pub fn setControl(self: *Self, control: []const u8) void {
if (native_os.tag == .windows) {
self.control = Buffer.from(control);
} else {
self.control = @intFromPtr(control.ptr);
self.control_len = @as(meta.fieldInfo(Self, .control_len).field_type, @intCast(control.len));
}
}
pub fn setFlags(self: *Self, flags: u32) void {
self.flags = @as(meta.fieldInfo(Self, .flags).field_type, @intCast(flags));
}
pub fn getName(self: Self) []const u8 {
return @as([*]const u8, @ptrFromInt(self.name))[0..@as(usize, @intCast(self.name_len))];
}
pub fn getBuffers(self: Self) []const Buffer {
return @as([*]const Buffer, @ptrFromInt(self.buffers))[0..@as(usize, @intCast(self.buffers_len))];
}
pub fn getControl(self: Self) []const u8 {
if (native_os.tag == .windows) {
return self.control.into();
} else {
return @as([*]const u8, @ptrFromInt(self.control))[0..@as(usize, @intCast(self.control_len))];
}
}
pub fn getFlags(self: Self) u32 {
return @as(u32, @intCast(self.flags));
}
};
}
/// POSIX `linger`, denoting the linger settings of a socket.
///
/// Microsoft's documentation and glibc denote the fields to be unsigned
/// short's on Windows, whereas glibc and musl denote the fields to be
/// int's on every other platform.
pub const Linger = extern struct {
pub const Field = switch (native_os.tag) {
.windows => c_ushort,
else => c_int,
};
enabled: Field,
timeout_seconds: Field,
pub fn init(timeout_seconds: ?u16) Socket.Linger {
return .{
.enabled = @as(Socket.Linger.Field, @intCast(@intFromBool(timeout_seconds != null))),
.timeout_seconds = if (timeout_seconds) |seconds| @as(Socket.Linger.Field, @intCast(seconds)) else 0,
};
}
};
/// Possible set of flags to initialize a socket with.
pub const InitFlags = enum {
// Initialize a socket to be non-blocking.
nonblocking,
// Have a socket close itself on exec syscalls.
close_on_exec,
};
/// The underlying handle of a socket.
fd: os.socket_t,
/// Enclose a socket abstraction over an existing socket file descriptor.
pub fn from(fd: os.socket_t) Socket {
return Socket{ .fd = fd };
}
/// Mix in socket syscalls depending on the platform we are compiling against.
pub usingnamespace switch (native_os.tag) {
.windows => @import("socket_windows.zig"),
else => @import("socket_posix.zig"),
}.Mixin(Socket);
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/os/net.zig | const std = @import("../../std.zig");
const builtin = @import("builtin");
const os = std.os;
const fmt = std.fmt;
const mem = std.mem;
const math = std.math;
const testing = std.testing;
const native_os = builtin.os;
const have_ifnamesize = @hasDecl(os.system, "IFNAMESIZE");
/// Resolves a network interface name into a scope/zone ID. It returns
/// an error if either resolution fails, or if the interface name is
/// too long.
pub fn resolveScopeId(name: []const u8) !u32 {
if (have_ifnamesize) {
if (name.len >= os.IFNAMESIZE) return error.NameTooLong;
if (native_os.tag == .windows) {
var interface_name: [os.IFNAMESIZE:0]u8 = undefined;
mem.copy(u8, &interface_name, name);
interface_name[name.len] = 0;
const rc = os.windows.ws2_32.if_nametoindex(@as([*:0]const u8, @ptrCast(&interface_name)));
if (rc == 0) {
return error.InterfaceNotFound;
}
return rc;
}
const fd = try os.socket(os.AF.INET, os.SOCK.DGRAM, 0);
defer os.closeSocket(fd);
var f: os.ifreq = undefined;
mem.copy(u8, &f.ifrn.name, name);
f.ifrn.name[name.len] = 0;
try os.ioctl_SIOCGIFINDEX(fd, &f);
return @as(u32, @bitCast(f.ifru.ivalue));
}
return error.InterfaceNotFound;
}
/// An IPv4 address comprised of 4 bytes.
pub const IPv4 = extern struct {
/// A IPv4 host-port pair.
pub const Address = extern struct {
host: IPv4,
port: u16,
};
/// Octets of a IPv4 address designating the local host.
pub const localhost_octets = [_]u8{ 127, 0, 0, 1 };
/// The IPv4 address of the local host.
pub const localhost: IPv4 = .{ .octets = localhost_octets };
/// Octets of an unspecified IPv4 address.
pub const unspecified_octets = [_]u8{0} ** 4;
/// An unspecified IPv4 address.
pub const unspecified: IPv4 = .{ .octets = unspecified_octets };
/// Octets of a broadcast IPv4 address.
pub const broadcast_octets = [_]u8{255} ** 4;
/// An IPv4 broadcast address.
pub const broadcast: IPv4 = .{ .octets = broadcast_octets };
/// The prefix octet pattern of a link-local IPv4 address.
pub const link_local_prefix = [_]u8{ 169, 254 };
/// The prefix octet patterns of IPv4 addresses intended for
/// documentation.
pub const documentation_prefixes = [_][]const u8{
&[_]u8{ 192, 0, 2 },
&[_]u8{ 198, 51, 100 },
&[_]u8{ 203, 0, 113 },
};
octets: [4]u8,
/// Returns whether or not the two addresses are equal to, less than, or
/// greater than each other.
pub fn cmp(self: IPv4, other: IPv4) math.Order {
return mem.order(u8, &self.octets, &other.octets);
}
/// Returns true if both addresses are semantically equivalent.
pub fn eql(self: IPv4, other: IPv4) bool {
return mem.eql(u8, &self.octets, &other.octets);
}
/// Returns true if the address is a loopback address.
pub fn isLoopback(self: IPv4) bool {
return self.octets[0] == 127;
}
/// Returns true if the address is an unspecified IPv4 address.
pub fn isUnspecified(self: IPv4) bool {
return mem.eql(u8, &self.octets, &unspecified_octets);
}
/// Returns true if the address is a private IPv4 address.
pub fn isPrivate(self: IPv4) bool {
return self.octets[0] == 10 or
(self.octets[0] == 172 and self.octets[1] >= 16 and self.octets[1] <= 31) or
(self.octets[0] == 192 and self.octets[1] == 168);
}
/// Returns true if the address is a link-local IPv4 address.
pub fn isLinkLocal(self: IPv4) bool {
return mem.startsWith(u8, &self.octets, &link_local_prefix);
}
/// Returns true if the address is a multicast IPv4 address.
pub fn isMulticast(self: IPv4) bool {
return self.octets[0] >= 224 and self.octets[0] <= 239;
}
/// Returns true if the address is a IPv4 broadcast address.
pub fn isBroadcast(self: IPv4) bool {
return mem.eql(u8, &self.octets, &broadcast_octets);
}
/// Returns true if the address is in a range designated for documentation. Refer
/// to IETF RFC 5737 for more details.
pub fn isDocumentation(self: IPv4) bool {
inline for (documentation_prefixes) |prefix| {
if (mem.startsWith(u8, &self.octets, prefix)) {
return true;
}
}
return false;
}
/// Implements the `std.fmt.format` API.
pub fn format(
self: IPv4,
comptime layout: []const u8,
opts: fmt.FormatOptions,
writer: anytype,
) !void {
_ = opts;
if (comptime layout.len != 0 and layout[0] != 's') {
@compileError("Unsupported format specifier for IPv4 type '" ++ layout ++ "'.");
}
try fmt.format(writer, "{}.{}.{}.{}", .{
self.octets[0],
self.octets[1],
self.octets[2],
self.octets[3],
});
}
/// Set of possible errors that may encountered when parsing an IPv4
/// address.
pub const ParseError = error{
UnexpectedEndOfOctet,
TooManyOctets,
OctetOverflow,
UnexpectedToken,
IncompleteAddress,
};
/// Parses an arbitrary IPv4 address.
pub fn parse(buf: []const u8) ParseError!IPv4 {
var octets: [4]u8 = undefined;
var octet: u8 = 0;
var index: u8 = 0;
var saw_any_digits: bool = false;
for (buf) |c| {
switch (c) {
'.' => {
if (!saw_any_digits) return error.UnexpectedEndOfOctet;
if (index == 3) return error.TooManyOctets;
octets[index] = octet;
index += 1;
octet = 0;
saw_any_digits = false;
},
'0'...'9' => {
saw_any_digits = true;
octet = math.mul(u8, octet, 10) catch return error.OctetOverflow;
octet = math.add(u8, octet, c - '0') catch return error.OctetOverflow;
},
else => return error.UnexpectedToken,
}
}
if (index == 3 and saw_any_digits) {
octets[index] = octet;
return IPv4{ .octets = octets };
}
return error.IncompleteAddress;
}
/// Maps the address to its IPv6 equivalent. In most cases, you would
/// want to map the address to its IPv6 equivalent rather than directly
/// re-interpreting the address.
pub fn mapToIPv6(self: IPv4) IPv6 {
var octets: [16]u8 = undefined;
mem.copy(u8, octets[0..12], &IPv6.v4_mapped_prefix);
mem.copy(u8, octets[12..], &self.octets);
return IPv6{ .octets = octets, .scope_id = IPv6.no_scope_id };
}
/// Directly re-interprets the address to its IPv6 equivalent. In most
/// cases, you would want to map the address to its IPv6 equivalent rather
/// than directly re-interpreting the address.
pub fn toIPv6(self: IPv4) IPv6 {
var octets: [16]u8 = undefined;
mem.set(u8, octets[0..12], 0);
mem.copy(u8, octets[12..], &self.octets);
return IPv6{ .octets = octets, .scope_id = IPv6.no_scope_id };
}
};
/// An IPv6 address comprised of 16 bytes for an address, and 4 bytes
/// for a scope ID; cumulatively summing to 20 bytes in total.
pub const IPv6 = extern struct {
/// A IPv6 host-port pair.
pub const Address = extern struct {
host: IPv6,
port: u16,
};
/// Octets of a IPv6 address designating the local host.
pub const localhost_octets = [_]u8{0} ** 15 ++ [_]u8{0x01};
/// The IPv6 address of the local host.
pub const localhost: IPv6 = .{
.octets = localhost_octets,
.scope_id = no_scope_id,
};
/// Octets of an unspecified IPv6 address.
pub const unspecified_octets = [_]u8{0} ** 16;
/// An unspecified IPv6 address.
pub const unspecified: IPv6 = .{
.octets = unspecified_octets,
.scope_id = no_scope_id,
};
/// The prefix of a IPv6 address that is mapped to a IPv4 address.
pub const v4_mapped_prefix = [_]u8{0} ** 10 ++ [_]u8{0xFF} ** 2;
/// A marker value used to designate an IPv6 address with no
/// associated scope ID.
pub const no_scope_id = math.maxInt(u32);
octets: [16]u8,
scope_id: u32,
/// Returns whether or not the two addresses are equal to, less than, or
/// greater than each other.
pub fn cmp(self: IPv6, other: IPv6) math.Order {
return switch (mem.order(u8, self.octets, other.octets)) {
.eq => math.order(self.scope_id, other.scope_id),
else => |order| order,
};
}
/// Returns true if both addresses are semantically equivalent.
pub fn eql(self: IPv6, other: IPv6) bool {
return self.scope_id == other.scope_id and mem.eql(u8, &self.octets, &other.octets);
}
/// Returns true if the address is an unspecified IPv6 address.
pub fn isUnspecified(self: IPv6) bool {
return mem.eql(u8, &self.octets, &unspecified_octets);
}
/// Returns true if the address is a loopback address.
pub fn isLoopback(self: IPv6) bool {
return mem.eql(u8, self.octets[0..3], &[_]u8{ 0, 0, 0 }) and
mem.eql(u8, self.octets[12..], &[_]u8{ 0, 0, 0, 1 });
}
/// Returns true if the address maps to an IPv4 address.
pub fn mapsToIPv4(self: IPv6) bool {
return mem.startsWith(u8, &self.octets, &v4_mapped_prefix);
}
/// Returns an IPv4 address representative of the address should
/// it the address be mapped to an IPv4 address. It returns null
/// otherwise.
pub fn toIPv4(self: IPv6) ?IPv4 {
if (!self.mapsToIPv4()) return null;
return IPv4{ .octets = self.octets[12..][0..4].* };
}
/// Returns true if the address is a multicast IPv6 address.
pub fn isMulticast(self: IPv6) bool {
return self.octets[0] == 0xFF;
}
/// Returns true if the address is a unicast link local IPv6 address.
pub fn isLinkLocal(self: IPv6) bool {
return self.octets[0] == 0xFE and self.octets[1] & 0xC0 == 0x80;
}
/// Returns true if the address is a deprecated unicast site local
/// IPv6 address. Refer to IETF RFC 3879 for more details as to
/// why they are deprecated.
pub fn isSiteLocal(self: IPv6) bool {
return self.octets[0] == 0xFE and self.octets[1] & 0xC0 == 0xC0;
}
/// IPv6 multicast address scopes.
pub const Scope = enum(u8) {
interface = 1,
link = 2,
realm = 3,
admin = 4,
site = 5,
organization = 8,
global = 14,
unknown = 0xFF,
};
/// Returns the multicast scope of the address.
pub fn scope(self: IPv6) Scope {
if (!self.isMulticast()) return .unknown;
return switch (self.octets[0] & 0x0F) {
1 => .interface,
2 => .link,
3 => .realm,
4 => .admin,
5 => .site,
8 => .organization,
14 => .global,
else => .unknown,
};
}
/// Implements the `std.fmt.format` API. Specifying 'x' or 's' formats the
/// address lower-cased octets, while specifying 'X' or 'S' formats the
/// address using upper-cased ASCII octets.
///
/// The default specifier is 'x'.
pub fn format(
self: IPv6,
comptime layout: []const u8,
opts: fmt.FormatOptions,
writer: anytype,
) !void {
_ = opts;
const specifier = comptime &[_]u8{if (layout.len == 0) 'x' else switch (layout[0]) {
'x', 'X' => |specifier| specifier,
's' => 'x',
'S' => 'X',
else => @compileError("Unsupported format specifier for IPv6 type '" ++ layout ++ "'."),
}};
if (mem.startsWith(u8, &self.octets, &v4_mapped_prefix)) {
return fmt.format(writer, "::{" ++ specifier ++ "}{" ++ specifier ++ "}:{}.{}.{}.{}", .{
0xFF,
0xFF,
self.octets[12],
self.octets[13],
self.octets[14],
self.octets[15],
});
}
const zero_span = span: {
var i: usize = 0;
while (i < self.octets.len) : (i += 2) {
if (self.octets[i] == 0 and self.octets[i + 1] == 0) break;
} else break :span .{ .from = 0, .to = 0 };
const from = i;
while (i < self.octets.len) : (i += 2) {
if (self.octets[i] != 0 or self.octets[i + 1] != 0) break;
}
break :span .{ .from = from, .to = i };
};
var i: usize = 0;
while (i != 16) : (i += 2) {
if (zero_span.from != zero_span.to and i == zero_span.from) {
try writer.writeAll("::");
} else if (i >= zero_span.from and i < zero_span.to) {} else {
if (i != 0 and i != zero_span.to) try writer.writeAll(":");
const val = @as(u16, self.octets[i]) << 8 | self.octets[i + 1];
try fmt.formatIntValue(val, specifier, .{}, writer);
}
}
if (self.scope_id != no_scope_id and self.scope_id != 0) {
try fmt.format(writer, "%{d}", .{self.scope_id});
}
}
/// Set of possible errors that may encountered when parsing an IPv6
/// address.
pub const ParseError = error{
MalformedV4Mapping,
InterfaceNotFound,
UnknownScopeId,
} || IPv4.ParseError;
/// Parses an arbitrary IPv6 address, including link-local addresses.
pub fn parse(buf: []const u8) ParseError!IPv6 {
if (mem.lastIndexOfScalar(u8, buf, '%')) |index| {
const ip_slice = buf[0..index];
const scope_id_slice = buf[index + 1 ..];
if (scope_id_slice.len == 0) return error.UnknownScopeId;
const scope_id: u32 = switch (scope_id_slice[0]) {
'0'...'9' => fmt.parseInt(u32, scope_id_slice, 10),
else => resolveScopeId(scope_id_slice) catch |err| switch (err) {
error.InterfaceNotFound => return error.InterfaceNotFound,
else => err,
},
} catch return error.UnknownScopeId;
return parseWithScopeID(ip_slice, scope_id);
}
return parseWithScopeID(buf, no_scope_id);
}
/// Parses an IPv6 address with a pre-specified scope ID. Presumes
/// that the address is not a link-local address.
pub fn parseWithScopeID(buf: []const u8, scope_id: u32) ParseError!IPv6 {
var octets: [16]u8 = undefined;
var octet: u16 = 0;
var tail: [16]u8 = undefined;
var out: []u8 = &octets;
var index: u8 = 0;
var saw_any_digits: bool = false;
var abbrv: bool = false;
for (buf, 0..) |c, i| {
switch (c) {
':' => {
if (!saw_any_digits) {
if (abbrv) return error.UnexpectedToken;
if (i != 0) abbrv = true;
mem.set(u8, out[index..], 0);
out = &tail;
index = 0;
continue;
}
if (index == 14) return error.TooManyOctets;
out[index] = @as(u8, @truncate(octet >> 8));
index += 1;
out[index] = @as(u8, @truncate(octet));
index += 1;
octet = 0;
saw_any_digits = false;
},
'.' => {
if (!abbrv or out[0] != 0xFF and out[1] != 0xFF) {
return error.MalformedV4Mapping;
}
const start_index = mem.lastIndexOfScalar(u8, buf[0..i], ':').? + 1;
const v4 = try IPv4.parse(buf[start_index..]);
octets[10] = 0xFF;
octets[11] = 0xFF;
mem.copy(u8, octets[12..], &v4.octets);
return IPv6{ .octets = octets, .scope_id = scope_id };
},
else => {
saw_any_digits = true;
const digit = fmt.charToDigit(c, 16) catch return error.UnexpectedToken;
octet = math.mul(u16, octet, 16) catch return error.OctetOverflow;
octet = math.add(u16, octet, digit) catch return error.OctetOverflow;
},
}
}
if (!saw_any_digits and !abbrv) {
return error.IncompleteAddress;
}
if (index == 14) {
out[14] = @as(u8, @truncate(octet >> 8));
out[15] = @as(u8, @truncate(octet));
} else {
out[index] = @as(u8, @truncate(octet >> 8));
index += 1;
out[index] = @as(u8, @truncate(octet));
index += 1;
mem.copy(u8, octets[16 - index ..], out[0..index]);
}
return IPv6{ .octets = octets, .scope_id = scope_id };
}
};
test {
testing.refAllDecls(@This());
}
test "ip: convert to and from ipv6" {
try testing.expectFmt("::7f00:1", "{}", .{IPv4.localhost.toIPv6()});
try testing.expect(!IPv4.localhost.toIPv6().mapsToIPv4());
try testing.expectFmt("::ffff:127.0.0.1", "{}", .{IPv4.localhost.mapToIPv6()});
try testing.expect(IPv4.localhost.mapToIPv6().mapsToIPv4());
try testing.expect(IPv4.localhost.toIPv6().toIPv4() == null);
try testing.expectFmt("127.0.0.1", "{}", .{IPv4.localhost.mapToIPv6().toIPv4()});
}
test "ipv4: parse & format" {
const cases = [_][]const u8{
"0.0.0.0",
"255.255.255.255",
"1.2.3.4",
"123.255.0.91",
"127.0.0.1",
};
for (cases) |case| {
try testing.expectFmt(case, "{}", .{try IPv4.parse(case)});
}
}
test "ipv6: parse & format" {
const inputs = [_][]const u8{
"FF01:0:0:0:0:0:0:FB",
"FF01::Fb",
"::1",
"::",
"2001:db8::",
"::1234:5678",
"2001:db8::1234:5678",
"::ffff:123.5.123.5",
};
const outputs = [_][]const u8{
"ff01::fb",
"ff01::fb",
"::1",
"::",
"2001:db8::",
"::1234:5678",
"2001:db8::1234:5678",
"::ffff:123.5.123.5",
};
for (inputs, 0..) |input, i| {
try testing.expectFmt(outputs[i], "{}", .{try IPv6.parse(input)});
}
}
test "ipv6: parse & format addresses with scope ids" {
if (!have_ifnamesize) return error.SkipZigTest;
const iface = if (native_os.tag == .linux)
"lo"
else
"lo0";
const input = "FF01::FB%" ++ iface;
const output = "ff01::fb%1";
const parsed = IPv6.parse(input) catch |err| switch (err) {
error.InterfaceNotFound => return,
else => return err,
};
try testing.expectFmt(output, "{}", .{parsed});
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/os/socket_windows.zig | const std = @import("../../std.zig");
const net = @import("net.zig");
const os = std.os;
const mem = std.mem;
const windows = std.os.windows;
const ws2_32 = windows.ws2_32;
pub fn Mixin(comptime Socket: type) type {
return struct {
/// Open a new socket.
pub fn init(domain: u32, socket_type: u32, protocol: u32, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Socket {
var raw_flags: u32 = ws2_32.WSA_FLAG_OVERLAPPED;
const set = std.EnumSet(Socket.InitFlags).init(flags);
if (set.contains(.close_on_exec)) raw_flags |= ws2_32.WSA_FLAG_NO_HANDLE_INHERIT;
const fd = ws2_32.WSASocketW(
@as(i32, @intCast(domain)),
@as(i32, @intCast(socket_type)),
@as(i32, @intCast(protocol)),
null,
0,
raw_flags,
);
if (fd == ws2_32.INVALID_SOCKET) {
return switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => {
_ = try windows.WSAStartup(2, 2);
return Socket.init(domain, socket_type, protocol, flags);
},
.WSAEAFNOSUPPORT => error.AddressFamilyNotSupported,
.WSAEMFILE => error.ProcessFdQuotaExceeded,
.WSAENOBUFS => error.SystemResources,
.WSAEPROTONOSUPPORT => error.ProtocolNotSupported,
else => |err| windows.unexpectedWSAError(err),
};
}
if (set.contains(.nonblocking)) {
var enabled: c_ulong = 1;
const rc = ws2_32.ioctlsocket(fd, ws2_32.FIONBIO, &enabled);
if (rc == ws2_32.SOCKET_ERROR) {
return windows.unexpectedWSAError(ws2_32.WSAGetLastError());
}
}
return Socket{ .fd = fd };
}
/// Closes the socket.
pub fn deinit(self: Socket) void {
_ = ws2_32.closesocket(self.fd);
}
/// Shutdown either the read side, write side, or all side of the socket.
pub fn shutdown(self: Socket, how: os.ShutdownHow) !void {
const rc = ws2_32.shutdown(self.fd, switch (how) {
.recv => ws2_32.SD_RECEIVE,
.send => ws2_32.SD_SEND,
.both => ws2_32.SD_BOTH,
});
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => return error.ConnectionAborted,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEINPROGRESS => return error.BlockingOperationInProgress,
.WSAEINVAL => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOTCONN => return error.SocketNotConnected,
.WSAENOTSOCK => unreachable,
.WSANOTINITIALISED => unreachable,
else => |err| return windows.unexpectedWSAError(err),
};
}
}
/// Binds the socket to an address.
pub fn bind(self: Socket, address: Socket.Address) !void {
const rc = ws2_32.bind(self.fd, @as(*const ws2_32.sockaddr, @ptrCast(&address.toNative())), @as(c_int, @intCast(address.getNativeSize())));
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAEACCES => error.AccessDenied,
.WSAEADDRINUSE => error.AddressInUse,
.WSAEADDRNOTAVAIL => error.AddressNotAvailable,
.WSAEFAULT => error.BadAddress,
.WSAEINPROGRESS => error.WouldBlock,
.WSAEINVAL => error.AlreadyBound,
.WSAENOBUFS => error.NoEphemeralPortsAvailable,
.WSAENOTSOCK => error.NotASocket,
else => |err| windows.unexpectedWSAError(err),
};
}
}
/// Start listening for incoming connections on the socket.
pub fn listen(self: Socket, max_backlog_size: u31) !void {
const rc = ws2_32.listen(self.fd, max_backlog_size);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAEADDRINUSE => error.AddressInUse,
.WSAEISCONN => error.AlreadyConnected,
.WSAEINVAL => error.SocketNotBound,
.WSAEMFILE, .WSAENOBUFS => error.SystemResources,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAEINPROGRESS => error.WouldBlock,
else => |err| windows.unexpectedWSAError(err),
};
}
}
/// Have the socket attempt to the connect to an address.
pub fn connect(self: Socket, address: Socket.Address) !void {
const rc = ws2_32.connect(self.fd, @as(*const ws2_32.sockaddr, @ptrCast(&address.toNative())), @as(c_int, @intCast(address.getNativeSize())));
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAEADDRINUSE => error.AddressInUse,
.WSAEADDRNOTAVAIL => error.AddressNotAvailable,
.WSAECONNREFUSED => error.ConnectionRefused,
.WSAETIMEDOUT => error.ConnectionTimedOut,
.WSAEFAULT => error.BadAddress,
.WSAEINVAL => error.ListeningSocket,
.WSAEISCONN => error.AlreadyConnected,
.WSAENOTSOCK => error.NotASocket,
.WSAEACCES => error.BroadcastNotEnabled,
.WSAENOBUFS => error.SystemResources,
.WSAEAFNOSUPPORT => error.AddressFamilyNotSupported,
.WSAEINPROGRESS, .WSAEWOULDBLOCK => error.WouldBlock,
.WSAEHOSTUNREACH, .WSAENETUNREACH => error.NetworkUnreachable,
else => |err| windows.unexpectedWSAError(err),
};
}
}
/// Accept a pending incoming connection queued to the kernel backlog
/// of the socket.
pub fn accept(self: Socket, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Socket.Connection {
var address: Socket.Address.Native.Storage = undefined;
var address_len: c_int = @sizeOf(Socket.Address.Native.Storage);
const fd = ws2_32.accept(self.fd, @as(*ws2_32.sockaddr, @ptrCast(&address)), &address_len);
if (fd == ws2_32.INVALID_SOCKET) {
return switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAECONNRESET => error.ConnectionResetByPeer,
.WSAEFAULT => unreachable,
.WSAEINVAL => error.SocketNotListening,
.WSAEMFILE => error.ProcessFdQuotaExceeded,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENOBUFS => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAEWOULDBLOCK => error.WouldBlock,
else => |err| windows.unexpectedWSAError(err),
};
}
const socket = Socket.from(fd);
errdefer socket.deinit();
const socket_address = Socket.Address.fromNative(@as(*ws2_32.sockaddr, @ptrCast(&address)));
const set = std.EnumSet(Socket.InitFlags).init(flags);
if (set.contains(.nonblocking)) {
var enabled: c_ulong = 1;
const rc = ws2_32.ioctlsocket(fd, ws2_32.FIONBIO, &enabled);
if (rc == ws2_32.SOCKET_ERROR) {
return windows.unexpectedWSAError(ws2_32.WSAGetLastError());
}
}
return Socket.Connection.from(socket, socket_address);
}
/// Read data from the socket into the buffer provided with a set of flags
/// specified. It returns the number of bytes read into the buffer provided.
pub fn read(self: Socket, buf: []u8, flags: u32) !usize {
var bufs = &[_]ws2_32.WSABUF{.{ .len = @as(u32, @intCast(buf.len)), .buf = buf.ptr }};
var num_bytes: u32 = undefined;
var flags_ = flags;
const rc = ws2_32.WSARecv(self.fd, bufs, 1, &num_bytes, &flags_, null, null);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => error.ConnectionAborted,
.WSAECONNRESET => error.ConnectionResetByPeer,
.WSAEDISCON => error.ConnectionClosedByPeer,
.WSAEFAULT => error.BadBuffer,
.WSAEINPROGRESS,
.WSAEWOULDBLOCK,
.WSA_IO_PENDING,
.WSAETIMEDOUT,
=> error.WouldBlock,
.WSAEINTR => error.Cancelled,
.WSAEINVAL => error.SocketNotBound,
.WSAEMSGSIZE => error.MessageTooLarge,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENETRESET => error.NetworkReset,
.WSAENOTCONN => error.SocketNotConnected,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAESHUTDOWN => error.AlreadyShutdown,
.WSA_OPERATION_ABORTED => error.OperationAborted,
else => |err| windows.unexpectedWSAError(err),
};
}
return @as(usize, @intCast(num_bytes));
}
/// Write a buffer of data provided to the socket with a set of flags specified.
/// It returns the number of bytes that are written to the socket.
pub fn write(self: Socket, buf: []const u8, flags: u32) !usize {
var bufs = &[_]ws2_32.WSABUF{.{ .len = @as(u32, @intCast(buf.len)), .buf = @as([*]u8, @ptrFromInt(@intFromPtr(buf.ptr))) }};
var num_bytes: u32 = undefined;
const rc = ws2_32.WSASend(self.fd, bufs, 1, &num_bytes, flags, null, null);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => error.ConnectionAborted,
.WSAECONNRESET => error.ConnectionResetByPeer,
.WSAEFAULT => error.BadBuffer,
.WSAEINPROGRESS,
.WSAEWOULDBLOCK,
.WSA_IO_PENDING,
.WSAETIMEDOUT,
=> error.WouldBlock,
.WSAEINTR => error.Cancelled,
.WSAEINVAL => error.SocketNotBound,
.WSAEMSGSIZE => error.MessageTooLarge,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENETRESET => error.NetworkReset,
.WSAENOBUFS => error.BufferDeadlock,
.WSAENOTCONN => error.SocketNotConnected,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAESHUTDOWN => error.AlreadyShutdown,
.WSA_OPERATION_ABORTED => error.OperationAborted,
else => |err| windows.unexpectedWSAError(err),
};
}
return @as(usize, @intCast(num_bytes));
}
/// Writes multiple I/O vectors with a prepended message header to the socket
/// with a set of flags specified. It returns the number of bytes that are
/// written to the socket.
pub fn writeMessage(self: Socket, msg: Socket.Message, flags: u32) !usize {
const call = try windows.loadWinsockExtensionFunction(ws2_32.LPFN_WSASENDMSG, self.fd, ws2_32.WSAID_WSASENDMSG);
var num_bytes: u32 = undefined;
const rc = call(self.fd, &msg, flags, &num_bytes, null, null);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => error.ConnectionAborted,
.WSAECONNRESET => error.ConnectionResetByPeer,
.WSAEFAULT => error.BadBuffer,
.WSAEINPROGRESS,
.WSAEWOULDBLOCK,
.WSA_IO_PENDING,
.WSAETIMEDOUT,
=> error.WouldBlock,
.WSAEINTR => error.Cancelled,
.WSAEINVAL => error.SocketNotBound,
.WSAEMSGSIZE => error.MessageTooLarge,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENETRESET => error.NetworkReset,
.WSAENOBUFS => error.BufferDeadlock,
.WSAENOTCONN => error.SocketNotConnected,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAESHUTDOWN => error.AlreadyShutdown,
.WSA_OPERATION_ABORTED => error.OperationAborted,
else => |err| windows.unexpectedWSAError(err),
};
}
return @as(usize, @intCast(num_bytes));
}
/// Read multiple I/O vectors with a prepended message header from the socket
/// with a set of flags specified. It returns the number of bytes that were
/// read into the buffer provided.
pub fn readMessage(self: Socket, msg: *Socket.Message, flags: u32) !usize {
_ = flags;
const call = try windows.loadWinsockExtensionFunction(ws2_32.LPFN_WSARECVMSG, self.fd, ws2_32.WSAID_WSARECVMSG);
var num_bytes: u32 = undefined;
const rc = call(self.fd, msg, &num_bytes, null, null);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => error.ConnectionAborted,
.WSAECONNRESET => error.ConnectionResetByPeer,
.WSAEDISCON => error.ConnectionClosedByPeer,
.WSAEFAULT => error.BadBuffer,
.WSAEINPROGRESS,
.WSAEWOULDBLOCK,
.WSA_IO_PENDING,
.WSAETIMEDOUT,
=> error.WouldBlock,
.WSAEINTR => error.Cancelled,
.WSAEINVAL => error.SocketNotBound,
.WSAEMSGSIZE => error.MessageTooLarge,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENETRESET => error.NetworkReset,
.WSAENOTCONN => error.SocketNotConnected,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAESHUTDOWN => error.AlreadyShutdown,
.WSA_OPERATION_ABORTED => error.OperationAborted,
else => |err| windows.unexpectedWSAError(err),
};
}
return @as(usize, @intCast(num_bytes));
}
/// Query the address that the socket is locally bounded to.
pub fn getLocalAddress(self: Socket) !Socket.Address {
var address: Socket.Address.Native.Storage = undefined;
var address_len: c_int = @sizeOf(Socket.Address.Native.Storage);
const rc = ws2_32.getsockname(self.fd, @as(*ws2_32.sockaddr, @ptrCast(&address)), &address_len);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAEFAULT => unreachable,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEINVAL => error.SocketNotBound,
else => |err| windows.unexpectedWSAError(err),
};
}
return Socket.Address.fromNative(@as(*ws2_32.sockaddr, @ptrCast(&address)));
}
/// Query the address that the socket is connected to.
pub fn getRemoteAddress(self: Socket) !Socket.Address {
var address: Socket.Address.Native.Storage = undefined;
var address_len: c_int = @sizeOf(Socket.Address.Native.Storage);
const rc = ws2_32.getpeername(self.fd, @as(*ws2_32.sockaddr, @ptrCast(&address)), &address_len);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAEFAULT => unreachable,
.WSAENETDOWN => error.NetworkSubsystemFailed,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
.WSAEINVAL => error.SocketNotBound,
else => |err| windows.unexpectedWSAError(err),
};
}
return Socket.Address.fromNative(@as(*ws2_32.sockaddr, @ptrCast(&address)));
}
/// Query and return the latest cached error on the socket.
pub fn getError(self: Socket) !void {
_ = self;
return {};
}
/// Query the read buffer size of the socket.
pub fn getReadBufferSize(self: Socket) !u32 {
_ = self;
return 0;
}
/// Query the write buffer size of the socket.
pub fn getWriteBufferSize(self: Socket) !u32 {
_ = self;
return 0;
}
/// Set a socket option.
pub fn setOption(self: Socket, level: u32, code: u32, value: []const u8) !void {
const rc = ws2_32.setsockopt(self.fd, @as(i32, @intCast(level)), @as(i32, @intCast(code)), value.ptr, @as(i32, @intCast(value.len)));
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAEFAULT => unreachable,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEINVAL => return error.SocketNotBound,
else => |err| windows.unexpectedWSAError(err),
};
}
}
/// Have close() or shutdown() syscalls block until all queued messages in the socket have been successfully
/// sent, or if the timeout specified in seconds has been reached. It returns `error.UnsupportedSocketOption`
/// if the host does not support the option for a socket to linger around up until a timeout specified in
/// seconds.
pub fn setLinger(self: Socket, timeout_seconds: ?u16) !void {
const settings = Socket.Linger.init(timeout_seconds);
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.LINGER, mem.asBytes(&settings));
}
/// On connection-oriented sockets, have keep-alive messages be sent periodically. The timing in which keep-alive
/// messages are sent are dependant on operating system settings. It returns `error.UnsupportedSocketOption` if
/// the host does not support periodically sending keep-alive messages on connection-oriented sockets.
pub fn setKeepAlive(self: Socket, enabled: bool) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.KEEPALIVE, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
/// Allow multiple sockets on the same host to listen on the same address. It returns `error.UnsupportedSocketOption` if
/// the host does not support sockets listening the same address.
pub fn setReuseAddress(self: Socket, enabled: bool) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.REUSEADDR, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
/// Allow multiple sockets on the same host to listen on the same port. It returns `error.UnsupportedSocketOption` if
/// the host does not supports sockets listening on the same port.
///
/// TODO: verify if this truly mimicks SO.REUSEPORT behavior, or if SO.REUSE_UNICASTPORT provides the correct behavior
pub fn setReusePort(self: Socket, enabled: bool) !void {
try self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.BROADCAST, mem.asBytes(&@as(u32, @intFromBool(enabled))));
try self.setReuseAddress(enabled);
}
/// Set the write buffer size of the socket.
pub fn setWriteBufferSize(self: Socket, size: u32) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.SNDBUF, mem.asBytes(&size));
}
/// Set the read buffer size of the socket.
pub fn setReadBufferSize(self: Socket, size: u32) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.RCVBUF, mem.asBytes(&size));
}
/// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is
/// set on a non-blocking socket.
///
/// Set a timeout on the socket that is to occur if no messages are successfully written
/// to its bound destination after a specified number of milliseconds. A subsequent write
/// to the socket will thereafter return `error.WouldBlock` should the timeout be exceeded.
pub fn setWriteTimeout(self: Socket, milliseconds: u32) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.SNDTIMEO, mem.asBytes(&milliseconds));
}
/// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is
/// set on a non-blocking socket.
///
/// Set a timeout on the socket that is to occur if no messages are successfully read
/// from its bound destination after a specified number of milliseconds. A subsequent
/// read from the socket will thereafter return `error.WouldBlock` should the timeout be
/// exceeded.
pub fn setReadTimeout(self: Socket, milliseconds: u32) !void {
return self.setOption(ws2_32.SOL.SOCKET, ws2_32.SO.RCVTIMEO, mem.asBytes(&milliseconds));
}
};
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/net/ip.zig | const std = @import("../../std.zig");
const fmt = std.fmt;
const IPv4 = std.x.os.IPv4;
const IPv6 = std.x.os.IPv6;
const Socket = std.x.os.Socket;
/// A generic IP abstraction.
const ip = @This();
/// A union of all eligible types of IP addresses.
pub const Address = union(enum) {
ipv4: IPv4.Address,
ipv6: IPv6.Address,
/// Instantiate a new address with a IPv4 host and port.
pub fn initIPv4(host: IPv4, port: u16) Address {
return .{ .ipv4 = .{ .host = host, .port = port } };
}
/// Instantiate a new address with a IPv6 host and port.
pub fn initIPv6(host: IPv6, port: u16) Address {
return .{ .ipv6 = .{ .host = host, .port = port } };
}
/// Re-interpret a generic socket address into an IP address.
pub fn from(address: Socket.Address) ip.Address {
return switch (address) {
.ipv4 => |ipv4_address| .{ .ipv4 = ipv4_address },
.ipv6 => |ipv6_address| .{ .ipv6 = ipv6_address },
};
}
/// Re-interpret an IP address into a generic socket address.
pub fn into(self: ip.Address) Socket.Address {
return switch (self) {
.ipv4 => |ipv4_address| .{ .ipv4 = ipv4_address },
.ipv6 => |ipv6_address| .{ .ipv6 = ipv6_address },
};
}
/// Implements the `std.fmt.format` API.
pub fn format(
self: ip.Address,
comptime layout: []const u8,
opts: fmt.FormatOptions,
writer: anytype,
) !void {
_ = opts;
_ = layout;
switch (self) {
.ipv4 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }),
.ipv6 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }),
}
}
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x | repos/gotta-go-fast/src/self-hosted-parser/input_dir/x/net/tcp.zig | const std = @import("../../std.zig");
const builtin = @import("builtin");
const io = std.io;
const os = std.os;
const ip = std.x.net.ip;
const fmt = std.fmt;
const mem = std.mem;
const testing = std.testing;
const native_os = builtin.os;
const IPv4 = std.x.os.IPv4;
const IPv6 = std.x.os.IPv6;
const Socket = std.x.os.Socket;
const Buffer = std.x.os.Buffer;
/// A generic TCP socket abstraction.
const tcp = @This();
/// A TCP client-address pair.
pub const Connection = struct {
client: tcp.Client,
address: ip.Address,
/// Enclose a TCP client and address into a client-address pair.
pub fn from(conn: Socket.Connection) tcp.Connection {
return .{
.client = tcp.Client.from(conn.socket),
.address = ip.Address.from(conn.address),
};
}
/// Unravel a TCP client-address pair into a socket-address pair.
pub fn into(self: tcp.Connection) Socket.Connection {
return .{
.socket = self.client.socket,
.address = self.address.into(),
};
}
/// Closes the underlying client of the connection.
pub fn deinit(self: tcp.Connection) void {
self.client.deinit();
}
};
/// Possible domains that a TCP client/listener may operate over.
pub const Domain = enum(u16) {
ip = os.AF.INET,
ipv6 = os.AF.INET6,
};
/// A TCP client.
pub const Client = struct {
socket: Socket,
/// Implements `std.io.Reader`.
pub const Reader = struct {
client: Client,
flags: u32,
/// Implements `readFn` for `std.io.Reader`.
pub fn read(self: Client.Reader, buffer: []u8) !usize {
return self.client.read(buffer, self.flags);
}
};
/// Implements `std.io.Writer`.
pub const Writer = struct {
client: Client,
flags: u32,
/// Implements `writeFn` for `std.io.Writer`.
pub fn write(self: Client.Writer, buffer: []const u8) !usize {
return self.client.write(buffer, self.flags);
}
};
/// Opens a new client.
pub fn init(domain: tcp.Domain, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Client {
return Client{
.socket = try Socket.init(
@intFromEnum(domain),
os.SOCK.STREAM,
os.IPPROTO.TCP,
flags,
),
};
}
/// Enclose a TCP client over an existing socket.
pub fn from(socket: Socket) Client {
return Client{ .socket = socket };
}
/// Closes the client.
pub fn deinit(self: Client) void {
self.socket.deinit();
}
/// Shutdown either the read side, write side, or all sides of the client's underlying socket.
pub fn shutdown(self: Client, how: os.ShutdownHow) !void {
return self.socket.shutdown(how);
}
/// Have the client attempt to the connect to an address.
pub fn connect(self: Client, address: ip.Address) !void {
return self.socket.connect(address.into());
}
/// Extracts the error set of a function.
/// TODO: remove after Socket.{read, write} error unions are well-defined across different platforms
fn ErrorSetOf(comptime Function: anytype) type {
return @typeInfo(@typeInfo(@TypeOf(Function)).Fn.return_type.?).ErrorUnion.error_set;
}
/// Wrap `tcp.Client` into `std.io.Reader`.
pub fn reader(self: Client, flags: u32) io.Reader(Client.Reader, ErrorSetOf(Client.Reader.read), Client.Reader.read) {
return .{ .context = .{ .client = self, .flags = flags } };
}
/// Wrap `tcp.Client` into `std.io.Writer`.
pub fn writer(self: Client, flags: u32) io.Writer(Client.Writer, ErrorSetOf(Client.Writer.write), Client.Writer.write) {
return .{ .context = .{ .client = self, .flags = flags } };
}
/// Read data from the socket into the buffer provided with a set of flags
/// specified. It returns the number of bytes read into the buffer provided.
pub fn read(self: Client, buf: []u8, flags: u32) !usize {
return self.socket.read(buf, flags);
}
/// Write a buffer of data provided to the socket with a set of flags specified.
/// It returns the number of bytes that are written to the socket.
pub fn write(self: Client, buf: []const u8, flags: u32) !usize {
return self.socket.write(buf, flags);
}
/// Writes multiple I/O vectors with a prepended message header to the socket
/// with a set of flags specified. It returns the number of bytes that are
/// written to the socket.
pub fn writeMessage(self: Client, msg: Socket.Message, flags: u32) !usize {
return self.socket.writeMessage(msg, flags);
}
/// Read multiple I/O vectors with a prepended message header from the socket
/// with a set of flags specified. It returns the number of bytes that were
/// read into the buffer provided.
pub fn readMessage(self: Client, msg: *Socket.Message, flags: u32) !usize {
return self.socket.readMessage(msg, flags);
}
/// Query and return the latest cached error on the client's underlying socket.
pub fn getError(self: Client) !void {
return self.socket.getError();
}
/// Query the read buffer size of the client's underlying socket.
pub fn getReadBufferSize(self: Client) !u32 {
return self.socket.getReadBufferSize();
}
/// Query the write buffer size of the client's underlying socket.
pub fn getWriteBufferSize(self: Client) !u32 {
return self.socket.getWriteBufferSize();
}
/// Query the address that the client's socket is locally bounded to.
pub fn getLocalAddress(self: Client) !ip.Address {
return ip.Address.from(try self.socket.getLocalAddress());
}
/// Query the address that the socket is connected to.
pub fn getRemoteAddress(self: Client) !ip.Address {
return ip.Address.from(try self.socket.getRemoteAddress());
}
/// Have close() or shutdown() syscalls block until all queued messages in the client have been successfully
/// sent, or if the timeout specified in seconds has been reached. It returns `error.UnsupportedSocketOption`
/// if the host does not support the option for a socket to linger around up until a timeout specified in
/// seconds.
pub fn setLinger(self: Client, timeout_seconds: ?u16) !void {
return self.socket.setLinger(timeout_seconds);
}
/// Have keep-alive messages be sent periodically. The timing in which keep-alive messages are sent are
/// dependant on operating system settings. It returns `error.UnsupportedSocketOption` if the host does
/// not support periodically sending keep-alive messages on connection-oriented sockets.
pub fn setKeepAlive(self: Client, enabled: bool) !void {
return self.socket.setKeepAlive(enabled);
}
/// Disable Nagle's algorithm on a TCP socket. It returns `error.UnsupportedSocketOption` if
/// the host does not support sockets disabling Nagle's algorithm.
pub fn setNoDelay(self: Client, enabled: bool) !void {
if (@hasDecl(os.TCP, "NODELAY")) {
const bytes = mem.asBytes(&@as(usize, @intFromBool(enabled)));
return self.socket.setOption(os.IPPROTO.TCP, os.TCP.NODELAY, bytes);
}
return error.UnsupportedSocketOption;
}
/// Enables TCP Quick ACK on a TCP socket to immediately send rather than delay ACKs when necessary. It returns
/// `error.UnsupportedSocketOption` if the host does not support TCP Quick ACK.
pub fn setQuickACK(self: Client, enabled: bool) !void {
if (@hasDecl(os.TCP, "QUICKACK")) {
return self.socket.setOption(os.IPPROTO.TCP, os.TCP.QUICKACK, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
return error.UnsupportedSocketOption;
}
/// Set the write buffer size of the socket.
pub fn setWriteBufferSize(self: Client, size: u32) !void {
return self.socket.setWriteBufferSize(size);
}
/// Set the read buffer size of the socket.
pub fn setReadBufferSize(self: Client, size: u32) !void {
return self.socket.setReadBufferSize(size);
}
/// Set a timeout on the socket that is to occur if no messages are successfully written
/// to its bound destination after a specified number of milliseconds. A subsequent write
/// to the socket will thereafter return `error.WouldBlock` should the timeout be exceeded.
pub fn setWriteTimeout(self: Client, milliseconds: u32) !void {
return self.socket.setWriteTimeout(milliseconds);
}
/// Set a timeout on the socket that is to occur if no messages are successfully read
/// from its bound destination after a specified number of milliseconds. A subsequent
/// read from the socket will thereafter return `error.WouldBlock` should the timeout be
/// exceeded.
pub fn setReadTimeout(self: Client, milliseconds: u32) !void {
return self.socket.setReadTimeout(milliseconds);
}
};
/// A TCP listener.
pub const Listener = struct {
socket: Socket,
/// Opens a new listener.
pub fn init(domain: tcp.Domain, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !Listener {
return Listener{
.socket = try Socket.init(
@intFromEnum(domain),
os.SOCK.STREAM,
os.IPPROTO.TCP,
flags,
),
};
}
/// Closes the listener.
pub fn deinit(self: Listener) void {
self.socket.deinit();
}
/// Shuts down the underlying listener's socket. The next subsequent call, or
/// a current pending call to accept() after shutdown is called will return
/// an error.
pub fn shutdown(self: Listener) !void {
return self.socket.shutdown(.recv);
}
/// Binds the listener's socket to an address.
pub fn bind(self: Listener, address: ip.Address) !void {
return self.socket.bind(address.into());
}
/// Start listening for incoming connections.
pub fn listen(self: Listener, max_backlog_size: u31) !void {
return self.socket.listen(max_backlog_size);
}
/// Accept a pending incoming connection queued to the kernel backlog
/// of the listener's socket.
pub fn accept(self: Listener, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !tcp.Connection {
return tcp.Connection.from(try self.socket.accept(flags));
}
/// Query and return the latest cached error on the listener's underlying socket.
pub fn getError(self: Client) !void {
return self.socket.getError();
}
/// Query the address that the listener's socket is locally bounded to.
pub fn getLocalAddress(self: Listener) !ip.Address {
return ip.Address.from(try self.socket.getLocalAddress());
}
/// Allow multiple sockets on the same host to listen on the same address. It returns `error.UnsupportedSocketOption` if
/// the host does not support sockets listening the same address.
pub fn setReuseAddress(self: Listener, enabled: bool) !void {
return self.socket.setReuseAddress(enabled);
}
/// Allow multiple sockets on the same host to listen on the same port. It returns `error.UnsupportedSocketOption` if
/// the host does not supports sockets listening on the same port.
pub fn setReusePort(self: Listener, enabled: bool) !void {
return self.socket.setReusePort(enabled);
}
/// Enables TCP Fast Open (RFC 7413) on a TCP socket. It returns `error.UnsupportedSocketOption` if the host does not
/// support TCP Fast Open.
pub fn setFastOpen(self: Listener, enabled: bool) !void {
if (@hasDecl(os.TCP, "FASTOPEN")) {
return self.socket.setOption(os.IPPROTO.TCP, os.TCP.FASTOPEN, mem.asBytes(&@as(u32, @intFromBool(enabled))));
}
return error.UnsupportedSocketOption;
}
/// Set a timeout on the listener that is to occur if no new incoming connections come in
/// after a specified number of milliseconds. A subsequent accept call to the listener
/// will thereafter return `error.WouldBlock` should the timeout be exceeded.
pub fn setAcceptTimeout(self: Listener, milliseconds: usize) !void {
return self.socket.setReadTimeout(milliseconds);
}
};
test "tcp: create client/listener pair" {
if (native_os.tag == .wasi) return error.SkipZigTest;
const listener = try tcp.Listener.init(.ip, .{ .close_on_exec = true });
defer listener.deinit();
try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0));
try listener.listen(128);
var binded_address = try listener.getLocalAddress();
switch (binded_address) {
.ipv4 => |*ipv4| ipv4.host = IPv4.localhost,
.ipv6 => |*ipv6| ipv6.host = IPv6.localhost,
}
const client = try tcp.Client.init(.ip, .{ .close_on_exec = true });
defer client.deinit();
try client.connect(binded_address);
const conn = try listener.accept(.{ .close_on_exec = true });
defer conn.deinit();
}
test "tcp/client: 1ms read timeout" {
if (native_os.tag == .wasi) return error.SkipZigTest;
const listener = try tcp.Listener.init(.ip, .{ .close_on_exec = true });
defer listener.deinit();
try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0));
try listener.listen(128);
var binded_address = try listener.getLocalAddress();
switch (binded_address) {
.ipv4 => |*ipv4| ipv4.host = IPv4.localhost,
.ipv6 => |*ipv6| ipv6.host = IPv6.localhost,
}
const client = try tcp.Client.init(.ip, .{ .close_on_exec = true });
defer client.deinit();
try client.connect(binded_address);
try client.setReadTimeout(1);
const conn = try listener.accept(.{ .close_on_exec = true });
defer conn.deinit();
var buf: [1]u8 = undefined;
try testing.expectError(error.WouldBlock, client.reader(0).read(&buf));
}
test "tcp/client: read and write multiple vectors" {
if (native_os.tag == .wasi) return error.SkipZigTest;
const listener = try tcp.Listener.init(.ip, .{ .close_on_exec = true });
defer listener.deinit();
try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0));
try listener.listen(128);
var binded_address = try listener.getLocalAddress();
switch (binded_address) {
.ipv4 => |*ipv4| ipv4.host = IPv4.localhost,
.ipv6 => |*ipv6| ipv6.host = IPv6.localhost,
}
const client = try tcp.Client.init(.ip, .{ .close_on_exec = true });
defer client.deinit();
try client.connect(binded_address);
const conn = try listener.accept(.{ .close_on_exec = true });
defer conn.deinit();
const message = "hello world";
_ = try conn.client.writeMessage(Socket.Message.fromBuffers(&[_]Buffer{
Buffer.from(message[0 .. message.len / 2]),
Buffer.from(message[message.len / 2 ..]),
}), 0);
var buf: [message.len + 1]u8 = undefined;
var msg = Socket.Message.fromBuffers(&[_]Buffer{
Buffer.from(buf[0 .. message.len / 2]),
Buffer.from(buf[message.len / 2 ..]),
});
_ = try client.readMessage(&msg, 0);
try testing.expectEqualStrings(message, buf[0..message.len]);
}
test "tcp/listener: bind to unspecified ipv4 address" {
if (native_os.tag == .wasi) return error.SkipZigTest;
const listener = try tcp.Listener.init(.ip, .{ .close_on_exec = true });
defer listener.deinit();
try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0));
try listener.listen(128);
const address = try listener.getLocalAddress();
try testing.expect(address == .ipv4);
}
test "tcp/listener: bind to unspecified ipv6 address" {
if (native_os.tag == .wasi) return error.SkipZigTest;
const listener = try tcp.Listener.init(.ipv6, .{ .close_on_exec = true });
defer listener.deinit();
try listener.bind(ip.Address.initIPv6(IPv6.unspecified, 0));
try listener.listen(128);
const address = try listener.getLocalAddress();
try testing.expect(address == .ipv6);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/ResetEvent.zig | //! A thread-safe resource which supports blocking until signaled.
//! This API is for kernel threads, not evented I/O.
//! This API requires being initialized at runtime, and initialization
//! can fail. Once initialized, the core operations cannot fail.
//! If you need an abstraction that cannot fail to be initialized, see
//! `std.Thread.StaticResetEvent`. However if you can handle initialization failure,
//! it is preferred to use `ResetEvent`.
const ResetEvent = @This();
const std = @import("../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const assert = std.debug.assert;
const c = std.c;
const os = std.os;
const time = std.time;
impl: Impl,
pub const Impl = if (builtin.single_threaded)
std.Thread.StaticResetEvent.DebugEvent
else if (builtin.target.isDarwin())
DarwinEvent
else if (std.Thread.use_pthreads)
PosixEvent
else
std.Thread.StaticResetEvent.AtomicEvent;
pub const InitError = error{SystemResources};
/// After `init`, it is legal to call any other function.
pub fn init(ev: *ResetEvent) InitError!void {
return ev.impl.init();
}
/// This function is not thread-safe.
/// After `deinit`, the only legal function to call is `init`.
pub fn deinit(ev: *ResetEvent) void {
return ev.impl.deinit();
}
/// Sets the event if not already set and wakes up all the threads waiting on
/// the event. It is safe to call `set` multiple times before calling `wait`.
/// However it is illegal to call `set` after `wait` is called until the event
/// is `reset`. This function is thread-safe.
pub fn set(ev: *ResetEvent) void {
return ev.impl.set();
}
/// Resets the event to its original, unset state.
/// This function is *not* thread-safe. It is equivalent to calling
/// `deinit` followed by `init` but without the possibility of failure.
pub fn reset(ev: *ResetEvent) void {
return ev.impl.reset();
}
/// Wait for the event to be set by blocking the current thread.
/// Thread-safe. No spurious wakeups.
/// Upon return from `wait`, the only functions available to be called
/// in `ResetEvent` are `reset` and `deinit`.
pub fn wait(ev: *ResetEvent) void {
return ev.impl.wait();
}
pub const TimedWaitResult = enum { event_set, timed_out };
/// Wait for the event to be set by blocking the current thread.
/// A timeout in nanoseconds can be provided as a hint for how
/// long the thread should block on the unset event before returning
/// `TimedWaitResult.timed_out`.
/// Thread-safe. No precision of timing is guaranteed.
/// Upon return from `wait`, the only functions available to be called
/// in `ResetEvent` are `reset` and `deinit`.
pub fn timedWait(ev: *ResetEvent, timeout_ns: u64) TimedWaitResult {
return ev.impl.timedWait(timeout_ns);
}
/// Apple has decided to not support POSIX semaphores, so we go with a
/// different approach using Grand Central Dispatch. This API is exposed
/// by libSystem so it is guaranteed to be available on all Darwin platforms.
pub const DarwinEvent = struct {
sem: c.dispatch_semaphore_t = undefined,
pub fn init(ev: *DarwinEvent) !void {
ev.* = .{
.sem = c.dispatch_semaphore_create(0) orelse return error.SystemResources,
};
}
pub fn deinit(ev: *DarwinEvent) void {
c.dispatch_release(ev.sem);
ev.* = undefined;
}
pub fn set(ev: *DarwinEvent) void {
// Empirically this returns the numerical value of the semaphore.
_ = c.dispatch_semaphore_signal(ev.sem);
}
pub fn wait(ev: *DarwinEvent) void {
assert(c.dispatch_semaphore_wait(ev.sem, c.DISPATCH_TIME_FOREVER) == 0);
}
pub fn timedWait(ev: *DarwinEvent, timeout_ns: u64) TimedWaitResult {
const t = c.dispatch_time(c.DISPATCH_TIME_NOW, @as(i64, @intCast(timeout_ns)));
if (c.dispatch_semaphore_wait(ev.sem, t) != 0) {
return .timed_out;
} else {
return .event_set;
}
}
pub fn reset(ev: *DarwinEvent) void {
// Keep calling until the semaphore goes back down to 0.
while (c.dispatch_semaphore_wait(ev.sem, c.DISPATCH_TIME_NOW) == 0) {}
}
};
/// POSIX semaphores must be initialized at runtime because they are allowed to
/// be implemented as file descriptors, in which case initialization would require
/// a syscall to open the fd.
pub const PosixEvent = struct {
sem: c.sem_t = undefined,
pub fn init(ev: *PosixEvent) !void {
switch (c.getErrno(c.sem_init(&ev.sem, 0, 0))) {
.SUCCESS => return,
else => return error.SystemResources,
}
}
pub fn deinit(ev: *PosixEvent) void {
assert(c.sem_destroy(&ev.sem) == 0);
ev.* = undefined;
}
pub fn set(ev: *PosixEvent) void {
assert(c.sem_post(&ev.sem) == 0);
}
pub fn wait(ev: *PosixEvent) void {
while (true) {
switch (c.getErrno(c.sem_wait(&ev.sem))) {
.SUCCESS => return,
.INTR => continue,
.INVAL => unreachable,
else => unreachable,
}
}
}
pub fn timedWait(ev: *PosixEvent, timeout_ns: u64) TimedWaitResult {
var ts: os.timespec = undefined;
var timeout_abs = timeout_ns;
os.clock_gettime(os.CLOCK.REALTIME, &ts) catch return .timed_out;
timeout_abs += @as(u64, @intCast(ts.tv_sec)) * time.ns_per_s;
timeout_abs += @as(u64, @intCast(ts.tv_nsec));
ts.tv_sec = @as(@TypeOf(ts.tv_sec), @intCast(@divFloor(timeout_abs, time.ns_per_s)));
ts.tv_nsec = @as(@TypeOf(ts.tv_nsec), @intCast(@mod(timeout_abs, time.ns_per_s)));
while (true) {
switch (c.getErrno(c.sem_timedwait(&ev.sem, &ts))) {
.SUCCESS => return .event_set,
.INTR => continue,
.INVAL => unreachable,
.TIMEDOUT => return .timed_out,
else => unreachable,
}
}
}
pub fn reset(ev: *PosixEvent) void {
while (true) {
switch (c.getErrno(c.sem_trywait(&ev.sem))) {
.SUCCESS => continue, // Need to make it go to zero.
.INTR => continue,
.INVAL => unreachable,
.AGAIN => return, // The semaphore currently has the value zero.
else => unreachable,
}
}
}
};
test "basic usage" {
var event: ResetEvent = undefined;
try event.init();
defer event.deinit();
// test event setting
event.set();
// test event resetting
event.reset();
// test event waiting (non-blocking)
event.set();
event.wait();
event.reset();
event.set();
try testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
// test cross-thread signaling
if (builtin.single_threaded)
return;
const Context = struct {
const Self = @This();
value: u128,
in: ResetEvent,
out: ResetEvent,
fn init(self: *Self) !void {
self.* = .{
.value = 0,
.in = undefined,
.out = undefined,
};
try self.in.init();
try self.out.init();
}
fn deinit(self: *Self) void {
self.in.deinit();
self.out.deinit();
self.* = undefined;
}
fn sender(self: *Self) !void {
// update value and signal input
try testing.expect(self.value == 0);
self.value = 1;
self.in.set();
// wait for receiver to update value and signal output
self.out.wait();
try testing.expect(self.value == 2);
// update value and signal final input
self.value = 3;
self.in.set();
}
fn receiver(self: *Self) !void {
// wait for sender to update value and signal input
self.in.wait();
try testing.expect(self.value == 1);
// update value and signal output
self.in.reset();
self.value = 2;
self.out.set();
// wait for sender to update value and signal final input
self.in.wait();
try testing.expect(self.value == 3);
}
fn sleeper(self: *Self) void {
self.in.set();
time.sleep(time.ns_per_ms * 2);
self.value = 5;
self.out.set();
}
fn timedWaiter(self: *Self) !void {
self.in.wait();
try testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try self.out.timedWait(time.ns_per_ms * 100);
try testing.expect(self.value == 5);
}
};
var context: Context = undefined;
try context.init();
defer context.deinit();
const receiver = try std.Thread.spawn(.{}, Context.receiver, .{&context});
defer receiver.join();
try context.sender();
if (false) {
// I have now observed this fail on macOS, Windows, and Linux.
// https://github.com/ziglang/zig/issues/7009
var timed = Context.init();
defer timed.deinit();
const sleeper = try std.Thread.spawn(.{}, Context.sleeper, .{&timed});
defer sleeper.join();
try timed.timedWaiter();
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/Semaphore.zig | //! A semaphore is an unsigned integer that blocks the kernel thread if
//! the number would become negative.
//! This API supports static initialization and does not require deinitialization.
mutex: Mutex = .{},
cond: Condition = .{},
/// It is OK to initialize this field to any value.
permits: usize = 0,
const Semaphore = @This();
const std = @import("../std.zig");
const Mutex = std.Thread.Mutex;
const Condition = std.Thread.Condition;
pub fn wait(sem: *Semaphore) void {
const held = sem.mutex.acquire();
defer held.release();
while (sem.permits == 0)
sem.cond.wait(&sem.mutex);
sem.permits -= 1;
if (sem.permits > 0)
sem.cond.signal();
}
pub fn post(sem: *Semaphore) void {
const held = sem.mutex.acquire();
defer held.release();
sem.permits += 1;
sem.cond.signal();
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/Futex.zig | //! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.
//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.
//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.
//! Using Futex, other Thread synchronization primitives can be built which efficiently wait for cross-thread events or signals.
const std = @import("../std.zig");
const builtin = @import("builtin");
const Futex = @This();
const target = builtin.target;
const single_threaded = builtin.single_threaded;
const assert = std.debug.assert;
const testing = std.testing;
const Atomic = std.atomic.Atomic;
const spinLoopHint = std.atomic.spinLoopHint;
/// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either:
/// - The value at `ptr` is no longer equal to `expect`.
/// - The caller is unblocked by a matching `wake()`.
/// - The caller is unblocked spuriously by an arbitrary internal signal.
///
/// If `timeout` is provided, and the caller is blocked for longer than `timeout` nanoseconds`, `error.TimedOut` is returned.
///
/// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically
/// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`.
pub fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
if (single_threaded) {
// check whether the caller should block
if (ptr.loadUnchecked() != expect) {
return;
}
// There are no other threads which could notify the caller on single_threaded.
// Therefor a wait() without a timeout would block indefinitely.
const timeout_ns = timeout orelse {
@panic("deadlock");
};
// Simulate blocking with the timeout knowing that:
// - no other thread can change the ptr value
// - no other thread could unblock us if we waiting on the ptr
std.time.sleep(timeout_ns);
return error.TimedOut;
}
// Avoid calling into the OS for no-op waits()
if (timeout) |timeout_ns| {
if (timeout_ns == 0) {
if (ptr.load(.SeqCst) != expect) return;
return error.TimedOut;
}
}
return OsFutex.wait(ptr, expect, timeout);
}
/// Unblocks at most `num_waiters` callers blocked in a `wait()` call on `ptr`.
/// `num_waiters` of 1 unblocks at most one `wait(ptr, ...)` and `maxInt(u32)` unblocks effectively all `wait(ptr, ...)`.
pub fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
if (single_threaded) return;
if (num_waiters == 0) return;
return OsFutex.wake(ptr, num_waiters);
}
const OsFutex = if (target.os.tag == .windows)
WindowsFutex
else if (target.os.tag == .linux)
LinuxFutex
else if (target.isDarwin())
DarwinFutex
else if (builtin.link_libc)
PosixFutex
else
UnsupportedFutex;
const UnsupportedFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
return unsupported(.{ ptr, expect, timeout });
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
return unsupported(.{ ptr, num_waiters });
}
fn unsupported(unused: anytype) noreturn {
@compileLog("Unsupported operating system", target.os.tag);
_ = unused;
unreachable;
}
};
const WindowsFutex = struct {
const windows = std.os.windows;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var timeout_value: windows.LARGE_INTEGER = undefined;
var timeout_ptr: ?*const windows.LARGE_INTEGER = null;
// NTDLL functions work with time in units of 100 nanoseconds.
// Positive values for timeouts are absolute time while negative is relative.
if (timeout) |timeout_ns| {
timeout_ptr = &timeout_value;
timeout_value = -@as(windows.LARGE_INTEGER, @intCast(timeout_ns / 100));
}
switch (windows.ntdll.RtlWaitOnAddress(
@as(?*const anyopaque, @ptrCast(ptr)),
@as(?*const anyopaque, @ptrCast(&expect)),
@sizeOf(@TypeOf(expect)),
timeout_ptr,
)) {
.SUCCESS => {},
.TIMEOUT => return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @as(?*const anyopaque, @ptrCast(ptr));
switch (num_waiters) {
1 => windows.ntdll.RtlWakeAddressSingle(address),
else => windows.ntdll.RtlWakeAddressAll(address),
}
}
};
const LinuxFutex = struct {
const linux = std.os.linux;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var ts: std.os.timespec = undefined;
var ts_ptr: ?*std.os.timespec = null;
// Futex timespec timeout is already in relative time.
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts.tv_sec = @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s));
ts.tv_nsec = @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s));
}
switch (linux.getErrno(linux.futex_wait(
@as(*const i32, @ptrCast(ptr)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAIT,
@as(i32, @bitCast(expect)),
ts_ptr,
))) {
.SUCCESS => {}, // notified by `wake()`
.INTR => {}, // spurious wakeup
.AGAIN => {}, // ptr.* != expect
.TIMEDOUT => return error.TimedOut,
.INVAL => {}, // possibly timeout overflow
.FAULT => unreachable,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
switch (linux.getErrno(linux.futex_wake(
@as(*const i32, @ptrCast(ptr)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAKE,
std.math.cast(i32, num_waiters) catch std.math.maxInt(i32),
))) {
.SUCCESS => {}, // successful wake up
.INVAL => {}, // invalid futex_wait() on ptr done elsewhere
.FAULT => {}, // pointer became invalid while doing the wake
else => unreachable,
}
}
};
const DarwinFutex = struct {
const darwin = std.os.darwin;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
// Darwin XNU 7195.50.7.100.1 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it:
// https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
//
// This XNU version appears to correspond to 11.0.1:
// https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
//
// ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout
// ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
var timeout_ns: u64 = 0;
if (timeout) |timeout_value| {
// This should be checked by the caller.
assert(timeout_value != 0);
timeout_ns = timeout_value;
}
const addr = @as(*const anyopaque, @ptrCast(ptr));
const flags = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
// If we're using `__ulock_wait` and `timeout` is too big to fit inside a `u32` count of
// micro-seconds (around 70min), we'll request a shorter timeout. This is fine (users
// should handle spurious wakeups), but we need to remember that we did so, so that
// we don't return `TimedOut` incorrectly. If that happens, we set this variable to
// true so that we we know to ignore the ETIMEDOUT result.
var timeout_overflowed = false;
const status = blk: {
if (target.os.version_range.semver.max.major >= 11) {
break :blk darwin.__ulock_wait2(flags, addr, expect, timeout_ns, 0);
} else {
const timeout_us = std.math.cast(u32, timeout_ns / std.time.ns_per_us) catch overflow: {
timeout_overflowed = true;
break :overflow std.math.maxInt(u32);
};
break :blk darwin.__ulock_wait(flags, addr, expect, timeout_us);
}
};
if (status >= 0) return;
switch (@as(std.os.E, @enumFromInt(-status))) {
.INTR => {},
// Address of the futex is paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
.FAULT => {},
.TIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
var flags: u32 = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
if (num_waiters > 1) {
flags |= darwin.ULF_WAKE_ALL;
}
while (true) {
const addr = @as(*const anyopaque, @ptrCast(ptr));
const status = darwin.__ulock_wake(flags, addr, 0);
if (status >= 0) return;
switch (@as(std.os.E, @enumFromInt(-status))) {
.INTR => continue, // spurious wake()
.FAULT => continue, // address of the lock was paged out
.NOENT => return, // nothing was woken up
.ALREADY => unreachable, // only for ULF_WAKE_THREAD
else => unreachable,
}
}
}
};
const PosixFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var waiter: List.Node = undefined;
{
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
if (ptr.load(.SeqCst) != expect) {
return;
}
waiter.data = .{ .address = address };
bucket.list.prepend(&waiter);
}
var timed_out = false;
waiter.data.wait(timeout) catch {
defer if (!timed_out) {
waiter.data.wait(null) catch unreachable;
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
if (waiter.data.address == address) {
timed_out = true;
bucket.list.remove(&waiter);
}
};
waiter.data.deinit();
if (timed_out) {
return error.TimedOut;
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var can_notify = num_waiters;
var notified = List{};
defer while (notified.popFirst()) |waiter| {
waiter.data.notify();
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
var waiters = bucket.list.first;
while (waiters) |waiter| {
assert(waiter.data.address != null);
waiters = waiter.next;
if (waiter.data.address != address) continue;
if (can_notify == 0) break;
can_notify -= 1;
bucket.list.remove(waiter);
waiter.data.address = null;
notified.prepend(waiter);
}
}
const Bucket = struct {
mutex: std.c.pthread_mutex_t = .{},
list: List = .{},
var buckets = [_]Bucket{.{}} ** 64;
fn from(address: usize) *Bucket {
return &buckets[address % buckets.len];
}
};
const List = std.TailQueue(struct {
address: ?usize,
state: State = .empty,
cond: std.c.pthread_cond_t = .{},
mutex: std.c.pthread_mutex_t = .{},
const Self = @This();
const State = enum {
empty,
waiting,
notified,
};
fn deinit(self: *Self) void {
_ = std.c.pthread_cond_destroy(&self.cond);
_ = std.c.pthread_mutex_destroy(&self.mutex);
}
fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
switch (self.state) {
.empty => self.state = .waiting,
.waiting => unreachable,
.notified => return,
}
var ts: std.os.timespec = undefined;
var ts_ptr: ?*const std.os.timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
std.os.clock_gettime(std.os.CLOCK.REALTIME, &ts) catch unreachable;
ts.tv_sec += @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s));
ts.tv_nsec += @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s));
if (ts.tv_nsec >= std.time.ns_per_s) {
ts.tv_sec += 1;
ts.tv_nsec -= std.time.ns_per_s;
}
}
while (true) {
switch (self.state) {
.empty => unreachable,
.waiting => {},
.notified => return,
}
const ts_ref = ts_ptr orelse {
assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == .SUCCESS);
continue;
};
const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);
switch (rc) {
.SUCCESS => {},
.TIMEDOUT => {
self.state = .empty;
return error.TimedOut;
},
else => unreachable,
}
}
}
fn notify(self: *Self) void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
switch (self.state) {
.empty => self.state = .notified,
.waiting => {
self.state = .notified;
assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS);
},
.notified => unreachable,
}
}
});
};
test "Futex - wait/wake" {
var value = Atomic(u32).init(0);
Futex.wait(&value, 1, null) catch unreachable;
const wait_noop_result = Futex.wait(&value, 0, 0);
try testing.expectError(error.TimedOut, wait_noop_result);
const wait_longer_result = Futex.wait(&value, 0, std.time.ns_per_ms);
try testing.expectError(error.TimedOut, wait_longer_result);
Futex.wake(&value, 0);
Futex.wake(&value, 1);
Futex.wake(&value, std.math.maxInt(u32));
}
test "Futex - Signal" {
if (single_threaded) {
return error.SkipZigTest;
}
const Paddle = struct {
value: Atomic(u32) = Atomic(u32).init(0),
current: u32 = 0,
fn run(self: *@This(), hit_to: *@This()) !void {
var iterations: usize = 4;
while (iterations > 0) : (iterations -= 1) {
var value: u32 = undefined;
while (true) {
value = self.value.load(.Acquire);
if (value != self.current) break;
Futex.wait(&self.value, self.current, null) catch unreachable;
}
try testing.expectEqual(value, self.current + 1);
self.current = value;
_ = hit_to.value.fetchAdd(1, .Release);
Futex.wake(&hit_to.value, 1);
}
}
};
var ping = Paddle{};
var pong = Paddle{};
const t1 = try std.Thread.spawn(.{}, Paddle.run, .{ &ping, &pong });
defer t1.join();
const t2 = try std.Thread.spawn(.{}, Paddle.run, .{ &pong, &ping });
defer t2.join();
_ = ping.value.fetchAdd(1, .Release);
Futex.wake(&ping.value, 1);
}
test "Futex - Broadcast" {
if (single_threaded) {
return error.SkipZigTest;
}
const Context = struct {
threads: [4]std.Thread = undefined,
broadcast: Atomic(u32) = Atomic(u32).init(0),
notified: Atomic(usize) = Atomic(usize).init(0),
const BROADCAST_EMPTY = 0;
const BROADCAST_SENT = 1;
const BROADCAST_RECEIVED = 2;
fn runSender(self: *@This()) !void {
self.broadcast.store(BROADCAST_SENT, .Monotonic);
Futex.wake(&self.broadcast, @as(u32, @intCast(self.threads.len)));
while (true) {
const broadcast = self.broadcast.load(.Acquire);
if (broadcast == BROADCAST_RECEIVED) break;
try testing.expectEqual(broadcast, BROADCAST_SENT);
Futex.wait(&self.broadcast, broadcast, null) catch unreachable;
}
}
fn runReceiver(self: *@This()) void {
while (true) {
const broadcast = self.broadcast.load(.Acquire);
if (broadcast == BROADCAST_SENT) break;
assert(broadcast == BROADCAST_EMPTY);
Futex.wait(&self.broadcast, broadcast, null) catch unreachable;
}
const notified = self.notified.fetchAdd(1, .Monotonic);
if (notified + 1 == self.threads.len) {
self.broadcast.store(BROADCAST_RECEIVED, .Release);
Futex.wake(&self.broadcast, 1);
}
}
};
var ctx = Context{};
for (ctx.threads) |*thread|
thread.* = try std.Thread.spawn(.{}, Context.runReceiver, .{&ctx});
defer for (ctx.threads) |thread|
thread.join();
// Try to wait for the threads to start before running runSender().
// NOTE: not actually needed for correctness.
std.time.sleep(16 * std.time.ns_per_ms);
try ctx.runSender();
const notified = ctx.notified.load(.Monotonic);
try testing.expectEqual(notified, ctx.threads.len);
}
test "Futex - Chain" {
if (single_threaded) {
return error.SkipZigTest;
}
const Signal = struct {
value: Atomic(u32) = Atomic(u32).init(0),
fn wait(self: *@This()) void {
while (true) {
const value = self.value.load(.Acquire);
if (value == 1) break;
assert(value == 0);
Futex.wait(&self.value, 0, null) catch unreachable;
}
}
fn notify(self: *@This()) void {
assert(self.value.load(.Unordered) == 0);
self.value.store(1, .Release);
Futex.wake(&self.value, 1);
}
};
const Context = struct {
completed: Signal = .{},
threads: [4]struct {
thread: std.Thread,
signal: Signal,
} = undefined,
fn run(self: *@This(), index: usize) void {
const this_signal = &self.threads[index].signal;
var next_signal = &self.completed;
if (index + 1 < self.threads.len) {
next_signal = &self.threads[index + 1].signal;
}
this_signal.wait();
next_signal.notify();
}
};
var ctx = Context{};
for (ctx.threads, 0..) |*entry, index| {
entry.signal = .{};
entry.thread = try std.Thread.spawn(.{}, Context.run, .{ &ctx, index });
}
ctx.threads[0].signal.notify();
ctx.completed.wait();
for (ctx.threads) |entry| {
entry.thread.join();
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/RwLock.zig | //! A lock that supports one writer or many readers.
//! This API is for kernel threads, not evented I/O.
//! This API requires being initialized at runtime, and initialization
//! can fail. Once initialized, the core operations cannot fail.
impl: Impl,
const RwLock = @This();
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const Mutex = std.Thread.Mutex;
const Semaphore = std.Semaphore;
const CondVar = std.CondVar;
pub const Impl = if (builtin.single_threaded)
SingleThreadedRwLock
else if (std.Thread.use_pthreads)
PthreadRwLock
else
DefaultRwLock;
pub fn init(rwl: *RwLock) void {
return rwl.impl.init();
}
pub fn deinit(rwl: *RwLock) void {
return rwl.impl.deinit();
}
/// Attempts to obtain exclusive lock ownership.
/// Returns `true` if the lock is obtained, `false` otherwise.
pub fn tryLock(rwl: *RwLock) bool {
return rwl.impl.tryLock();
}
/// Blocks until exclusive lock ownership is acquired.
pub fn lock(rwl: *RwLock) void {
return rwl.impl.lock();
}
/// Releases a held exclusive lock.
/// Asserts the lock is held exclusively.
pub fn unlock(rwl: *RwLock) void {
return rwl.impl.unlock();
}
/// Attempts to obtain shared lock ownership.
/// Returns `true` if the lock is obtained, `false` otherwise.
pub fn tryLockShared(rwl: *RwLock) bool {
return rwl.impl.tryLockShared();
}
/// Blocks until shared lock ownership is acquired.
pub fn lockShared(rwl: *RwLock) void {
return rwl.impl.lockShared();
}
/// Releases a held shared lock.
pub fn unlockShared(rwl: *RwLock) void {
return rwl.impl.unlockShared();
}
/// Single-threaded applications use this for deadlock checks in
/// debug mode, and no-ops in release modes.
pub const SingleThreadedRwLock = struct {
state: enum { unlocked, locked_exclusive, locked_shared },
shared_count: usize,
pub fn init(rwl: *SingleThreadedRwLock) void {
rwl.* = .{
.state = .unlocked,
.shared_count = 0,
};
}
pub fn deinit(rwl: *SingleThreadedRwLock) void {
assert(rwl.state == .unlocked);
assert(rwl.shared_count == 0);
}
/// Attempts to obtain exclusive lock ownership.
/// Returns `true` if the lock is obtained, `false` otherwise.
pub fn tryLock(rwl: *SingleThreadedRwLock) bool {
switch (rwl.state) {
.unlocked => {
assert(rwl.shared_count == 0);
rwl.state = .locked_exclusive;
return true;
},
.locked_exclusive, .locked_shared => return false,
}
}
/// Blocks until exclusive lock ownership is acquired.
pub fn lock(rwl: *SingleThreadedRwLock) void {
assert(rwl.state == .unlocked); // deadlock detected
assert(rwl.shared_count == 0); // corrupted state detected
rwl.state = .locked_exclusive;
}
/// Releases a held exclusive lock.
/// Asserts the lock is held exclusively.
pub fn unlock(rwl: *SingleThreadedRwLock) void {
assert(rwl.state == .locked_exclusive);
assert(rwl.shared_count == 0); // corrupted state detected
rwl.state = .unlocked;
}
/// Attempts to obtain shared lock ownership.
/// Returns `true` if the lock is obtained, `false` otherwise.
pub fn tryLockShared(rwl: *SingleThreadedRwLock) bool {
switch (rwl.state) {
.unlocked => {
rwl.state = .locked_shared;
assert(rwl.shared_count == 0);
rwl.shared_count = 1;
return true;
},
.locked_exclusive, .locked_shared => return false,
}
}
/// Blocks until shared lock ownership is acquired.
pub fn lockShared(rwl: *SingleThreadedRwLock) void {
switch (rwl.state) {
.unlocked => {
rwl.state = .locked_shared;
assert(rwl.shared_count == 0);
rwl.shared_count = 1;
},
.locked_shared => {
rwl.shared_count += 1;
},
.locked_exclusive => unreachable, // deadlock detected
}
}
/// Releases a held shared lock.
pub fn unlockShared(rwl: *SingleThreadedRwLock) void {
switch (rwl.state) {
.unlocked => unreachable, // too many calls to `unlockShared`
.locked_exclusive => unreachable, // exclusively held lock
.locked_shared => {
rwl.shared_count -= 1;
if (rwl.shared_count == 0) {
rwl.state = .unlocked;
}
},
}
}
};
pub const PthreadRwLock = struct {
rwlock: std.c.pthread_rwlock_t,
pub fn init(rwl: *PthreadRwLock) void {
rwl.* = .{ .rwlock = .{} };
}
pub fn deinit(rwl: *PthreadRwLock) void {
const safe_rc: std.os.E = switch (builtin.os.tag) {
.dragonfly, .netbsd => .AGAIN,
else => .SUCCESS,
};
const rc = std.c.pthread_rwlock_destroy(&rwl.rwlock);
assert(rc == .SUCCESS or rc == safe_rc);
rwl.* = undefined;
}
pub fn tryLock(rwl: *PthreadRwLock) bool {
return std.c.pthread_rwlock_trywrlock(&rwl.rwlock) == .SUCCESS;
}
pub fn lock(rwl: *PthreadRwLock) void {
const rc = std.c.pthread_rwlock_wrlock(&rwl.rwlock);
assert(rc == .SUCCESS);
}
pub fn unlock(rwl: *PthreadRwLock) void {
const rc = std.c.pthread_rwlock_unlock(&rwl.rwlock);
assert(rc == .SUCCESS);
}
pub fn tryLockShared(rwl: *PthreadRwLock) bool {
return std.c.pthread_rwlock_tryrdlock(&rwl.rwlock) == .SUCCESS;
}
pub fn lockShared(rwl: *PthreadRwLock) void {
const rc = std.c.pthread_rwlock_rdlock(&rwl.rwlock);
assert(rc == .SUCCESS);
}
pub fn unlockShared(rwl: *PthreadRwLock) void {
const rc = std.c.pthread_rwlock_unlock(&rwl.rwlock);
assert(rc == .SUCCESS);
}
};
pub const DefaultRwLock = struct {
state: usize,
mutex: Mutex,
semaphore: Semaphore,
const IS_WRITING: usize = 1;
const WRITER: usize = 1 << 1;
const READER: usize = 1 << (1 + std.meta.bitCount(Count));
const WRITER_MASK: usize = std.math.maxInt(Count) << @ctz(WRITER);
const READER_MASK: usize = std.math.maxInt(Count) << @ctz(READER);
const Count = std.meta.Int(.unsigned, @divFloor(std.meta.bitCount(usize) - 1, 2));
pub fn init(rwl: *DefaultRwLock) void {
rwl.* = .{
.state = 0,
.mutex = Mutex.init(),
.semaphore = Semaphore.init(0),
};
}
pub fn deinit(rwl: *DefaultRwLock) void {
rwl.semaphore.deinit();
rwl.mutex.deinit();
rwl.* = undefined;
}
pub fn tryLock(rwl: *DefaultRwLock) bool {
if (rwl.mutex.tryLock()) {
const state = @atomicLoad(usize, &rwl.state, .SeqCst);
if (state & READER_MASK == 0) {
_ = @atomicRmw(usize, &rwl.state, .Or, IS_WRITING, .SeqCst);
return true;
}
rwl.mutex.unlock();
}
return false;
}
pub fn lock(rwl: *DefaultRwLock) void {
_ = @atomicRmw(usize, &rwl.state, .Add, WRITER, .SeqCst);
rwl.mutex.lock();
const state = @atomicRmw(usize, &rwl.state, .Or, IS_WRITING, .SeqCst);
if (state & READER_MASK != 0)
rwl.semaphore.wait();
}
pub fn unlock(rwl: *DefaultRwLock) void {
_ = @atomicRmw(usize, &rwl.state, .And, ~IS_WRITING, .SeqCst);
rwl.mutex.unlock();
}
pub fn tryLockShared(rwl: *DefaultRwLock) bool {
const state = @atomicLoad(usize, &rwl.state, .SeqCst);
if (state & (IS_WRITING | WRITER_MASK) == 0) {
_ = @cmpxchgStrong(
usize,
&rwl.state,
state,
state + READER,
.SeqCst,
.SeqCst,
) orelse return true;
}
if (rwl.mutex.tryLock()) {
_ = @atomicRmw(usize, &rwl.state, .Add, READER, .SeqCst);
rwl.mutex.unlock();
return true;
}
return false;
}
pub fn lockShared(rwl: *DefaultRwLock) void {
var state = @atomicLoad(usize, &rwl.state, .SeqCst);
while (state & (IS_WRITING | WRITER_MASK) == 0) {
state = @cmpxchgWeak(
usize,
&rwl.state,
state,
state + READER,
.SeqCst,
.SeqCst,
) orelse return;
}
rwl.mutex.lock();
_ = @atomicRmw(usize, &rwl.state, .Add, READER, .SeqCst);
rwl.mutex.unlock();
}
pub fn unlockShared(rwl: *DefaultRwLock) void {
const state = @atomicRmw(usize, &rwl.state, .Sub, READER, .SeqCst);
if ((state & READER_MASK == READER) and (state & IS_WRITING != 0))
rwl.semaphore.post();
}
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/AutoResetEvent.zig | //! Similar to `StaticResetEvent` but on `set()` it also (atomically) does `reset()`.
//! Unlike StaticResetEvent, `wait()` can only be called by one thread (MPSC-like).
//!
//! AutoResetEvent has 3 possible states:
//! - UNSET: the AutoResetEvent is currently unset
//! - SET: the AutoResetEvent was notified before a wait() was called
//! - <StaticResetEvent pointer>: there is an active waiter waiting for a notification.
//!
//! When attempting to wait:
//! if the event is unset, it registers a ResetEvent pointer to be notified when the event is set
//! if the event is already set, then it consumes the notification and resets the event.
//!
//! When attempting to notify:
//! if the event is unset, then we set the event
//! if theres a waiting ResetEvent, then we unset the event and notify the ResetEvent
//!
//! This ensures that the event is automatically reset after a wait() has been issued
//! and avoids the race condition when using StaticResetEvent in the following scenario:
//! thread 1 | thread 2
//! StaticResetEvent.wait() |
//! | StaticResetEvent.set()
//! | StaticResetEvent.set()
//! StaticResetEvent.reset() |
//! StaticResetEvent.wait() | (missed the second .set() notification above)
state: usize = UNSET,
const std = @import("../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const assert = std.debug.assert;
const StaticResetEvent = std.Thread.StaticResetEvent;
const AutoResetEvent = @This();
const UNSET = 0;
const SET = 1;
/// the minimum alignment for the `*StaticResetEvent` created by wait*()
const event_align = std.math.max(@alignOf(StaticResetEvent), 2);
pub fn wait(self: *AutoResetEvent) void {
self.waitFor(null) catch unreachable;
}
pub fn timedWait(self: *AutoResetEvent, timeout: u64) error{TimedOut}!void {
return self.waitFor(timeout);
}
fn waitFor(self: *AutoResetEvent, timeout: ?u64) error{TimedOut}!void {
// lazily initialized StaticResetEvent
var reset_event: StaticResetEvent align(event_align) = undefined;
var has_reset_event = false;
var state = @atomicLoad(usize, &self.state, .SeqCst);
while (true) {
// consume a notification if there is any
if (state == SET) {
@atomicStore(usize, &self.state, UNSET, .SeqCst);
return;
}
// check if theres currently a pending ResetEvent pointer already registered
if (state != UNSET) {
unreachable; // multiple waiting threads on the same AutoResetEvent
}
// lazily initialize the ResetEvent if it hasn't been already
if (!has_reset_event) {
has_reset_event = true;
reset_event = .{};
}
// Since the AutoResetEvent currently isnt set,
// try to register our ResetEvent on it to wait
// for a set() call from another thread.
if (@cmpxchgWeak(
usize,
&self.state,
UNSET,
@intFromPtr(&reset_event),
.SeqCst,
.SeqCst,
)) |new_state| {
state = new_state;
continue;
}
// if no timeout was specified, then just wait forever
const timeout_ns = timeout orelse {
reset_event.wait();
return;
};
// wait with a timeout and return if signalled via set()
switch (reset_event.timedWait(timeout_ns)) {
.event_set => return,
.timed_out => {},
}
// If we timed out, we need to transition the AutoResetEvent back to UNSET.
// If we don't, then when we return, a set() thread could observe a pointer to an invalid ResetEvent.
state = @cmpxchgStrong(
usize,
&self.state,
@intFromPtr(&reset_event),
UNSET,
.SeqCst,
.SeqCst,
) orelse return error.TimedOut;
// We didn't manage to unregister ourselves from the state.
if (state == SET) {
unreachable; // AutoResetEvent notified without waking up the waiting thread
} else if (state != UNSET) {
unreachable; // multiple waiting threads on the same AutoResetEvent observed when timing out
}
// This menas a set() thread saw our ResetEvent pointer, acquired it, and is trying to wake it up.
// We need to wait for it to wake up our ResetEvent before we can return and invalidate it.
// We don't return error.TimedOut here as it technically notified us while we were "timing out".
reset_event.wait();
return;
}
}
pub fn set(self: *AutoResetEvent) void {
var state = @atomicLoad(usize, &self.state, .SeqCst);
while (true) {
// If the AutoResetEvent is already set, there is nothing else left to do
if (state == SET) {
return;
}
// If the AutoResetEvent isn't set,
// then try to leave a notification for the wait() thread that we set() it.
if (state == UNSET) {
state = @cmpxchgWeak(
usize,
&self.state,
UNSET,
SET,
.SeqCst,
.SeqCst,
) orelse return;
continue;
}
// There is a ResetEvent pointer registered on the AutoResetEvent event thats waiting.
// Try to acquire ownership of it so that we can wake it up.
// This also resets the AutoResetEvent so that there is no race condition as defined above.
if (@cmpxchgWeak(
usize,
&self.state,
state,
UNSET,
.SeqCst,
.SeqCst,
)) |new_state| {
state = new_state;
continue;
}
const reset_event = @as(*align(event_align) StaticResetEvent, @ptrFromInt(state));
reset_event.set();
return;
}
}
test "basic usage" {
// test local code paths
{
var event = AutoResetEvent{};
try testing.expectError(error.TimedOut, event.timedWait(1));
event.set();
event.wait();
}
// test cross-thread signaling
if (builtin.single_threaded)
return;
const Context = struct {
value: u128 = 0,
in: AutoResetEvent = AutoResetEvent{},
out: AutoResetEvent = AutoResetEvent{},
const Self = @This();
fn sender(self: *Self) !void {
try testing.expect(self.value == 0);
self.value = 1;
self.out.set();
self.in.wait();
try testing.expect(self.value == 2);
self.value = 3;
self.out.set();
self.in.wait();
try testing.expect(self.value == 4);
}
fn receiver(self: *Self) !void {
self.out.wait();
try testing.expect(self.value == 1);
self.value = 2;
self.in.set();
self.out.wait();
try testing.expect(self.value == 3);
self.value = 4;
self.in.set();
}
};
var context = Context{};
const send_thread = try std.Thread.spawn(.{}, Context.sender, .{&context});
const recv_thread = try std.Thread.spawn(.{}, Context.receiver, .{&context});
send_thread.join();
recv_thread.join();
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/Mutex.zig | //! Lock may be held only once. If the same thread tries to acquire
//! the same mutex twice, it deadlocks. This type supports static
//! initialization and is at most `@sizeOf(usize)` in size. When an
//! application is built in single threaded release mode, all the
//! functions are no-ops. In single threaded debug mode, there is
//! deadlock detection.
//!
//! Example usage:
//! var m = Mutex{};
//!
//! const lock = m.acquire();
//! defer lock.release();
//! ... critical code
//!
//! Non-blocking:
//! if (m.tryAcquire) |lock| {
//! defer lock.release();
//! // ... critical section
//! } else {
//! // ... lock not acquired
//! }
impl: Impl = .{},
const Mutex = @This();
const std = @import("../std.zig");
const builtin = @import("builtin");
const os = std.os;
const assert = std.debug.assert;
const windows = os.windows;
const linux = os.linux;
const testing = std.testing;
const StaticResetEvent = std.thread.StaticResetEvent;
/// Try to acquire the mutex without blocking. Returns `null` if the mutex is
/// unavailable. Otherwise returns `Held`. Call `release` on `Held`, or use
/// releaseDirect().
pub fn tryAcquire(m: *Mutex) ?Held {
return m.impl.tryAcquire();
}
/// Acquire the mutex. Deadlocks if the mutex is already
/// held by the calling thread.
pub fn acquire(m: *Mutex) Held {
return m.impl.acquire();
}
/// Release the mutex. Prefer Held.release() if available.
pub fn releaseDirect(m: *Mutex) void {
return m.impl.releaseDirect();
}
/// A held mutex handle. Call release to allow other threads to
/// take the mutex. Do not call release() more than once.
/// For more complex scenarios, this handle can be discarded
/// and Mutex.releaseDirect can be called instead.
pub const Held = Impl.Held;
const Impl = if (builtin.single_threaded)
Dummy
else if (builtin.os.tag == .windows)
WindowsMutex
else if (std.Thread.use_pthreads)
PthreadMutex
else
AtomicMutex;
fn HeldInterface(comptime MutexType: type) type {
return struct {
const Mixin = @This();
pub const Held = struct {
mutex: *MutexType,
pub fn release(held: Mixin.Held) void {
held.mutex.releaseDirect();
}
};
pub fn tryAcquire(m: *MutexType) ?Mixin.Held {
if (m.tryAcquireDirect()) {
return Mixin.Held{ .mutex = m };
} else {
return null;
}
}
pub fn acquire(m: *MutexType) Mixin.Held {
m.acquireDirect();
return Mixin.Held{ .mutex = m };
}
};
}
pub const AtomicMutex = struct {
state: State = .unlocked,
const State = enum(i32) {
unlocked,
locked,
waiting,
};
pub usingnamespace HeldInterface(@This());
fn tryAcquireDirect(m: *AtomicMutex) bool {
return @cmpxchgStrong(
State,
&m.state,
.unlocked,
.locked,
.Acquire,
.Monotonic,
) == null;
}
fn acquireDirect(m: *AtomicMutex) void {
switch (@atomicRmw(State, &m.state, .Xchg, .locked, .Acquire)) {
.unlocked => {},
else => |s| m.lockSlow(s),
}
}
fn releaseDirect(m: *AtomicMutex) void {
switch (@atomicRmw(State, &m.state, .Xchg, .unlocked, .Release)) {
.unlocked => unreachable,
.locked => {},
.waiting => m.unlockSlow(),
}
}
fn lockSlow(m: *AtomicMutex, current_state: State) void {
@setCold(true);
var new_state = current_state;
var spin: u8 = 0;
while (spin < 100) : (spin += 1) {
const state = @cmpxchgWeak(
State,
&m.state,
.unlocked,
new_state,
.Acquire,
.Monotonic,
) orelse return;
switch (state) {
.unlocked => {},
.locked => {},
.waiting => break,
}
var iter = std.math.min(32, spin + 1);
while (iter > 0) : (iter -= 1)
std.atomic.spinLoopHint();
}
new_state = .waiting;
while (true) {
switch (@atomicRmw(State, &m.state, .Xchg, new_state, .Acquire)) {
.unlocked => return,
else => {},
}
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wait(
@as(*const i32, @ptrCast(&m.state)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAIT,
@intFromEnum(new_state),
null,
))) {
.SUCCESS => {},
.INTR => {},
.AGAIN => {},
else => unreachable,
}
},
else => std.atomic.spinLoopHint(),
}
}
}
fn unlockSlow(m: *AtomicMutex) void {
@setCold(true);
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wake(
@as(*const i32, @ptrCast(&m.state)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAKE,
1,
))) {
.SUCCESS => {},
.FAULT => unreachable, // invalid pointer passed to futex_wake
else => unreachable,
}
},
else => {},
}
}
};
pub const PthreadMutex = struct {
pthread_mutex: std.c.pthread_mutex_t = .{},
pub usingnamespace HeldInterface(@This());
/// Try to acquire the mutex without blocking. Returns true if
/// the mutex is unavailable. Otherwise returns false. Call
/// release when done.
fn tryAcquireDirect(m: *PthreadMutex) bool {
return std.c.pthread_mutex_trylock(&m.pthread_mutex) == .SUCCESS;
}
/// Acquire the mutex. Will deadlock if the mutex is already
/// held by the calling thread.
fn acquireDirect(m: *PthreadMutex) void {
switch (std.c.pthread_mutex_lock(&m.pthread_mutex)) {
.SUCCESS => {},
.INVAL => unreachable,
.BUSY => unreachable,
.AGAIN => unreachable,
.DEADLK => unreachable,
.PERM => unreachable,
else => unreachable,
}
}
fn releaseDirect(m: *PthreadMutex) void {
switch (std.c.pthread_mutex_unlock(&m.pthread_mutex)) {
.SUCCESS => return,
.INVAL => unreachable,
.AGAIN => unreachable,
.PERM => unreachable,
else => unreachable,
}
}
};
/// This has the sematics as `Mutex`, however it does not actually do any
/// synchronization. Operations are safety-checked no-ops.
pub const Dummy = struct {
lock: @TypeOf(lock_init) = lock_init,
pub usingnamespace HeldInterface(@This());
const lock_init = if (std.debug.runtime_safety) false else {};
/// Try to acquire the mutex without blocking. Returns false if
/// the mutex is unavailable. Otherwise returns true.
fn tryAcquireDirect(m: *Dummy) bool {
if (std.debug.runtime_safety) {
if (m.lock) return false;
m.lock = true;
}
return true;
}
/// Acquire the mutex. Will deadlock if the mutex is already
/// held by the calling thread.
fn acquireDirect(m: *Dummy) void {
if (!m.tryAcquireDirect()) {
@panic("deadlock detected");
}
}
fn releaseDirect(m: *Dummy) void {
if (std.debug.runtime_safety) {
m.lock = false;
}
}
};
const WindowsMutex = struct {
srwlock: windows.SRWLOCK = windows.SRWLOCK_INIT,
pub usingnamespace HeldInterface(@This());
fn tryAcquireDirect(m: *WindowsMutex) bool {
return windows.kernel32.TryAcquireSRWLockExclusive(&m.srwlock) != windows.FALSE;
}
fn acquireDirect(m: *WindowsMutex) void {
windows.kernel32.AcquireSRWLockExclusive(&m.srwlock);
}
fn releaseDirect(m: *WindowsMutex) void {
windows.kernel32.ReleaseSRWLockExclusive(&m.srwlock);
}
};
const TestContext = struct {
mutex: *Mutex,
data: i128,
const incr_count = 10000;
};
test "basic usage" {
var mutex = Mutex{};
var context = TestContext{
.mutex = &mutex,
.data = 0,
};
if (builtin.single_threaded) {
worker(&context);
try testing.expect(context.data == TestContext.incr_count);
} else {
const thread_count = 10;
var threads: [thread_count]std.Thread = undefined;
for (threads) |*t| {
t.* = try std.Thread.spawn(.{}, worker, .{&context});
}
for (threads) |t|
t.join();
try testing.expect(context.data == thread_count * TestContext.incr_count);
}
}
fn worker(ctx: *TestContext) void {
var i: usize = 0;
while (i != TestContext.incr_count) : (i += 1) {
const held = ctx.mutex.acquire();
defer held.release();
ctx.data += 1;
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/Condition.zig | //! A condition provides a way for a kernel thread to block until it is signaled
//! to wake up. Spurious wakeups are possible.
//! This API supports static initialization and does not require deinitialization.
impl: Impl = .{},
const std = @import("../std.zig");
const builtin = @import("builtin");
const Condition = @This();
const windows = std.os.windows;
const linux = std.os.linux;
const Mutex = std.Thread.Mutex;
const assert = std.debug.assert;
pub fn wait(cond: *Condition, mutex: *Mutex) void {
cond.impl.wait(mutex);
}
pub fn signal(cond: *Condition) void {
cond.impl.signal();
}
pub fn broadcast(cond: *Condition) void {
cond.impl.broadcast();
}
const Impl = if (builtin.single_threaded)
SingleThreadedCondition
else if (builtin.os.tag == .windows)
WindowsCondition
else if (std.Thread.use_pthreads)
PthreadCondition
else
AtomicCondition;
pub const SingleThreadedCondition = struct {
pub fn wait(cond: *SingleThreadedCondition, mutex: *Mutex) void {
_ = cond;
_ = mutex;
unreachable; // deadlock detected
}
pub fn signal(cond: *SingleThreadedCondition) void {
_ = cond;
}
pub fn broadcast(cond: *SingleThreadedCondition) void {
_ = cond;
}
};
pub const WindowsCondition = struct {
cond: windows.CONDITION_VARIABLE = windows.CONDITION_VARIABLE_INIT,
pub fn wait(cond: *WindowsCondition, mutex: *Mutex) void {
const rc = windows.kernel32.SleepConditionVariableSRW(
&cond.cond,
&mutex.impl.srwlock,
windows.INFINITE,
@as(windows.ULONG, 0),
);
assert(rc != windows.FALSE);
}
pub fn signal(cond: *WindowsCondition) void {
windows.kernel32.WakeConditionVariable(&cond.cond);
}
pub fn broadcast(cond: *WindowsCondition) void {
windows.kernel32.WakeAllConditionVariable(&cond.cond);
}
};
pub const PthreadCondition = struct {
cond: std.c.pthread_cond_t = .{},
pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {
const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);
assert(rc == .SUCCESS);
}
pub fn signal(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_signal(&cond.cond);
assert(rc == .SUCCESS);
}
pub fn broadcast(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_broadcast(&cond.cond);
assert(rc == .SUCCESS);
}
};
pub const AtomicCondition = struct {
pending: bool = false,
queue_mutex: Mutex = .{},
queue_list: QueueList = .{},
pub const QueueList = std.SinglyLinkedList(QueueItem);
pub const QueueItem = struct {
futex: i32 = 0,
fn wait(cond: *@This()) void {
while (@atomicLoad(i32, &cond.futex, .Acquire) == 0) {
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wait(
&cond.futex,
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAIT,
0,
null,
))) {
.SUCCESS => {},
.INTR => {},
.AGAIN => {},
else => unreachable,
}
},
else => std.atomic.spinLoopHint(),
}
}
}
fn notify(cond: *@This()) void {
@atomicStore(i32, &cond.futex, 1, .Release);
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wake(
&cond.futex,
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
1,
))) {
.SUCCESS => {},
.FAULT => {},
else => unreachable,
}
},
else => {},
}
}
};
pub fn wait(cond: *AtomicCondition, mutex: *Mutex) void {
var waiter = QueueList.Node{ .data = .{} };
{
const held = cond.queue_mutex.acquire();
defer held.release();
cond.queue_list.prepend(&waiter);
@atomicStore(bool, &cond.pending, true, .SeqCst);
}
mutex.unlock();
waiter.data.wait();
mutex.lock();
}
pub fn signal(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
const maybe_waiter = blk: {
const held = cond.queue_mutex.acquire();
defer held.release();
const maybe_waiter = cond.queue_list.popFirst();
@atomicStore(bool, &cond.pending, cond.queue_list.first != null, .SeqCst);
break :blk maybe_waiter;
};
if (maybe_waiter) |waiter|
waiter.data.notify();
}
pub fn broadcast(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
@atomicStore(bool, &cond.pending, false, .SeqCst);
var waiters = blk: {
const held = cond.queue_mutex.acquire();
defer held.release();
const waiters = cond.queue_list;
cond.queue_list = .{};
break :blk waiters;
};
while (waiters.popFirst()) |waiter|
waiter.data.notify();
}
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/Thread/StaticResetEvent.zig | //! A thread-safe resource which supports blocking until signaled.
//! This API is for kernel threads, not evented I/O.
//! This API is statically initializable. It cannot fail to be initialized
//! and it requires no deinitialization. The downside is that it may not
//! integrate as cleanly into other synchronization APIs, or, in a worst case,
//! may be forced to fall back on spin locking. As a rule of thumb, prefer
//! to use `std.Thread.ResetEvent` when possible, and use `StaticResetEvent` when
//! the logic needs stronger API guarantees.
const std = @import("../std.zig");
const builtin = @import("builtin");
const StaticResetEvent = @This();
const assert = std.debug.assert;
const os = std.os;
const time = std.time;
const linux = std.os.linux;
const windows = std.os.windows;
const testing = std.testing;
impl: Impl = .{},
pub const Impl = if (builtin.single_threaded)
DebugEvent
else
AtomicEvent;
/// Sets the event if not already set and wakes up all the threads waiting on
/// the event. It is safe to call `set` multiple times before calling `wait`.
/// However it is illegal to call `set` after `wait` is called until the event
/// is `reset`. This function is thread-safe.
pub fn set(ev: *StaticResetEvent) void {
return ev.impl.set();
}
/// Wait for the event to be set by blocking the current thread.
/// Thread-safe. No spurious wakeups.
/// Upon return from `wait`, the only function available to be called
/// in `StaticResetEvent` is `reset`.
pub fn wait(ev: *StaticResetEvent) void {
return ev.impl.wait();
}
/// Resets the event to its original, unset state.
/// This function is *not* thread-safe. It is equivalent to calling
/// `deinit` followed by `init` but without the possibility of failure.
pub fn reset(ev: *StaticResetEvent) void {
return ev.impl.reset();
}
pub const TimedWaitResult = std.Thread.ResetEvent.TimedWaitResult;
/// Wait for the event to be set by blocking the current thread.
/// A timeout in nanoseconds can be provided as a hint for how
/// long the thread should block on the unset event before returning
/// `TimedWaitResult.timed_out`.
/// Thread-safe. No precision of timing is guaranteed.
/// Upon return from `timedWait`, the only function available to be called
/// in `StaticResetEvent` is `reset`.
pub fn timedWait(ev: *StaticResetEvent, timeout_ns: u64) TimedWaitResult {
return ev.impl.timedWait(timeout_ns);
}
/// For single-threaded builds, we use this to detect deadlocks.
/// In unsafe modes this ends up being no-ops.
pub const DebugEvent = struct {
state: State = State.unset,
const State = enum {
unset,
set,
waited,
};
/// This function is provided so that this type can be re-used inside
/// `std.Thread.ResetEvent`.
pub fn init(ev: *DebugEvent) void {
ev.* = .{};
}
/// This function is provided so that this type can be re-used inside
/// `std.Thread.ResetEvent`.
pub fn deinit(ev: *DebugEvent) void {
ev.* = undefined;
}
pub fn set(ev: *DebugEvent) void {
switch (ev.state) {
.unset => ev.state = .set,
.set => {},
.waited => unreachable, // Not allowed to call `set` until `reset`.
}
}
pub fn wait(ev: *DebugEvent) void {
switch (ev.state) {
.unset => unreachable, // Deadlock detected.
.set => return,
.waited => unreachable, // Not allowed to call `wait` until `reset`.
}
}
pub fn timedWait(ev: *DebugEvent, timeout: u64) TimedWaitResult {
_ = timeout;
switch (ev.state) {
.unset => return .timed_out,
.set => return .event_set,
.waited => unreachable, // Not allowed to call `wait` until `reset`.
}
}
pub fn reset(ev: *DebugEvent) void {
ev.state = .unset;
}
};
pub const AtomicEvent = struct {
waiters: u32 = 0,
const WAKE = 1 << 0;
const WAIT = 1 << 1;
/// This function is provided so that this type can be re-used inside
/// `std.Thread.ResetEvent`.
pub fn init(ev: *AtomicEvent) void {
ev.* = .{};
}
/// This function is provided so that this type can be re-used inside
/// `std.Thread.ResetEvent`.
pub fn deinit(ev: *AtomicEvent) void {
ev.* = undefined;
}
pub fn set(ev: *AtomicEvent) void {
const waiters = @atomicRmw(u32, &ev.waiters, .Xchg, WAKE, .Release);
if (waiters >= WAIT) {
return Futex.wake(&ev.waiters, waiters >> 1);
}
}
pub fn wait(ev: *AtomicEvent) void {
switch (ev.timedWait(null)) {
.timed_out => unreachable,
.event_set => return,
}
}
pub fn timedWait(ev: *AtomicEvent, timeout: ?u64) TimedWaitResult {
var waiters = @atomicLoad(u32, &ev.waiters, .Acquire);
while (waiters != WAKE) {
waiters = @cmpxchgWeak(u32, &ev.waiters, waiters, waiters + WAIT, .Acquire, .Acquire) orelse {
if (Futex.wait(&ev.waiters, timeout)) |_| {
return .event_set;
} else |_| {
return .timed_out;
}
};
}
return .event_set;
}
pub fn reset(ev: *AtomicEvent) void {
@atomicStore(u32, &ev.waiters, 0, .Monotonic);
}
pub const Futex = switch (builtin.os.tag) {
.windows => WindowsFutex,
.linux => LinuxFutex,
else => SpinFutex,
};
pub const SpinFutex = struct {
fn wake(waiters: *u32, wake_count: u32) void {
_ = waiters;
_ = wake_count;
}
fn wait(waiters: *u32, timeout: ?u64) !void {
var timer: time.Timer = undefined;
if (timeout != null)
timer = time.Timer.start() catch return error.TimedOut;
while (@atomicLoad(u32, waiters, .Acquire) != WAKE) {
std.os.sched_yield() catch std.atomic.spinLoopHint();
if (timeout) |timeout_ns| {
if (timer.read() >= timeout_ns)
return error.TimedOut;
}
}
}
};
pub const LinuxFutex = struct {
fn wake(waiters: *u32, wake_count: u32) void {
_ = wake_count;
const waiting = std.math.maxInt(i32); // wake_count
const ptr = @as(*const i32, @ptrCast(waiters));
const rc = linux.futex_wake(ptr, linux.FUTEX.WAKE | linux.FUTEX.PRIVATE_FLAG, waiting);
assert(linux.getErrno(rc) == .SUCCESS);
}
fn wait(waiters: *u32, timeout: ?u64) !void {
var ts: linux.timespec = undefined;
var ts_ptr: ?*linux.timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts.tv_sec = @as(isize, @intCast(timeout_ns / time.ns_per_s));
ts.tv_nsec = @as(isize, @intCast(timeout_ns % time.ns_per_s));
}
while (true) {
const waiting = @atomicLoad(u32, waiters, .Acquire);
if (waiting == WAKE)
return;
const expected = @as(i32, @intCast(waiting));
const ptr = @as(*const i32, @ptrCast(waiters));
const rc = linux.futex_wait(ptr, linux.FUTEX.WAIT | linux.FUTEX.PRIVATE_FLAG, expected, ts_ptr);
switch (linux.getErrno(rc)) {
.SUCCESS => continue,
.TIMEDOUT => return error.TimedOut,
.INTR => continue,
.AGAIN => return,
else => unreachable,
}
}
}
};
pub const WindowsFutex = struct {
pub fn wake(waiters: *u32, wake_count: u32) void {
const handle = getEventHandle() orelse return SpinFutex.wake(waiters, wake_count);
const key = @as(*const anyopaque, @ptrCast(waiters));
var waiting = wake_count;
while (waiting != 0) : (waiting -= 1) {
const rc = windows.ntdll.NtReleaseKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == .SUCCESS);
}
}
pub fn wait(waiters: *u32, timeout: ?u64) !void {
const handle = getEventHandle() orelse return SpinFutex.wait(waiters, timeout);
const key = @as(*const anyopaque, @ptrCast(waiters));
// NT uses timeouts in units of 100ns with negative value being relative
var timeout_ptr: ?*windows.LARGE_INTEGER = null;
var timeout_value: windows.LARGE_INTEGER = undefined;
if (timeout) |timeout_ns| {
timeout_ptr = &timeout_value;
timeout_value = -@as(windows.LARGE_INTEGER, @intCast(timeout_ns / 100));
}
// NtWaitForKeyedEvent doesnt have spurious wake-ups
var rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, timeout_ptr);
switch (rc) {
.TIMEOUT => {
// update the wait count to signal that we're not waiting anymore.
// if the .set() thread already observed that we are, perform a
// matching NtWaitForKeyedEvent so that the .set() thread doesn't
// deadlock trying to run NtReleaseKeyedEvent above.
var waiting = @atomicLoad(u32, waiters, .Monotonic);
while (true) {
if (waiting == WAKE) {
rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == windows.NTSTATUS.WAIT_0);
break;
} else {
waiting = @cmpxchgWeak(u32, waiters, waiting, waiting - WAIT, .Acquire, .Monotonic) orelse break;
continue;
}
}
return error.TimedOut;
},
windows.NTSTATUS.WAIT_0 => {},
else => unreachable,
}
}
var event_handle: usize = EMPTY;
const EMPTY = ~@as(usize, 0);
const LOADING = EMPTY - 1;
pub fn getEventHandle() ?windows.HANDLE {
var handle = @atomicLoad(usize, &event_handle, .Monotonic);
while (true) {
switch (handle) {
EMPTY => handle = @cmpxchgWeak(usize, &event_handle, EMPTY, LOADING, .Acquire, .Monotonic) orelse {
const handle_ptr = @as(*windows.HANDLE, @ptrCast(&handle));
const access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE;
if (windows.ntdll.NtCreateKeyedEvent(handle_ptr, access_mask, null, 0) != .SUCCESS)
handle = 0;
@atomicStore(usize, &event_handle, handle, .Monotonic);
return @as(?windows.HANDLE, @ptrFromInt(handle));
},
LOADING => {
std.os.sched_yield() catch std.atomic.spinLoopHint();
handle = @atomicLoad(usize, &event_handle, .Monotonic);
},
else => {
return @as(?windows.HANDLE, @ptrFromInt(handle));
},
}
}
}
};
};
test "basic usage" {
var event = StaticResetEvent{};
// test event setting
event.set();
// test event resetting
event.reset();
// test event waiting (non-blocking)
event.set();
event.wait();
event.reset();
event.set();
try testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
// test cross-thread signaling
if (builtin.single_threaded)
return;
const Context = struct {
const Self = @This();
value: u128 = 0,
in: StaticResetEvent = .{},
out: StaticResetEvent = .{},
fn sender(self: *Self) !void {
// update value and signal input
try testing.expect(self.value == 0);
self.value = 1;
self.in.set();
// wait for receiver to update value and signal output
self.out.wait();
try testing.expect(self.value == 2);
// update value and signal final input
self.value = 3;
self.in.set();
}
fn receiver(self: *Self) !void {
// wait for sender to update value and signal input
self.in.wait();
try testing.expect(self.value == 1);
// update value and signal output
self.in.reset();
self.value = 2;
self.out.set();
// wait for sender to update value and signal final input
self.in.wait();
try testing.expect(self.value == 3);
}
fn sleeper(self: *Self) void {
self.in.set();
time.sleep(time.ns_per_ms * 2);
self.value = 5;
self.out.set();
}
fn timedWaiter(self: *Self) !void {
self.in.wait();
try testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try self.out.timedWait(time.ns_per_ms * 100);
try testing.expect(self.value == 5);
}
};
var context = Context{};
const receiver = try std.Thread.spawn(.{}, Context.receiver, .{&context});
defer receiver.join();
try context.sender();
if (false) {
// I have now observed this fail on macOS, Windows, and Linux.
// https://github.com/ziglang/zig/issues/7009
var timed = Context.init();
defer timed.deinit();
const sleeper = try std.Thread.spawn(.{}, Context.sleeper, .{&timed});
defer sleeper.join();
try timed.timedWaiter();
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/WriteFileStep.zig | const std = @import("../std.zig");
const build = @import("../build.zig");
const Step = build.Step;
const Builder = build.Builder;
const fs = std.fs;
const warn = std.debug.warn;
const ArrayList = std.ArrayList;
const WriteFileStep = @This();
pub const base_id = .write_file;
step: Step,
builder: *Builder,
output_dir: []const u8,
files: std.TailQueue(File),
pub const File = struct {
source: build.GeneratedFile,
basename: []const u8,
bytes: []const u8,
};
pub fn init(builder: *Builder) WriteFileStep {
return WriteFileStep{
.builder = builder,
.step = Step.init(.write_file, "writefile", builder.allocator, make),
.files = .{},
.output_dir = undefined,
};
}
pub fn add(self: *WriteFileStep, basename: []const u8, bytes: []const u8) void {
const node = self.builder.allocator.create(std.TailQueue(File).Node) catch unreachable;
node.* = .{
.data = .{
.source = build.GeneratedFile{ .step = &self.step },
.basename = self.builder.dupePath(basename),
.bytes = self.builder.dupe(bytes),
},
};
self.files.append(node);
}
/// Gets a file source for the given basename. If the file does not exist, returns `null`.
pub fn getFileSource(step: *WriteFileStep, basename: []const u8) ?build.FileSource {
var it = step.files.first;
while (it) |node| : (it = node.next) {
if (std.mem.eql(u8, node.data.basename, basename))
return build.FileSource{ .generated = &node.data.source };
}
return null;
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(WriteFileStep, "step", step);
// The cache is used here not really as a way to speed things up - because writing
// the data to a file would probably be very fast - but as a way to find a canonical
// location to put build artifacts.
// If, for example, a hard-coded path was used as the location to put WriteFileStep
// files, then two WriteFileSteps executing in parallel might clobber each other.
// TODO port the cache system from stage1 to zig std lib. Until then we use blake2b
// directly and construct the path, and no "cache hit" detection happens; the files
// are always written.
var hash = std.crypto.hash.blake2.Blake2b384.init(.{});
// Random bytes to make WriteFileStep unique. Refresh this with
// new random bytes when WriteFileStep implementation is modified
// in a non-backwards-compatible way.
hash.update("eagVR1dYXoE7ARDP");
{
var it = self.files.first;
while (it) |node| : (it = node.next) {
hash.update(node.data.basename);
hash.update(node.data.bytes);
hash.update("|");
}
}
var digest: [48]u8 = undefined;
hash.final(&digest);
var hash_basename: [64]u8 = undefined;
_ = fs.base64_encoder.encode(&hash_basename, &digest);
self.output_dir = try fs.path.join(self.builder.allocator, &[_][]const u8{
self.builder.cache_root,
"o",
&hash_basename,
});
// TODO replace with something like fs.makePathAndOpenDir
fs.cwd().makePath(self.output_dir) catch |err| {
warn("unable to make path {s}: {s}\n", .{ self.output_dir, @errorName(err) });
return err;
};
var dir = try fs.cwd().openDir(self.output_dir, .{});
defer dir.close();
{
var it = self.files.first;
while (it) |node| : (it = node.next) {
dir.writeFile(node.data.basename, node.data.bytes) catch |err| {
warn("unable to write {s} into {s}: {s}\n", .{
node.data.basename,
self.output_dir,
@errorName(err),
});
return err;
};
node.data.source.path = fs.path.join(
self.builder.allocator,
&[_][]const u8{ self.output_dir, node.data.basename },
) catch unreachable;
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/TranslateCStep.zig | const std = @import("../std.zig");
const build = std.build;
const Step = build.Step;
const Builder = build.Builder;
const LibExeObjStep = build.LibExeObjStep;
const CheckFileStep = build.CheckFileStep;
const fs = std.fs;
const mem = std.mem;
const CrossTarget = std.zig.CrossTarget;
const TranslateCStep = @This();
pub const base_id = .translate_c;
step: Step,
builder: *Builder,
source: build.FileSource,
include_dirs: std.ArrayList([]const u8),
output_dir: ?[]const u8,
out_basename: []const u8,
target: CrossTarget = CrossTarget{},
output_file: build.GeneratedFile,
pub fn create(builder: *Builder, source: build.FileSource) *TranslateCStep {
const self = builder.allocator.create(TranslateCStep) catch unreachable;
self.* = TranslateCStep{
.step = Step.init(.translate_c, "translate-c", builder.allocator, make),
.builder = builder,
.source = source,
.include_dirs = std.ArrayList([]const u8).init(builder.allocator),
.output_dir = null,
.out_basename = undefined,
.output_file = build.GeneratedFile{ .step = &self.step },
};
source.addStepDependencies(&self.step);
return self;
}
pub fn setTarget(self: *TranslateCStep, target: CrossTarget) void {
self.target = target;
}
/// Creates a step to build an executable from the translated source.
pub fn addExecutable(self: *TranslateCStep) *LibExeObjStep {
return self.builder.addExecutableSource("translated_c", build.FileSource{ .generated = &self.output_file });
}
pub fn addIncludeDir(self: *TranslateCStep, include_dir: []const u8) void {
self.include_dirs.append(self.builder.dupePath(include_dir)) catch unreachable;
}
pub fn addCheckFile(self: *TranslateCStep, expected_matches: []const []const u8) *CheckFileStep {
return CheckFileStep.create(self.builder, .{ .generated = &self.output_file }, self.builder.dupeStrings(expected_matches));
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(TranslateCStep, "step", step);
var argv_list = std.ArrayList([]const u8).init(self.builder.allocator);
try argv_list.append(self.builder.zig_exe);
try argv_list.append("translate-c");
try argv_list.append("-lc");
try argv_list.append("--enable-cache");
if (!self.target.isNative()) {
try argv_list.append("-target");
try argv_list.append(try self.target.zigTriple(self.builder.allocator));
}
for (self.include_dirs.items) |include_dir| {
try argv_list.append("-I");
try argv_list.append(include_dir);
}
try argv_list.append(self.source.getPath(self.builder));
const output_path_nl = try self.builder.execFromStep(argv_list.items, &self.step);
const output_path = mem.trimRight(u8, output_path_nl, "\r\n");
self.out_basename = fs.path.basename(output_path);
if (self.output_dir) |output_dir| {
const full_dest = try fs.path.join(self.builder.allocator, &[_][]const u8{ output_dir, self.out_basename });
try self.builder.updateFile(output_path, full_dest);
} else {
self.output_dir = fs.path.dirname(output_path).?;
}
self.output_file.path = fs.path.join(
self.builder.allocator,
&[_][]const u8{ self.output_dir.?, self.out_basename },
) catch unreachable;
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/RunStep.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const build = std.build;
const Step = build.Step;
const Builder = build.Builder;
const LibExeObjStep = build.LibExeObjStep;
const WriteFileStep = build.WriteFileStep;
const fs = std.fs;
const mem = std.mem;
const process = std.process;
const ArrayList = std.ArrayList;
const BufMap = std.BufMap;
const warn = std.debug.warn;
const max_stdout_size = 1 * 1024 * 1024; // 1 MiB
const RunStep = @This();
pub const base_id = .run;
step: Step,
builder: *Builder,
/// See also addArg and addArgs to modifying this directly
argv: ArrayList(Arg),
/// Set this to modify the current working directory
cwd: ?[]const u8,
/// Override this field to modify the environment, or use setEnvironmentVariable
env_map: ?*BufMap,
stdout_action: StdIoAction = .inherit,
stderr_action: StdIoAction = .inherit,
stdin_behavior: std.ChildProcess.StdIo = .Inherit,
expected_exit_code: u8 = 0,
pub const StdIoAction = union(enum) {
inherit,
ignore,
expect_exact: []const u8,
expect_matches: []const []const u8,
};
pub const Arg = union(enum) {
artifact: *LibExeObjStep,
file_source: build.FileSource,
bytes: []u8,
};
pub fn create(builder: *Builder, name: []const u8) *RunStep {
const self = builder.allocator.create(RunStep) catch unreachable;
self.* = RunStep{
.builder = builder,
.step = Step.init(.run, name, builder.allocator, make),
.argv = ArrayList(Arg).init(builder.allocator),
.cwd = null,
.env_map = null,
};
return self;
}
pub fn addArtifactArg(self: *RunStep, artifact: *LibExeObjStep) void {
self.argv.append(Arg{ .artifact = artifact }) catch unreachable;
self.step.dependOn(&artifact.step);
}
pub fn addFileSourceArg(self: *RunStep, file_source: build.FileSource) void {
self.argv.append(Arg{
.file_source = file_source.dupe(self.builder),
}) catch unreachable;
file_source.addStepDependencies(&self.step);
}
pub fn addArg(self: *RunStep, arg: []const u8) void {
self.argv.append(Arg{ .bytes = self.builder.dupe(arg) }) catch unreachable;
}
pub fn addArgs(self: *RunStep, args: []const []const u8) void {
for (args) |arg| {
self.addArg(arg);
}
}
pub fn clearEnvironment(self: *RunStep) void {
const new_env_map = self.builder.allocator.create(BufMap) catch unreachable;
new_env_map.* = BufMap.init(self.builder.allocator);
self.env_map = new_env_map;
}
pub fn addPathDir(self: *RunStep, search_path: []const u8) void {
const env_map = self.getEnvMap();
var key: []const u8 = undefined;
var prev_path: ?[]const u8 = undefined;
if (builtin.os.tag == .windows) {
key = "Path";
prev_path = env_map.get(key);
if (prev_path == null) {
key = "PATH";
prev_path = env_map.get(key);
}
} else {
key = "PATH";
prev_path = env_map.get(key);
}
if (prev_path) |pp| {
const new_path = self.builder.fmt("{s}" ++ [1]u8{fs.path.delimiter} ++ "{s}", .{ pp, search_path });
env_map.put(key, new_path) catch unreachable;
} else {
env_map.put(key, self.builder.dupePath(search_path)) catch unreachable;
}
}
pub fn getEnvMap(self: *RunStep) *BufMap {
return self.env_map orelse {
const env_map = self.builder.allocator.create(BufMap) catch unreachable;
env_map.* = process.getEnvMap(self.builder.allocator) catch unreachable;
self.env_map = env_map;
return env_map;
};
}
pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8) void {
const env_map = self.getEnvMap();
env_map.put(
self.builder.dupe(key),
self.builder.dupe(value),
) catch unreachable;
}
pub fn expectStdErrEqual(self: *RunStep, bytes: []const u8) void {
self.stderr_action = .{ .expect_exact = self.builder.dupe(bytes) };
}
pub fn expectStdOutEqual(self: *RunStep, bytes: []const u8) void {
self.stdout_action = .{ .expect_exact = self.builder.dupe(bytes) };
}
fn stdIoActionToBehavior(action: StdIoAction) std.ChildProcess.StdIo {
return switch (action) {
.ignore => .Ignore,
.inherit => .Inherit,
.expect_exact, .expect_matches => .Pipe,
};
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(RunStep, "step", step);
const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;
var argv_list = ArrayList([]const u8).init(self.builder.allocator);
for (self.argv.items) |arg| {
switch (arg) {
.bytes => |bytes| try argv_list.append(bytes),
.file_source => |file| try argv_list.append(file.getPath(self.builder)),
.artifact => |artifact| {
if (artifact.target.isWindows()) {
// On Windows we don't have rpaths so we have to add .dll search paths to PATH
self.addPathForDynLibs(artifact);
}
const executable_path = artifact.installed_path orelse artifact.getOutputSource().getPath(self.builder);
try argv_list.append(executable_path);
},
}
}
const argv = argv_list.items;
const child = std.ChildProcess.init(argv, self.builder.allocator) catch unreachable;
defer child.deinit();
child.cwd = cwd;
child.env_map = self.env_map orelse self.builder.env_map;
child.stdin_behavior = self.stdin_behavior;
child.stdout_behavior = stdIoActionToBehavior(self.stdout_action);
child.stderr_behavior = stdIoActionToBehavior(self.stderr_action);
child.spawn() catch |err| {
warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return err;
};
// TODO need to poll to read these streams to prevent a deadlock (or rely on evented I/O).
var stdout: ?[]const u8 = null;
defer if (stdout) |s| self.builder.allocator.free(s);
switch (self.stdout_action) {
.expect_exact, .expect_matches => {
stdout = child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
},
.inherit, .ignore => {},
}
var stderr: ?[]const u8 = null;
defer if (stderr) |s| self.builder.allocator.free(s);
switch (self.stderr_action) {
.expect_exact, .expect_matches => {
stderr = child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
},
.inherit, .ignore => {},
}
const term = child.wait() catch |err| {
warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return err;
};
switch (term) {
.Exited => |code| {
if (code != self.expected_exit_code) {
if (self.builder.prominent_compile_errors) {
warn("Run step exited with error code {} (expected {})\n", .{
code,
self.expected_exit_code,
});
} else {
warn("The following command exited with error code {} (expected {}):\n", .{
code,
self.expected_exit_code,
});
printCmd(cwd, argv);
}
return error.UnexpectedExitCode;
}
},
else => {
warn("The following command terminated unexpectedly:\n", .{});
printCmd(cwd, argv);
return error.UncleanExit;
},
}
switch (self.stderr_action) {
.inherit, .ignore => {},
.expect_exact => |expected_bytes| {
if (!mem.eql(u8, expected_bytes, stderr.?)) {
warn(
\\
\\========= Expected this stderr: =========
\\{s}
\\========= But found: ====================
\\{s}
\\
, .{ expected_bytes, stderr.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
.expect_matches => |matches| for (matches) |match| {
if (mem.indexOf(u8, stderr.?, match) == null) {
warn(
\\
\\========= Expected to find in stderr: =========
\\{s}
\\========= But stderr does not contain it: =====
\\{s}
\\
, .{ match, stderr.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
}
switch (self.stdout_action) {
.inherit, .ignore => {},
.expect_exact => |expected_bytes| {
if (!mem.eql(u8, expected_bytes, stdout.?)) {
warn(
\\
\\========= Expected this stdout: =========
\\{s}
\\========= But found: ====================
\\{s}
\\
, .{ expected_bytes, stdout.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
.expect_matches => |matches| for (matches) |match| {
if (mem.indexOf(u8, stdout.?, match) == null) {
warn(
\\
\\========= Expected to find in stdout: =========
\\{s}
\\========= But stdout does not contain it: =====
\\{s}
\\
, .{ match, stdout.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
}
}
fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void {
if (cwd) |yes_cwd| warn("cd {s} && ", .{yes_cwd});
for (argv) |arg| {
warn("{s} ", .{arg});
}
warn("\n", .{});
}
fn addPathForDynLibs(self: *RunStep, artifact: *LibExeObjStep) void {
for (artifact.link_objects.items) |link_object| {
switch (link_object) {
.other_step => |other| {
if (other.target.isWindows() and other.isDynamicLibrary()) {
self.addPathDir(fs.path.dirname(other.getOutputSource().getPath(self.builder)).?);
self.addPathForDynLibs(other);
}
},
else => {},
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/InstallRawStep.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.ArrayList;
const Builder = std.build.Builder;
const File = std.fs.File;
const InstallDir = std.build.InstallDir;
const LibExeObjStep = std.build.LibExeObjStep;
const Step = std.build.Step;
const elf = std.elf;
const fs = std.fs;
const io = std.io;
const sort = std.sort;
const warn = std.debug.warn;
const BinaryElfSection = struct {
elfOffset: u64,
binaryOffset: u64,
fileSize: usize,
segment: ?*BinaryElfSegment,
};
const BinaryElfSegment = struct {
physicalAddress: u64,
virtualAddress: u64,
elfOffset: u64,
binaryOffset: u64,
fileSize: usize,
firstSection: ?*BinaryElfSection,
};
const BinaryElfOutput = struct {
segments: ArrayList(*BinaryElfSegment),
sections: ArrayList(*BinaryElfSection),
const Self = @This();
pub fn deinit(self: *Self) void {
self.sections.deinit();
self.segments.deinit();
}
pub fn parse(allocator: *Allocator, elf_file: File) !Self {
var self: Self = .{
.segments = ArrayList(*BinaryElfSegment).init(allocator),
.sections = ArrayList(*BinaryElfSection).init(allocator),
};
const elf_hdr = try std.elf.Header.read(&elf_file);
var section_headers = elf_hdr.section_header_iterator(&elf_file);
while (try section_headers.next()) |section| {
if (sectionValidForOutput(section)) {
const newSection = try allocator.create(BinaryElfSection);
newSection.binaryOffset = 0;
newSection.elfOffset = section.sh_offset;
newSection.fileSize = @as(usize, @intCast(section.sh_size));
newSection.segment = null;
try self.sections.append(newSection);
}
}
var program_headers = elf_hdr.program_header_iterator(&elf_file);
while (try program_headers.next()) |phdr| {
if (phdr.p_type == elf.PT_LOAD) {
const newSegment = try allocator.create(BinaryElfSegment);
newSegment.physicalAddress = if (phdr.p_paddr != 0) phdr.p_paddr else phdr.p_vaddr;
newSegment.virtualAddress = phdr.p_vaddr;
newSegment.fileSize = @as(usize, @intCast(phdr.p_filesz));
newSegment.elfOffset = phdr.p_offset;
newSegment.binaryOffset = 0;
newSegment.firstSection = null;
for (self.sections.items) |section| {
if (sectionWithinSegment(section, phdr)) {
if (section.segment) |sectionSegment| {
if (sectionSegment.elfOffset > newSegment.elfOffset) {
section.segment = newSegment;
}
} else {
section.segment = newSegment;
}
if (newSegment.firstSection == null) {
newSegment.firstSection = section;
}
}
}
try self.segments.append(newSegment);
}
}
sort.sort(*BinaryElfSegment, self.segments.items, {}, segmentSortCompare);
for (self.segments.items, 0..) |firstSegment, i| {
if (firstSegment.firstSection) |firstSection| {
const diff = firstSection.elfOffset - firstSegment.elfOffset;
firstSegment.elfOffset += diff;
firstSegment.fileSize += diff;
firstSegment.physicalAddress += diff;
const basePhysicalAddress = firstSegment.physicalAddress;
for (self.segments.items[i + 1 ..]) |segment| {
segment.binaryOffset = segment.physicalAddress - basePhysicalAddress;
}
break;
}
}
for (self.sections.items) |section| {
if (section.segment) |segment| {
section.binaryOffset = segment.binaryOffset + (section.elfOffset - segment.elfOffset);
}
}
sort.sort(*BinaryElfSection, self.sections.items, {}, sectionSortCompare);
return self;
}
fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.Elf64_Phdr) bool {
return segment.p_offset <= section.elfOffset and (segment.p_offset + segment.p_filesz) >= (section.elfOffset + section.fileSize);
}
fn sectionValidForOutput(shdr: anytype) bool {
return shdr.sh_size > 0 and shdr.sh_type != elf.SHT_NOBITS and
((shdr.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC);
}
fn segmentSortCompare(context: void, left: *BinaryElfSegment, right: *BinaryElfSegment) bool {
_ = context;
if (left.physicalAddress < right.physicalAddress) {
return true;
}
if (left.physicalAddress > right.physicalAddress) {
return false;
}
return false;
}
fn sectionSortCompare(context: void, left: *BinaryElfSection, right: *BinaryElfSection) bool {
_ = context;
return left.binaryOffset < right.binaryOffset;
}
};
fn writeBinaryElfSection(elf_file: File, out_file: File, section: *BinaryElfSection) !void {
try out_file.seekTo(section.binaryOffset);
try out_file.writeFileAll(elf_file, .{
.in_offset = section.elfOffset,
.in_len = section.fileSize,
});
}
const HexWriter = struct {
prev_addr: ?u32 = null,
out_file: File,
/// Max data bytes per line of output
const MAX_PAYLOAD_LEN: u8 = 16;
fn addressParts(address: u16) [2]u8 {
const msb = @as(u8, @truncate(address >> 8));
const lsb = @as(u8, @truncate(address));
return [2]u8{ msb, lsb };
}
const Record = struct {
const Type = enum(u8) {
Data = 0,
EOF = 1,
ExtendedSegmentAddress = 2,
ExtendedLinearAddress = 4,
};
address: u16,
payload: union(Type) {
Data: []const u8,
EOF: void,
ExtendedSegmentAddress: [2]u8,
ExtendedLinearAddress: [2]u8,
},
fn EOF() Record {
return Record{
.address = 0,
.payload = .EOF,
};
}
fn Data(address: u32, data: []const u8) Record {
return Record{
.address = @as(u16, @intCast(address % 0x10000)),
.payload = .{ .Data = data },
};
}
fn Address(address: u32) Record {
std.debug.assert(address > 0xFFFF);
const segment = @as(u16, @intCast(address / 0x10000));
if (address > 0xFFFFF) {
return Record{
.address = 0,
.payload = .{ .ExtendedLinearAddress = addressParts(segment) },
};
} else {
return Record{
.address = 0,
.payload = .{ .ExtendedSegmentAddress = addressParts(segment << 12) },
};
}
}
fn getPayloadBytes(self: Record) []const u8 {
return switch (self.payload) {
.Data => |d| d,
.EOF => @as([]const u8, &.{}),
.ExtendedSegmentAddress, .ExtendedLinearAddress => |*seg| seg,
};
}
fn checksum(self: Record) u8 {
const payload_bytes = self.getPayloadBytes();
var sum: u8 = @as(u8, @intCast(payload_bytes.len));
const parts = addressParts(self.address);
sum +%= parts[0];
sum +%= parts[1];
sum +%= @intFromEnum(self.payload);
for (payload_bytes) |byte| {
sum +%= byte;
}
return (sum ^ 0xFF) +% 1;
}
fn write(self: Record, file: File) File.WriteError!void {
const linesep = "\r\n";
// colon, (length, address, type, payload, checksum) as hex, CRLF
const BUFSIZE = 1 + (1 + 2 + 1 + MAX_PAYLOAD_LEN + 1) * 2 + linesep.len;
var outbuf: [BUFSIZE]u8 = undefined;
const payload_bytes = self.getPayloadBytes();
std.debug.assert(payload_bytes.len <= MAX_PAYLOAD_LEN);
const line = try std.fmt.bufPrint(&outbuf, ":{0X:0>2}{1X:0>4}{2X:0>2}{3s}{4X:0>2}" ++ linesep, .{
@as(u8, @intCast(payload_bytes.len)),
self.address,
@intFromEnum(self.payload),
std.fmt.fmtSliceHexUpper(payload_bytes),
self.checksum(),
});
try file.writeAll(line);
}
};
pub fn writeSegment(self: *HexWriter, segment: *const BinaryElfSegment, elf_file: File) !void {
var buf: [MAX_PAYLOAD_LEN]u8 = undefined;
var bytes_read: usize = 0;
while (bytes_read < segment.fileSize) {
const row_address = @as(u32, @intCast(segment.physicalAddress + bytes_read));
const remaining = segment.fileSize - bytes_read;
const to_read = @min(remaining, MAX_PAYLOAD_LEN);
const did_read = try elf_file.preadAll(buf[0..to_read], segment.elfOffset + bytes_read);
if (did_read < to_read) return error.UnexpectedEOF;
try self.writeDataRow(row_address, buf[0..did_read]);
bytes_read += did_read;
}
}
fn writeDataRow(self: *HexWriter, address: u32, data: []const u8) File.WriteError!void {
const record = Record.Data(address, data);
if (address > 0xFFFF and (self.prev_addr == null or record.address != self.prev_addr.?)) {
try Record.Address(address).write(self.out_file);
}
try record.write(self.out_file);
self.prev_addr = @as(u32, @intCast(record.address + data.len));
}
fn writeEOF(self: HexWriter) File.WriteError!void {
try Record.EOF().write(self.out_file);
}
};
fn containsValidAddressRange(segments: []*BinaryElfSegment) bool {
const max_address = std.math.maxInt(u32);
for (segments) |segment| {
if (segment.fileSize > max_address or
segment.physicalAddress > max_address - segment.fileSize) return false;
}
return true;
}
fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8, format: RawFormat) !void {
var elf_file = try fs.cwd().openFile(elf_path, .{});
defer elf_file.close();
var out_file = try fs.cwd().createFile(raw_path, .{});
defer out_file.close();
var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file);
defer binary_elf_output.deinit();
switch (format) {
.bin => {
for (binary_elf_output.sections.items) |section| {
try writeBinaryElfSection(elf_file, out_file, section);
}
},
.hex => {
if (binary_elf_output.segments.items.len == 0) return;
if (!containsValidAddressRange(binary_elf_output.segments.items)) {
return error.InvalidHexfileAddressRange;
}
var hex_writer = HexWriter{ .out_file = out_file };
for (binary_elf_output.sections.items) |section| {
if (section.segment) |segment| {
try hex_writer.writeSegment(segment, elf_file);
}
}
try hex_writer.writeEOF();
},
}
}
const InstallRawStep = @This();
pub const base_id = .install_raw;
pub const RawFormat = enum {
bin,
hex,
};
step: Step,
builder: *Builder,
artifact: *LibExeObjStep,
dest_dir: InstallDir,
dest_filename: []const u8,
format: RawFormat,
output_file: std.build.GeneratedFile,
fn detectFormat(filename: []const u8) RawFormat {
if (std.mem.endsWith(u8, filename, ".hex") or std.mem.endsWith(u8, filename, ".ihex")) {
return .hex;
}
return .bin;
}
pub fn create(builder: *Builder, artifact: *LibExeObjStep, dest_filename: []const u8, format: ?RawFormat) *InstallRawStep {
const self = builder.allocator.create(InstallRawStep) catch unreachable;
self.* = InstallRawStep{
.step = Step.init(.install_raw, builder.fmt("install raw binary {s}", .{artifact.step.name}), builder.allocator, make),
.builder = builder,
.artifact = artifact,
.dest_dir = switch (artifact.kind) {
.obj => unreachable,
.@"test" => unreachable,
.exe => .bin,
.lib => unreachable,
},
.dest_filename = dest_filename,
.format = format orelse detectFormat(dest_filename),
.output_file = std.build.GeneratedFile{ .step = &self.step },
};
self.step.dependOn(&artifact.step);
builder.pushInstalledFile(self.dest_dir, dest_filename);
return self;
}
pub fn getOutputSource(self: *const InstallRawStep) std.build.FileSource {
return std.build.FileSource{ .generated = &self.output_file };
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(InstallRawStep, "step", step);
const builder = self.builder;
if (self.artifact.target.getObjectFormat() != .elf) {
warn("InstallRawStep only works with ELF format.\n", .{});
return error.InvalidObjectFormat;
}
const full_src_path = self.artifact.getOutputSource().getPath(builder);
const full_dest_path = builder.getInstallPath(self.dest_dir, self.dest_filename);
fs.cwd().makePath(builder.getInstallPath(self.dest_dir, "")) catch unreachable;
try emitRaw(builder.allocator, full_src_path, full_dest_path, self.format);
self.output_file.path = full_dest_path;
}
test {
std.testing.refAllDecls(InstallRawStep);
}
test "Detect format from filename" {
try std.testing.expectEqual(RawFormat.hex, detectFormat("foo.hex"));
try std.testing.expectEqual(RawFormat.hex, detectFormat("foo.ihex"));
try std.testing.expectEqual(RawFormat.bin, detectFormat("foo.bin"));
try std.testing.expectEqual(RawFormat.bin, detectFormat("foo.bar"));
try std.testing.expectEqual(RawFormat.bin, detectFormat("a"));
}
test "containsValidAddressRange" {
var segment = BinaryElfSegment{
.physicalAddress = 0,
.virtualAddress = 0,
.elfOffset = 0,
.binaryOffset = 0,
.fileSize = 0,
.firstSection = null,
};
var buf: [1]*BinaryElfSegment = .{&segment};
// segment too big
segment.fileSize = std.math.maxInt(u32) + 1;
try std.testing.expect(!containsValidAddressRange(&buf));
// start address too big
segment.physicalAddress = std.math.maxInt(u32) + 1;
segment.fileSize = 2;
try std.testing.expect(!containsValidAddressRange(&buf));
// max address too big
segment.physicalAddress = std.math.maxInt(u32) - 1;
segment.fileSize = 2;
try std.testing.expect(!containsValidAddressRange(&buf));
// is ok
segment.physicalAddress = std.math.maxInt(u32) - 1;
segment.fileSize = 1;
try std.testing.expect(containsValidAddressRange(&buf));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/OptionsStep.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const build = std.build;
const fs = std.fs;
const Step = build.Step;
const Builder = build.Builder;
const GeneratedFile = build.GeneratedFile;
const LibExeObjStep = build.LibExeObjStep;
const FileSource = build.FileSource;
const OptionsStep = @This();
step: Step,
generated_file: GeneratedFile,
builder: *Builder,
contents: std.ArrayList(u8),
artifact_args: std.ArrayList(OptionArtifactArg),
file_source_args: std.ArrayList(OptionFileSourceArg),
pub fn create(builder: *Builder) *OptionsStep {
const self = builder.allocator.create(OptionsStep) catch unreachable;
self.* = .{
.builder = builder,
.step = Step.init(.options, "options", builder.allocator, make),
.generated_file = undefined,
.contents = std.ArrayList(u8).init(builder.allocator),
.artifact_args = std.ArrayList(OptionArtifactArg).init(builder.allocator),
.file_source_args = std.ArrayList(OptionFileSourceArg).init(builder.allocator),
};
self.generated_file = .{ .step = &self.step };
return self;
}
pub fn addOption(self: *OptionsStep, comptime T: type, name: []const u8, value: T) void {
const out = self.contents.writer();
switch (T) {
[]const []const u8 => {
out.print("pub const {}: []const []const u8 = &[_][]const u8{{\n", .{std.zig.fmtId(name)}) catch unreachable;
for (value) |slice| {
out.print(" \"{}\",\n", .{std.zig.fmtEscapes(slice)}) catch unreachable;
}
out.writeAll("};\n") catch unreachable;
return;
},
[:0]const u8 => {
out.print("pub const {}: [:0]const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
return;
},
[]const u8 => {
out.print("pub const {}: []const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
return;
},
?[:0]const u8 => {
out.print("pub const {}: ?[:0]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
if (value) |payload| {
out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
} else {
out.writeAll("null;\n") catch unreachable;
}
return;
},
?[]const u8 => {
out.print("pub const {}: ?[]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
if (value) |payload| {
out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
} else {
out.writeAll("null;\n") catch unreachable;
}
return;
},
std.builtin.Version => {
out.print(
\\pub const {}: @import("std").builtin.Version = .{{
\\ .major = {d},
\\ .minor = {d},
\\ .patch = {d},
\\}};
\\
, .{
std.zig.fmtId(name),
value.major,
value.minor,
value.patch,
}) catch unreachable;
},
std.SemanticVersion => {
out.print(
\\pub const {}: @import("std").SemanticVersion = .{{
\\ .major = {d},
\\ .minor = {d},
\\ .patch = {d},
\\
, .{
std.zig.fmtId(name),
value.major,
value.minor,
value.patch,
}) catch unreachable;
if (value.pre) |some| {
out.print(" .pre = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
}
if (value.build) |some| {
out.print(" .build = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
}
out.writeAll("};\n") catch unreachable;
return;
},
else => {},
}
switch (@typeInfo(T)) {
.Enum => |enum_info| {
out.print("pub const {} = enum {{\n", .{std.zig.fmtId(@typeName(T))}) catch unreachable;
inline for (enum_info.fields) |field| {
out.print(" {},\n", .{std.zig.fmtId(field.name)}) catch unreachable;
}
out.writeAll("};\n") catch unreachable;
},
else => {},
}
out.print("pub const {}: {s} = {};\n", .{ std.zig.fmtId(name), @typeName(T), value }) catch unreachable;
}
/// The value is the path in the cache dir.
/// Adds a dependency automatically.
pub fn addOptionFileSource(
self: *OptionsStep,
name: []const u8,
source: FileSource,
) void {
self.file_source_args.append(.{
.name = name,
.source = source.dupe(self.builder),
}) catch unreachable;
source.addStepDependencies(&self.step);
}
/// The value is the path in the cache dir.
/// Adds a dependency automatically.
pub fn addOptionArtifact(self: *OptionsStep, name: []const u8, artifact: *LibExeObjStep) void {
self.artifact_args.append(.{ .name = self.builder.dupe(name), .artifact = artifact }) catch unreachable;
self.step.dependOn(&artifact.step);
}
pub fn getPackage(self: OptionsStep, package_name: []const u8) build.Pkg {
return .{ .name = package_name, .path = self.getSource() };
}
pub fn getSource(self: OptionsStep) FileSource {
return .{ .generated = &self.generated_file };
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(OptionsStep, "step", step);
for (self.artifact_args.items) |item| {
self.addOption(
[]const u8,
item.name,
self.builder.pathFromRoot(item.artifact.getOutputSource().getPath(self.builder)),
);
}
for (self.file_source_args.items) |item| {
self.addOption(
[]const u8,
item.name,
item.source.getPath(self.builder),
);
}
const options_directory = self.builder.pathFromRoot(
try fs.path.join(
self.builder.allocator,
&[_][]const u8{ self.builder.cache_root, "options" },
),
);
try fs.cwd().makePath(options_directory);
const options_file = try fs.path.join(
self.builder.allocator,
&[_][]const u8{ options_directory, &self.hashContentsToFileName() },
);
try fs.cwd().writeFile(options_file, self.contents.items);
self.generated_file.path = options_file;
}
fn hashContentsToFileName(self: *OptionsStep) [64]u8 {
// This implementation is copied from `WriteFileStep.make`
var hash = std.crypto.hash.blake2.Blake2b384.init(.{});
// Random bytes to make OptionsStep unique. Refresh this with
// new random bytes when OptionsStep implementation is modified
// in a non-backwards-compatible way.
hash.update("yL0Ya4KkmcCjBlP8");
hash.update(self.contents.items);
var digest: [48]u8 = undefined;
hash.final(&digest);
var hash_basename: [64]u8 = undefined;
_ = fs.base64_encoder.encode(&hash_basename, &digest);
return hash_basename;
}
const OptionArtifactArg = struct {
name: []const u8,
artifact: *LibExeObjStep,
};
const OptionFileSourceArg = struct {
name: []const u8,
source: FileSource,
};
test "OptionsStep" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var builder = try Builder.create(
&arena.allocator,
"test",
"test",
"test",
"test",
);
defer builder.destroy();
const options = builder.addOptions();
options.addOption(usize, "option1", 1);
options.addOption(?usize, "option2", null);
options.addOption([]const u8, "string", "zigisthebest");
options.addOption(?[]const u8, "optional_string", null);
options.addOption(std.SemanticVersion, "semantic_version", try std.SemanticVersion.parse("0.1.2-foo+bar"));
try std.testing.expectEqualStrings(
\\pub const option1: usize = 1;
\\pub const option2: ?usize = null;
\\pub const string: []const u8 = "zigisthebest";
\\pub const optional_string: ?[]const u8 = null;
\\pub const semantic_version: @import("std").SemanticVersion = .{
\\ .major = 0,
\\ .minor = 1,
\\ .patch = 2,
\\ .pre = "foo",
\\ .build = "bar",
\\};
\\
, options.contents.items);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/CheckFileStep.zig | const std = @import("../std.zig");
const build = std.build;
const Step = build.Step;
const Builder = build.Builder;
const fs = std.fs;
const mem = std.mem;
const warn = std.debug.warn;
const CheckFileStep = @This();
pub const base_id = .check_file;
step: Step,
builder: *Builder,
expected_matches: []const []const u8,
source: build.FileSource,
max_bytes: usize = 20 * 1024 * 1024,
pub fn create(
builder: *Builder,
source: build.FileSource,
expected_matches: []const []const u8,
) *CheckFileStep {
const self = builder.allocator.create(CheckFileStep) catch unreachable;
self.* = CheckFileStep{
.builder = builder,
.step = Step.init(.check_file, "CheckFile", builder.allocator, make),
.source = source.dupe(builder),
.expected_matches = builder.dupeStrings(expected_matches),
};
self.source.addStepDependencies(&self.step);
return self;
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(CheckFileStep, "step", step);
const src_path = self.source.getPath(self.builder);
const contents = try fs.cwd().readFileAlloc(self.builder.allocator, src_path, self.max_bytes);
for (self.expected_matches) |expected_match| {
if (mem.indexOf(u8, contents, expected_match) == null) {
warn(
\\
\\========= Expected to find: ===================
\\{s}
\\========= But file does not contain it: =======
\\{s}
\\
, .{ expected_match, contents });
return error.TestFailed;
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/build/FmtStep.zig | const std = @import("../std.zig");
const build = @import("../build.zig");
const Step = build.Step;
const Builder = build.Builder;
const BufMap = std.BufMap;
const mem = std.mem;
const FmtStep = @This();
pub const base_id = .fmt;
step: Step,
builder: *Builder,
argv: [][]const u8,
pub fn create(builder: *Builder, paths: []const []const u8) *FmtStep {
const self = builder.allocator.create(FmtStep) catch unreachable;
const name = "zig fmt";
self.* = FmtStep{
.step = Step.init(.fmt, name, builder.allocator, make),
.builder = builder,
.argv = builder.allocator.alloc([]u8, paths.len + 2) catch unreachable,
};
self.argv[0] = builder.zig_exe;
self.argv[1] = "fmt";
for (paths, 0..) |path, i| {
self.argv[2 + i] = builder.pathFromRoot(path);
}
return self;
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(FmtStep, "step", step);
return self.builder.spawnChild(self.argv);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Gimli.zig | //! CSPRNG
const std = @import("std");
const Random = std.rand.Random;
const mem = std.mem;
const Gimli = @This();
state: std.crypto.core.Gimli,
pub const secret_seed_length = 32;
/// The seed must be uniform, secret and `secret_seed_length` bytes long.
pub fn init(secret_seed: [secret_seed_length]u8) Gimli {
var initial_state: [std.crypto.core.Gimli.BLOCKBYTES]u8 = undefined;
mem.copy(u8, initial_state[0..secret_seed_length], &secret_seed);
mem.set(u8, initial_state[secret_seed_length..], 0);
var self = Gimli{
.state = std.crypto.core.Gimli.init(initial_state),
};
return self;
}
pub fn random(self: *Gimli) Random {
return Random.init(self, fill);
}
pub fn fill(self: *Gimli, buf: []u8) void {
if (buf.len != 0) {
self.state.squeeze(buf);
} else {
self.state.permute();
}
mem.set(u8, self.state.toSlice()[0..std.crypto.core.Gimli.RATE], 0);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/ziggurat.zig | //! Implements ZIGNOR [1].
//!
//! [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to Generate Normal Random Samples*]
//! (https://www.doornik.com/research/ziggurat.pdf). Nuffield College, Oxford.
//!
//! rust/rand used as a reference;
//!
//! NOTE: This seems interesting but reference code is a bit hard to grok:
//! https://sbarral.github.io/etf.
const std = @import("../std.zig");
const builtin = @import("builtin");
const math = std.math;
const Random = std.rand.Random;
pub fn next_f64(random: Random, comptime tables: ZigTable) f64 {
while (true) {
// We manually construct a float from parts as we can avoid an extra random lookup here by
// using the unused exponent for the lookup table entry.
const bits = random.int(u64);
const i = @as(usize, @as(u8, @truncate(bits)));
const u = blk: {
if (tables.is_symmetric) {
// Generate a value in the range [2, 4) and scale into [-1, 1)
const repr = ((0x3ff + 1) << 52) | (bits >> 12);
break :blk @as(f64, @bitCast(repr)) - 3.0;
} else {
// Generate a value in the range [1, 2) and scale into (0, 1)
const repr = (0x3ff << 52) | (bits >> 12);
break :blk @as(f64, @bitCast(repr)) - (1.0 - math.f64_epsilon / 2.0);
}
};
const x = u * tables.x[i];
const test_x = if (tables.is_symmetric) math.fabs(x) else x;
// equivalent to |u| < tables.x[i+1] / tables.x[i] (or u < tables.x[i+1] / tables.x[i])
if (test_x < tables.x[i + 1]) {
return x;
}
if (i == 0) {
return tables.zero_case(random, u);
}
// equivalent to f1 + DRanU() * (f0 - f1) < 1
if (tables.f[i + 1] + (tables.f[i] - tables.f[i + 1]) * random.float(f64) < tables.pdf(x)) {
return x;
}
}
}
pub const ZigTable = struct {
r: f64,
x: [257]f64,
f: [257]f64,
// probability density function used as a fallback
pdf: fn (f64) f64,
// whether the distribution is symmetric
is_symmetric: bool,
// fallback calculation in the case we are in the 0 block
zero_case: fn (Random, f64) f64,
};
// zigNorInit
fn ZigTableGen(
comptime is_symmetric: bool,
comptime r: f64,
comptime v: f64,
comptime f: fn (f64) f64,
comptime f_inv: fn (f64) f64,
comptime zero_case: fn (Random, f64) f64,
) ZigTable {
var tables: ZigTable = undefined;
tables.is_symmetric = is_symmetric;
tables.r = r;
tables.pdf = f;
tables.zero_case = zero_case;
tables.x[0] = v / f(r);
tables.x[1] = r;
for (tables.x[2..256], 0..) |*entry, i| {
const last = tables.x[2 + i - 1];
entry.* = f_inv(v / last + f(last));
}
tables.x[256] = 0;
for (tables.f[0..], 0..) |*entry, i| {
entry.* = f(tables.x[i]);
}
return tables;
}
// N(0, 1)
pub const NormDist = blk: {
@setEvalBranchQuota(30000);
break :blk ZigTableGen(true, norm_r, norm_v, norm_f, norm_f_inv, norm_zero_case);
};
const norm_r = 3.6541528853610088;
const norm_v = 0.00492867323399;
fn norm_f(x: f64) f64 {
return math.exp(-x * x / 2.0);
}
fn norm_f_inv(y: f64) f64 {
return math.sqrt(-2.0 * math.ln(y));
}
fn norm_zero_case(random: Random, u: f64) f64 {
var x: f64 = 1;
var y: f64 = 0;
while (-2.0 * y < x * x) {
x = math.ln(random.float(f64)) / norm_r;
y = math.ln(random.float(f64));
}
if (u < 0) {
return x - norm_r;
} else {
return norm_r - x;
}
}
const please_windows_dont_oom = builtin.os.tag == .windows;
test "normal dist sanity" {
if (please_windows_dont_oom) return error.SkipZigTest;
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var i: usize = 0;
while (i < 1000) : (i += 1) {
_ = random.floatNorm(f64);
}
}
// Exp(1)
pub const ExpDist = blk: {
@setEvalBranchQuota(30000);
break :blk ZigTableGen(false, exp_r, exp_v, exp_f, exp_f_inv, exp_zero_case);
};
const exp_r = 7.69711747013104972;
const exp_v = 0.0039496598225815571993;
fn exp_f(x: f64) f64 {
return math.exp(-x);
}
fn exp_f_inv(y: f64) f64 {
return -math.ln(y);
}
fn exp_zero_case(random: Random, _: f64) f64 {
return exp_r - math.ln(random.float(f64));
}
test "exp dist sanity" {
if (please_windows_dont_oom) return error.SkipZigTest;
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var i: usize = 0;
while (i < 1000) : (i += 1) {
_ = random.floatExp(f64);
}
}
test "table gen" {
if (please_windows_dont_oom) return error.SkipZigTest;
_ = NormDist;
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Xoshiro256.zig | //! Xoshiro256++ - http://xoroshiro.di.unimi.it/
//!
//! PRNG
const std = @import("std");
const Random = std.rand.Random;
const math = std.math;
const Xoshiro256 = @This();
s: [4]u64,
pub fn init(init_s: u64) Xoshiro256 {
var x = Xoshiro256{
.s = undefined,
};
x.seed(init_s);
return x;
}
pub fn random(self: *Xoshiro256) Random {
return Random.init(self, fill);
}
fn next(self: *Xoshiro256) u64 {
const r = math.rotl(u64, self.s[0] +% self.s[3], 23) +% self.s[0];
const t = self.s[1] << 17;
self.s[2] ^= self.s[0];
self.s[3] ^= self.s[1];
self.s[1] ^= self.s[2];
self.s[0] ^= self.s[3];
self.s[2] ^= t;
self.s[3] = math.rotl(u64, self.s[3], 45);
return r;
}
// Skip 2^128 places ahead in the sequence
fn jump(self: *Xoshiro256) void {
var s: u256 = 0;
var table: u256 = 0x39abdc4529b1661ca9582618e03fc9aad5a61266f0c9392c180ec6d33cfd0aba;
while (table != 0) : (table >>= 1) {
if (@as(u1, @truncate(table)) != 0) {
s ^= @as(u256, @bitCast(self.s));
}
_ = self.next();
}
self.s = @as([4]u64, @bitCast(s));
}
pub fn seed(self: *Xoshiro256, init_s: u64) void {
// Xoshiro requires 256-bits of seed.
var gen = std.rand.SplitMix64.init(init_s);
self.s[0] = gen.next();
self.s[1] = gen.next();
self.s[2] = gen.next();
self.s[3] = gen.next();
}
pub fn fill(self: *Xoshiro256, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
test "xoroshiro sequence" {
var r = Xoshiro256.init(0);
const seq1 = [_]u64{
0x53175d61490b23df,
0x61da6f3dc380d507,
0x5c0fdf91ec9a7bfc,
0x02eebf8c3bbe5e1a,
0x7eca04ebaf4a5eea,
0x0543c37757f08d9a,
};
for (seq1) |s| {
try std.testing.expect(s == r.next());
}
r.jump();
const seq2 = [_]u64{
0xae1db5c5e27807be,
0xb584c6a7fd8709fe,
0xc46a0ee9330fb6e,
0xdc0c9606f49ed76e,
0x1f5bb6540f6651fb,
0x72fa2ca734601488,
};
for (seq2) |s| {
try std.testing.expect(s == r.next());
}
}
test "xoroshiro fill" {
var r = Xoshiro256.init(0);
const seq = [_]u64{
0x53175d61490b23df,
0x61da6f3dc380d507,
0x5c0fdf91ec9a7bfc,
0x02eebf8c3bbe5e1a,
0x7eca04ebaf4a5eea,
0x0543c37757f08d9a,
};
for (seq) |s| {
var buf0: [8]u8 = undefined;
var buf1: [7]u8 = undefined;
std.mem.writeIntLittle(u64, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Sfc64.zig | //! Sfc64 pseudo-random number generator from Practically Random.
//! Fastest engine of pracrand and smallest footprint.
//! See http://pracrand.sourceforge.net/
const std = @import("std");
const Random = std.rand.Random;
const math = std.math;
const Sfc64 = @This();
a: u64 = undefined,
b: u64 = undefined,
c: u64 = undefined,
counter: u64 = undefined,
const Rotation = 24;
const RightShift = 11;
const LeftShift = 3;
pub fn init(init_s: u64) Sfc64 {
var x = Sfc64{};
x.seed(init_s);
return x;
}
pub fn random(self: *Sfc64) Random {
return Random.init(self, fill);
}
fn next(self: *Sfc64) u64 {
const tmp = self.a +% self.b +% self.counter;
self.counter += 1;
self.a = self.b ^ (self.b >> RightShift);
self.b = self.c +% (self.c << LeftShift);
self.c = math.rotl(u64, self.c, Rotation) +% tmp;
return tmp;
}
fn seed(self: *Sfc64, init_s: u64) void {
self.a = init_s;
self.b = init_s;
self.c = init_s;
self.counter = 1;
var i: u32 = 0;
while (i < 12) : (i += 1) {
_ = self.next();
}
}
pub fn fill(self: *Sfc64, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
test "Sfc64 sequence" {
// Unfortunately there does not seem to be an official test sequence.
var r = Sfc64.init(0);
const seq = [_]u64{
0x3acfa029e3cc6041,
0xf5b6515bf2ee419c,
0x1259635894a29b61,
0xb6ae75395f8ebd6,
0x225622285ce302e2,
0x520d28611395cb21,
0xdb909c818901599d,
0x8ffd195365216f57,
0xe8c4ad5e258ac04a,
0x8f8ef2c89fdb63ca,
0xf9865b01d98d8e2f,
0x46555871a65d08ba,
0x66868677c6298fcd,
0x2ce15a7e6329f57d,
0xb2f1833ca91ca79,
0x4b0890ac9bf453ca,
};
for (seq) |s| {
try std.testing.expectEqual(s, r.next());
}
}
test "Sfc64 fill" {
// Unfortunately there does not seem to be an official test sequence.
var r = Sfc64.init(0);
const seq = [_]u64{
0x3acfa029e3cc6041,
0xf5b6515bf2ee419c,
0x1259635894a29b61,
0xb6ae75395f8ebd6,
0x225622285ce302e2,
0x520d28611395cb21,
0xdb909c818901599d,
0x8ffd195365216f57,
0xe8c4ad5e258ac04a,
0x8f8ef2c89fdb63ca,
0xf9865b01d98d8e2f,
0x46555871a65d08ba,
0x66868677c6298fcd,
0x2ce15a7e6329f57d,
0xb2f1833ca91ca79,
0x4b0890ac9bf453ca,
};
for (seq) |s| {
var buf0: [8]u8 = undefined;
var buf1: [7]u8 = undefined;
std.mem.writeIntLittle(u64, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Isaac64.zig | //! ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html
//!
//! Follows the general idea of the implementation from here with a few shortcuts.
//! https://doc.rust-lang.org/rand/src/rand/prng/isaac64.rs.html
const std = @import("std");
const Random = std.rand.Random;
const mem = std.mem;
const Isaac64 = @This();
r: [256]u64,
m: [256]u64,
a: u64,
b: u64,
c: u64,
i: usize,
pub fn init(init_s: u64) Isaac64 {
var isaac = Isaac64{
.r = undefined,
.m = undefined,
.a = undefined,
.b = undefined,
.c = undefined,
.i = undefined,
};
// seed == 0 => same result as the unseeded reference implementation
isaac.seed(init_s, 1);
return isaac;
}
pub fn random(self: *Isaac64) Random {
return Random.init(self, fill);
}
fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void {
const x = self.m[base + m1];
self.a = mix +% self.m[base + m2];
const y = self.a +% self.b +% self.m[@as(usize, @intCast((x >> 3) % self.m.len))];
self.m[base + m1] = y;
self.b = x +% self.m[@as(usize, @intCast((y >> 11) % self.m.len))];
self.r[self.r.len - 1 - base - m1] = self.b;
}
fn refill(self: *Isaac64) void {
const midpoint = self.r.len / 2;
self.c +%= 1;
self.b +%= self.c;
{
var i: usize = 0;
while (i < midpoint) : (i += 4) {
self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint);
self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint);
self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint);
self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint);
}
}
{
var i: usize = 0;
while (i < midpoint) : (i += 4) {
self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0);
self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0);
self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0);
self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0);
}
}
self.i = 0;
}
fn next(self: *Isaac64) u64 {
if (self.i >= self.r.len) {
self.refill();
}
const value = self.r[self.i];
self.i += 1;
return value;
}
fn seed(self: *Isaac64, init_s: u64, comptime rounds: usize) void {
// We ignore the multi-pass requirement since we don't currently expose full access to
// seeding the self.m array completely.
mem.set(u64, self.m[0..], 0);
self.m[0] = init_s;
// prescrambled golden ratio constants
var a = [_]u64{
0x647c4677a2884b7c,
0xb9f8b322c73ac862,
0x8c0ea5053d4712a0,
0xb29b2e824a595524,
0x82f053db8355e0ce,
0x48fe4a0fa5a09315,
0xae985bf2cbfc89ed,
0x98f5704f6c44c0ab,
};
comptime var i: usize = 0;
inline while (i < rounds) : (i += 1) {
var j: usize = 0;
while (j < self.m.len) : (j += 8) {
comptime var x1: usize = 0;
inline while (x1 < 8) : (x1 += 1) {
a[x1] +%= self.m[j + x1];
}
a[0] -%= a[4];
a[5] ^= a[7] >> 9;
a[7] +%= a[0];
a[1] -%= a[5];
a[6] ^= a[0] << 9;
a[0] +%= a[1];
a[2] -%= a[6];
a[7] ^= a[1] >> 23;
a[1] +%= a[2];
a[3] -%= a[7];
a[0] ^= a[2] << 15;
a[2] +%= a[3];
a[4] -%= a[0];
a[1] ^= a[3] >> 14;
a[3] +%= a[4];
a[5] -%= a[1];
a[2] ^= a[4] << 20;
a[4] +%= a[5];
a[6] -%= a[2];
a[3] ^= a[5] >> 17;
a[5] +%= a[6];
a[7] -%= a[3];
a[4] ^= a[6] << 14;
a[6] +%= a[7];
comptime var x2: usize = 0;
inline while (x2 < 8) : (x2 += 1) {
self.m[j + x2] = a[x2];
}
}
}
mem.set(u64, self.r[0..], 0);
self.a = 0;
self.b = 0;
self.c = 0;
self.i = self.r.len; // trigger refill on first value
}
pub fn fill(self: *Isaac64, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Fill complete 64-byte segments
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Fill trailing, ignoring excess (cut the stream).
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
test "isaac64 sequence" {
var r = Isaac64.init(0);
// from reference implementation
const seq = [_]u64{
0xf67dfba498e4937c,
0x84a5066a9204f380,
0xfee34bd5f5514dbb,
0x4d1664739b8f80d6,
0x8607459ab52a14aa,
0x0e78bc5a98529e49,
0xfe5332822ad13777,
0x556c27525e33d01a,
0x08643ca615f3149f,
0xd0771faf3cb04714,
0x30e86f68a37b008d,
0x3074ebc0488a3adf,
0x270645ea7a2790bc,
0x5601a0a8d3763c6a,
0x2f83071f53f325dd,
0xb9090f3d42d2d2ea,
};
for (seq) |s| {
try std.testing.expect(s == r.next());
}
}
test "isaac64 fill" {
var r = Isaac64.init(0);
// from reference implementation
const seq = [_]u64{
0xf67dfba498e4937c,
0x84a5066a9204f380,
0xfee34bd5f5514dbb,
0x4d1664739b8f80d6,
0x8607459ab52a14aa,
0x0e78bc5a98529e49,
0xfe5332822ad13777,
0x556c27525e33d01a,
0x08643ca615f3149f,
0xd0771faf3cb04714,
0x30e86f68a37b008d,
0x3074ebc0488a3adf,
0x270645ea7a2790bc,
0x5601a0a8d3763c6a,
0x2f83071f53f325dd,
0xb9090f3d42d2d2ea,
};
for (seq) |s| {
var buf0: [8]u8 = undefined;
var buf1: [7]u8 = undefined;
std.mem.writeIntLittle(u64, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Xoroshiro128.zig | //! Xoroshiro128+ - http://xoroshiro.di.unimi.it/
//!
//! PRNG
const std = @import("std");
const Random = std.rand.Random;
const math = std.math;
const Xoroshiro128 = @This();
s: [2]u64,
pub fn init(init_s: u64) Xoroshiro128 {
var x = Xoroshiro128{ .s = undefined };
x.seed(init_s);
return x;
}
pub fn random(self: *Xoroshiro128) Random {
return Random.init(self, fill);
}
fn next(self: *Xoroshiro128) u64 {
const s0 = self.s[0];
var s1 = self.s[1];
const r = s0 +% s1;
s1 ^= s0;
self.s[0] = math.rotl(u64, s0, @as(u8, 55)) ^ s1 ^ (s1 << 14);
self.s[1] = math.rotl(u64, s1, @as(u8, 36));
return r;
}
// Skip 2^64 places ahead in the sequence
fn jump(self: *Xoroshiro128) void {
var s0: u64 = 0;
var s1: u64 = 0;
const table = [_]u64{
0xbeac0467eba5facb,
0xd86b048b86aa9922,
};
inline for (table) |entry| {
var b: usize = 0;
while (b < 64) : (b += 1) {
if ((entry & (@as(u64, 1) << @as(u6, @intCast(b)))) != 0) {
s0 ^= self.s[0];
s1 ^= self.s[1];
}
_ = self.next();
}
}
self.s[0] = s0;
self.s[1] = s1;
}
pub fn seed(self: *Xoroshiro128, init_s: u64) void {
// Xoroshiro requires 128-bits of seed.
var gen = std.rand.SplitMix64.init(init_s);
self.s[0] = gen.next();
self.s[1] = gen.next();
}
pub fn fill(self: *Xoroshiro128, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
test "xoroshiro sequence" {
var r = Xoroshiro128.init(0);
r.s[0] = 0xaeecf86f7878dd75;
r.s[1] = 0x01cd153642e72622;
const seq1 = [_]u64{
0xb0ba0da5bb600397,
0x18a08afde614dccc,
0xa2635b956a31b929,
0xabe633c971efa045,
0x9ac19f9706ca3cac,
0xf62b426578c1e3fb,
};
for (seq1) |s| {
try std.testing.expect(s == r.next());
}
r.jump();
const seq2 = [_]u64{
0x95344a13556d3e22,
0xb4fb32dafa4d00df,
0xb2011d9ccdcfe2dd,
0x05679a9b2119b908,
0xa860a1da7c9cd8a0,
0x658a96efe3f86550,
};
for (seq2) |s| {
try std.testing.expect(s == r.next());
}
}
test "xoroshiro fill" {
var r = Xoroshiro128.init(0);
r.s[0] = 0xaeecf86f7878dd75;
r.s[1] = 0x01cd153642e72622;
const seq = [_]u64{
0xb0ba0da5bb600397,
0x18a08afde614dccc,
0xa2635b956a31b929,
0xabe633c971efa045,
0x9ac19f9706ca3cac,
0xf62b426578c1e3fb,
};
for (seq) |s| {
var buf0: [8]u8 = undefined;
var buf1: [7]u8 = undefined;
std.mem.writeIntLittle(u64, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/rand/Pcg.zig | //! PCG32 - http://www.pcg-random.org/
//!
//! PRNG
const std = @import("std");
const Random = std.rand.Random;
const Pcg = @This();
const default_multiplier = 6364136223846793005;
s: u64,
i: u64,
pub fn init(init_s: u64) Pcg {
var pcg = Pcg{
.s = undefined,
.i = undefined,
};
pcg.seed(init_s);
return pcg;
}
pub fn random(self: *Pcg) Random {
return Random.init(self, fill);
}
fn next(self: *Pcg) u32 {
const l = self.s;
self.s = l *% default_multiplier +% (self.i | 1);
const xor_s = @as(u32, @truncate(((l >> 18) ^ l) >> 27));
const rot = @as(u32, @intCast(l >> 59));
return (xor_s >> @as(u5, @intCast(rot))) | (xor_s << @as(u5, @intCast((0 -% rot) & 31)));
}
fn seed(self: *Pcg, init_s: u64) void {
// Pcg requires 128-bits of seed.
var gen = std.rand.SplitMix64.init(init_s);
self.seedTwo(gen.next(), gen.next());
}
fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void {
self.s = 0;
self.i = (init_s << 1) | 1;
self.s = self.s *% default_multiplier +% self.i;
self.s +%= init_i;
self.s = self.s *% default_multiplier +% self.i;
}
pub fn fill(self: *Pcg, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 4 byte segments.
while (i < aligned_len) : (i += 4) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 4) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
test "pcg sequence" {
var r = Pcg.init(0);
const s0: u64 = 0x9394bf54ce5d79de;
const s1: u64 = 0x84e9c579ef59bbf7;
r.seedTwo(s0, s1);
const seq = [_]u32{
2881561918,
3063928540,
1199791034,
2487695858,
1479648952,
3247963454,
};
for (seq) |s| {
try std.testing.expect(s == r.next());
}
}
test "pcg fill" {
var r = Pcg.init(0);
const s0: u64 = 0x9394bf54ce5d79de;
const s1: u64 = 0x84e9c579ef59bbf7;
r.seedTwo(s0, s1);
const seq = [_]u32{
2881561918,
3063928540,
1199791034,
2487695858,
1479648952,
3247963454,
};
for (seq) |s| {
var buf0: [4]u8 = undefined;
var buf1: [3]u8 = undefined;
std.mem.writeIntLittle(u32, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..3], buf1[0..]));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/unicode/throughput_test.zig | const std = @import("std");
const time = std.time;
const unicode = std.unicode;
const Timer = time.Timer;
const N = 1_000_000;
const KiB = 1024;
const MiB = 1024 * KiB;
const GiB = 1024 * MiB;
const ResultCount = struct {
count: usize,
throughput: u64,
};
fn benchmarkCodepointCount(buf: []const u8) !ResultCount {
var timer = try Timer.start();
const bytes = N * buf.len;
const start = timer.lap();
var i: usize = 0;
var r: usize = undefined;
while (i < N) : (i += 1) {
r = try @call(
.{ .modifier = .never_inline },
std.unicode.utf8CountCodepoints,
.{buf},
);
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(@as(f64, @floatFromInt(bytes)) / elapsed_s));
return ResultCount{ .count = r, .throughput = throughput };
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("short ASCII strings\n", .{});
{
const result = try benchmarkCodepointCount("abc");
try stdout.print(" count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
}
try stdout.print("short Unicode strings\n", .{});
{
const result = try benchmarkCodepointCount("ŌŌŌ");
try stdout.print(" count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
}
try stdout.print("pure ASCII strings\n", .{});
{
const result = try benchmarkCodepointCount("hello" ** 16);
try stdout.print(" count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
}
try stdout.print("pure Unicode strings\n", .{});
{
const result = try benchmarkCodepointCount("こんにちは" ** 16);
try stdout.print(" count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
}
try stdout.print("mixed ASCII/Unicode strings\n", .{});
{
const result = try benchmarkCodepointCount("Hyvää huomenta" ** 16);
try stdout.print(" count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/benchmark.zig | // zig run -O ReleaseFast --zig-lib-dir ../.. benchmark.zig
const std = @import("std");
const builtin = @import("builtin");
const time = std.time;
const Timer = time.Timer;
const hash = std.hash;
const KiB = 1024;
const MiB = 1024 * KiB;
const GiB = 1024 * MiB;
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
const Hash = struct {
ty: type,
name: []const u8,
has_iterative_api: bool = true,
init_u8s: ?[]const u8 = null,
init_u64: ?u64 = null,
};
const hashes = [_]Hash{
Hash{
.ty = hash.Wyhash,
.name = "wyhash",
.init_u64 = 0,
},
Hash{
.ty = hash.Fnv1a_64,
.name = "fnv1a",
},
Hash{
.ty = hash.Adler32,
.name = "adler32",
},
Hash{
.ty = hash.crc.Crc32WithPoly(.IEEE),
.name = "crc32-slicing-by-8",
},
Hash{
.ty = hash.crc.Crc32SmallWithPoly(.IEEE),
.name = "crc32-half-byte-lookup",
},
Hash{
.ty = hash.CityHash32,
.name = "cityhash-32",
.has_iterative_api = false,
},
Hash{
.ty = hash.CityHash64,
.name = "cityhash-64",
.has_iterative_api = false,
},
Hash{
.ty = hash.Murmur2_32,
.name = "murmur2-32",
.has_iterative_api = false,
},
Hash{
.ty = hash.Murmur2_64,
.name = "murmur2-64",
.has_iterative_api = false,
},
Hash{
.ty = hash.Murmur3_32,
.name = "murmur3-32",
.has_iterative_api = false,
},
};
const Result = struct {
hash: u64,
throughput: u64,
};
const block_size: usize = 8 * 8192;
pub fn benchmarkHash(comptime H: anytype, bytes: usize) !Result {
var h = blk: {
if (H.init_u8s) |init| {
break :blk H.ty.init(init);
}
if (H.init_u64) |init| {
break :blk H.ty.init(init);
}
break :blk H.ty.init();
};
var block: [block_size]u8 = undefined;
random.bytes(block[0..]);
var offset: usize = 0;
var timer = try Timer.start();
const start = timer.lap();
while (offset < bytes) : (offset += block.len) {
h.update(block[0..]);
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(@as(f64, @floatFromInt(bytes)) / elapsed_s));
return Result{
.hash = h.final(),
.throughput = throughput,
};
}
pub fn benchmarkHashSmallKeys(comptime H: anytype, key_size: usize, bytes: usize) !Result {
const key_count = bytes / key_size;
var block: [block_size]u8 = undefined;
random.bytes(block[0..]);
var i: usize = 0;
var timer = try Timer.start();
const start = timer.lap();
var sum: u64 = 0;
while (i < key_count) : (i += 1) {
const small_key = block[0..key_size];
sum +%= blk: {
if (H.init_u8s) |init| {
break :blk H.ty.hash(init, small_key);
}
if (H.init_u64) |init| {
break :blk H.ty.hash(init, small_key);
}
break :blk H.ty.hash(small_key);
};
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(@as(f64, @floatFromInt(bytes)) / elapsed_s));
return Result{
.hash = sum,
.throughput = throughput,
};
}
fn usage() void {
std.debug.warn(
\\throughput_test [options]
\\
\\Options:
\\ --filter [test-name]
\\ --seed [int]
\\ --count [int]
\\ --key-size [int]
\\ --iterative-only
\\ --help
\\
, .{});
}
fn mode(comptime x: comptime_int) comptime_int {
return if (builtin.mode == .Debug) x / 64 else x;
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
const args = try std.process.argsAlloc(&fixed.allocator);
var filter: ?[]u8 = "";
var count: usize = mode(128 * MiB);
var key_size: usize = 32;
var seed: u32 = 0;
var test_iterative_only = false;
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--mode")) {
try stdout.print("{}\n", .{builtin.mode});
return;
} else if (std.mem.eql(u8, args[i], "--seed")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
seed = try std.fmt.parseUnsigned(u32, args[i], 10);
// we seed later
} else if (std.mem.eql(u8, args[i], "--filter")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
filter = args[i];
} else if (std.mem.eql(u8, args[i], "--count")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
const c = try std.fmt.parseUnsigned(usize, args[i], 10);
count = c * MiB;
} else if (std.mem.eql(u8, args[i], "--key-size")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
key_size = try std.fmt.parseUnsigned(usize, args[i], 10);
if (key_size > block_size) {
try stdout.print("key_size cannot exceed block size of {}\n", .{block_size});
std.os.exit(1);
}
} else if (std.mem.eql(u8, args[i], "--iterative-only")) {
test_iterative_only = true;
} else if (std.mem.eql(u8, args[i], "--help")) {
usage();
return;
} else {
usage();
std.os.exit(1);
}
}
inline for (hashes) |H| {
if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) {
if (!test_iterative_only or H.has_iterative_api) {
try stdout.print("{}\n", .{H.name});
// Always reseed prior to every call so we are hashing the same buffer contents.
// This allows easier comparison between different implementations.
if (H.has_iterative_api) {
prng.seed(seed);
const result = try benchmarkHash(H, count);
try stdout.print(" iterative: {:5} MiB/s [{x:0<16}]\n", .{ result.throughput / (1 * MiB), result.hash });
}
if (!test_iterative_only) {
prng.seed(seed);
const result_small = try benchmarkHashSmallKeys(H, key_size, count);
try stdout.print(" small keys: {:5} MiB/s [{x:0<16}]\n", .{ result_small.throughput / (1 * MiB), result_small.hash });
}
}
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/auto_hash.zig | const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const meta = std.meta;
/// Describes how pointer types should be hashed.
pub const HashStrategy = enum {
/// Do not follow pointers, only hash their value.
Shallow,
/// Follow pointers, hash the pointee content.
/// Only dereferences one level, ie. it is changed into .Shallow when a
/// pointer type is encountered.
Deep,
/// Follow pointers, hash the pointee content.
/// Dereferences all pointers encountered.
/// Assumes no cycle.
DeepRecursive,
};
/// Helper function to hash a pointer and mutate the strategy if needed.
pub fn hashPointer(hasher: anytype, key: anytype, comptime strat: HashStrategy) void {
const info = @typeInfo(@TypeOf(key));
switch (info.Pointer.size) {
.One => switch (strat) {
.Shallow => hash(hasher, @intFromPtr(key), .Shallow),
.Deep => hash(hasher, key.*, .Shallow),
.DeepRecursive => hash(hasher, key.*, .DeepRecursive),
},
.Slice => switch (strat) {
.Shallow => {
hashPointer(hasher, key.ptr, .Shallow);
hash(hasher, key.len, .Shallow);
},
.Deep => hashArray(hasher, key, .Shallow),
.DeepRecursive => hashArray(hasher, key, .DeepRecursive),
},
.Many,
.C,
=> switch (strat) {
.Shallow => hash(hasher, @intFromPtr(key), .Shallow),
else => @compileError(
\\ unknown-length pointers and C pointers cannot be hashed deeply.
\\ Consider providing your own hash function.
),
},
}
}
/// Helper function to hash a set of contiguous objects, from an array or slice.
pub fn hashArray(hasher: anytype, key: anytype, comptime strat: HashStrategy) void {
switch (strat) {
.Shallow => {
for (key) |element| {
hash(hasher, element, .Shallow);
}
},
else => {
for (key) |element| {
hash(hasher, element, strat);
}
},
}
}
/// Provides generic hashing for any eligible type.
/// Strategy is provided to determine if pointers should be followed or not.
pub fn hash(hasher: anytype, key: anytype, comptime strat: HashStrategy) void {
const Key = @TypeOf(key);
if (strat == .Shallow and comptime meta.trait.hasUniqueRepresentation(Key)) {
@call(.{ .modifier = .always_inline }, hasher.update, .{mem.asBytes(&key)});
return;
}
switch (@typeInfo(Key)) {
.NoReturn,
.Opaque,
.Undefined,
.Void,
.Null,
.ComptimeFloat,
.ComptimeInt,
.Type,
.EnumLiteral,
.Frame,
.Float,
=> @compileError("unable to hash type " ++ @typeName(Key)),
// Help the optimizer see that hashing an int is easy by inlining!
// TODO Check if the situation is better after #561 is resolved.
.Int => {
if (comptime meta.trait.hasUniqueRepresentation(Key)) {
@call(.{ .modifier = .always_inline }, hasher.update, .{std.mem.asBytes(&key)});
} else {
// Take only the part containing the key value, the remaining
// bytes are undefined and must not be hashed!
const byte_size = comptime std.math.divCeil(comptime_int, @bitSizeOf(Key), 8) catch unreachable;
@call(.{ .modifier = .always_inline }, hasher.update, .{std.mem.asBytes(&key)[0..byte_size]});
}
},
.Bool => hash(hasher, @intFromBool(key), strat),
.Enum => hash(hasher, @intFromEnum(key), strat),
.ErrorSet => hash(hasher, @intFromError(key), strat),
.AnyFrame, .BoundFn, .Fn => hash(hasher, @intFromPtr(key), strat),
.Pointer => @call(.{ .modifier = .always_inline }, hashPointer, .{ hasher, key, strat }),
.Optional => if (key) |k| hash(hasher, k, strat),
.Array => hashArray(hasher, key, strat),
.Vector => |info| {
if (comptime meta.trait.hasUniqueRepresentation(Key)) {
hasher.update(mem.asBytes(&key));
} else {
comptime var i = 0;
inline while (i < info.len) : (i += 1) {
hash(hasher, key[i], strat);
}
}
},
.Struct => |info| {
inline for (info.fields) |field| {
// We reuse the hash of the previous field as the seed for the
// next one so that they're dependant.
hash(hasher, @field(key, field.name), strat);
}
},
.Union => |info| {
if (info.tag_type) |tag_type| {
const tag = meta.activeTag(key);
hash(hasher, tag, strat);
inline for (info.fields) |field| {
if (@field(tag_type, field.name) == tag) {
if (field.field_type != void) {
hash(hasher, @field(key, field.name), strat);
}
// TODO use a labelled break when it does not crash the compiler. cf #2908
// break :blk;
return;
}
}
unreachable;
} else @compileError("cannot hash untagged union type: " ++ @typeName(Key) ++ ", provide your own hash function");
},
.ErrorUnion => blk: {
const payload = key catch |err| {
hash(hasher, err, strat);
break :blk;
};
hash(hasher, payload, strat);
},
}
}
fn typeContainsSlice(comptime K: type) bool {
comptime {
if (meta.trait.isSlice(K)) {
return true;
}
if (meta.trait.is(.Struct)(K)) {
inline for (@typeInfo(K).Struct.fields) |field| {
if (typeContainsSlice(field.field_type)) {
return true;
}
}
}
if (meta.trait.is(.Union)(K)) {
inline for (@typeInfo(K).Union.fields) |field| {
if (typeContainsSlice(field.field_type)) {
return true;
}
}
}
return false;
}
}
/// Provides generic hashing for any eligible type.
/// Only hashes `key` itself, pointers are not followed.
/// Slices as well as unions and structs containing slices are rejected to avoid
/// ambiguity on the user's intention.
pub fn autoHash(hasher: anytype, key: anytype) void {
const Key = @TypeOf(key);
if (comptime typeContainsSlice(Key)) {
@compileError("std.auto_hash.autoHash does not allow slices as well as unions and structs containing slices here (" ++ @typeName(Key) ++
") because the intent is unclear. Consider using std.auto_hash.hash or providing your own hash function instead.");
}
hash(hasher, key, .Shallow);
}
const testing = std.testing;
const Wyhash = std.hash.Wyhash;
fn testHash(key: anytype) u64 {
// Any hash could be used here, for testing autoHash.
var hasher = Wyhash.init(0);
hash(&hasher, key, .Shallow);
return hasher.final();
}
fn testHashShallow(key: anytype) u64 {
// Any hash could be used here, for testing autoHash.
var hasher = Wyhash.init(0);
hash(&hasher, key, .Shallow);
return hasher.final();
}
fn testHashDeep(key: anytype) u64 {
// Any hash could be used here, for testing autoHash.
var hasher = Wyhash.init(0);
hash(&hasher, key, .Deep);
return hasher.final();
}
fn testHashDeepRecursive(key: anytype) u64 {
// Any hash could be used here, for testing autoHash.
var hasher = Wyhash.init(0);
hash(&hasher, key, .DeepRecursive);
return hasher.final();
}
test "typeContainsSlice" {
comptime {
try testing.expect(!typeContainsSlice(meta.Tag(std.builtin.TypeInfo)));
try testing.expect(typeContainsSlice([]const u8));
try testing.expect(!typeContainsSlice(u8));
const A = struct { x: []const u8 };
const B = struct { a: A };
const C = struct { b: B };
const D = struct { x: u8 };
try testing.expect(typeContainsSlice(A));
try testing.expect(typeContainsSlice(B));
try testing.expect(typeContainsSlice(C));
try testing.expect(!typeContainsSlice(D));
}
}
test "hash pointer" {
const array = [_]u32{ 123, 123, 123 };
const a = &array[0];
const b = &array[1];
const c = &array[2];
const d = a;
try testing.expect(testHashShallow(a) == testHashShallow(d));
try testing.expect(testHashShallow(a) != testHashShallow(c));
try testing.expect(testHashShallow(a) != testHashShallow(b));
try testing.expect(testHashDeep(a) == testHashDeep(a));
try testing.expect(testHashDeep(a) == testHashDeep(c));
try testing.expect(testHashDeep(a) == testHashDeep(b));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(a));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(c));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(b));
}
test "hash slice shallow" {
// Allocate one array dynamically so that we're assured it is not merged
// with the other by the optimization passes.
const array1 = try std.testing.allocator.create([6]u32);
defer std.testing.allocator.destroy(array1);
array1.* = [_]u32{ 1, 2, 3, 4, 5, 6 };
const array2 = [_]u32{ 1, 2, 3, 4, 5, 6 };
// TODO audit deep/shallow - maybe it has the wrong behavior with respect to array pointers and slices
var runtime_zero: usize = 0;
const a = array1[runtime_zero..];
const b = array2[runtime_zero..];
const c = array1[runtime_zero..3];
try testing.expect(testHashShallow(a) == testHashShallow(a));
try testing.expect(testHashShallow(a) != testHashShallow(array1));
try testing.expect(testHashShallow(a) != testHashShallow(b));
try testing.expect(testHashShallow(a) != testHashShallow(c));
}
test "hash slice deep" {
// Allocate one array dynamically so that we're assured it is not merged
// with the other by the optimization passes.
const array1 = try std.testing.allocator.create([6]u32);
defer std.testing.allocator.destroy(array1);
array1.* = [_]u32{ 1, 2, 3, 4, 5, 6 };
const array2 = [_]u32{ 1, 2, 3, 4, 5, 6 };
const a = array1[0..];
const b = array2[0..];
const c = array1[0..3];
try testing.expect(testHashDeep(a) == testHashDeep(a));
try testing.expect(testHashDeep(a) == testHashDeep(array1));
try testing.expect(testHashDeep(a) == testHashDeep(b));
try testing.expect(testHashDeep(a) != testHashDeep(c));
}
test "hash struct deep" {
const Foo = struct {
a: u32,
b: u16,
c: *bool,
const Self = @This();
pub fn init(allocator: *mem.Allocator, a_: u32, b_: u16, c_: bool) !Self {
const ptr = try allocator.create(bool);
ptr.* = c_;
return Self{ .a = a_, .b = b_, .c = ptr };
}
};
const allocator = std.testing.allocator;
const foo = try Foo.init(allocator, 123, 10, true);
const bar = try Foo.init(allocator, 123, 10, true);
const baz = try Foo.init(allocator, 123, 10, false);
defer allocator.destroy(foo.c);
defer allocator.destroy(bar.c);
defer allocator.destroy(baz.c);
try testing.expect(testHashDeep(foo) == testHashDeep(bar));
try testing.expect(testHashDeep(foo) != testHashDeep(baz));
try testing.expect(testHashDeep(bar) != testHashDeep(baz));
var hasher = Wyhash.init(0);
const h = testHashDeep(foo);
autoHash(&hasher, foo.a);
autoHash(&hasher, foo.b);
autoHash(&hasher, foo.c.*);
try testing.expectEqual(h, hasher.final());
const h2 = testHashDeepRecursive(&foo);
try testing.expect(h2 != testHashDeep(&foo));
try testing.expect(h2 == testHashDeep(foo));
}
test "testHash optional" {
const a: ?u32 = 123;
const b: ?u32 = null;
try testing.expectEqual(testHash(a), testHash(@as(u32, 123)));
try testing.expect(testHash(a) != testHash(b));
try testing.expectEqual(testHash(b), 0);
}
test "testHash array" {
const a = [_]u32{ 1, 2, 3 };
const h = testHash(a);
var hasher = Wyhash.init(0);
autoHash(&hasher, @as(u32, 1));
autoHash(&hasher, @as(u32, 2));
autoHash(&hasher, @as(u32, 3));
try testing.expectEqual(h, hasher.final());
}
test "testHash struct" {
const Foo = struct {
a: u32 = 1,
b: u32 = 2,
c: u32 = 3,
};
const f = Foo{};
const h = testHash(f);
var hasher = Wyhash.init(0);
autoHash(&hasher, @as(u32, 1));
autoHash(&hasher, @as(u32, 2));
autoHash(&hasher, @as(u32, 3));
try testing.expectEqual(h, hasher.final());
}
test "testHash union" {
const Foo = union(enum) {
A: u32,
B: bool,
C: u32,
D: void,
};
const a = Foo{ .A = 18 };
var b = Foo{ .B = true };
const c = Foo{ .C = 18 };
const d: Foo = .D;
try testing.expect(testHash(a) == testHash(a));
try testing.expect(testHash(a) != testHash(b));
try testing.expect(testHash(a) != testHash(c));
try testing.expect(testHash(a) != testHash(d));
b = Foo{ .A = 18 };
try testing.expect(testHash(a) == testHash(b));
b = .D;
try testing.expect(testHash(d) == testHash(b));
}
test "testHash vector" {
const a: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 4 };
const b: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 5 };
try testing.expect(testHash(a) == testHash(a));
try testing.expect(testHash(a) != testHash(b));
const c: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 4 };
const d: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 5 };
try testing.expect(testHash(c) == testHash(c));
try testing.expect(testHash(c) != testHash(d));
}
test "testHash error union" {
const Errors = error{Test};
const Foo = struct {
a: u32 = 1,
b: u32 = 2,
c: u32 = 3,
};
const f = Foo{};
const g: Errors!Foo = Errors.Test;
try testing.expect(testHash(f) != testHash(g));
try testing.expect(testHash(f) == testHash(Foo{}));
try testing.expect(testHash(g) == testHash(Errors.Test));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/crc.zig | // There are two implementations of CRC32 implemented with the following key characteristics:
//
// - Crc32WithPoly uses 8Kb of tables but is ~10x faster than the small method.
//
// - Crc32SmallWithPoly uses only 64 bytes of memory but is slower. Be aware that this is
// still moderately fast just slow relative to the slicing approach.
const std = @import("../std.zig");
const builtin = @import("builtin");
const debug = std.debug;
const testing = std.testing;
pub const Polynomial = enum(u32) {
IEEE = 0xedb88320,
Castagnoli = 0x82f63b78,
Koopman = 0xeb31d82e,
_,
};
// IEEE is by far the most common CRC and so is aliased by default.
pub const Crc32 = Crc32WithPoly(.IEEE);
// slicing-by-8 crc32 implementation.
pub fn Crc32WithPoly(comptime poly: Polynomial) type {
return struct {
const Self = @This();
const lookup_tables = block: {
@setEvalBranchQuota(20000);
var tables: [8][256]u32 = undefined;
for (tables[0], 0..) |*e, i| {
var crc = @as(u32, @intCast(i));
var j: usize = 0;
while (j < 8) : (j += 1) {
if (crc & 1 == 1) {
crc = (crc >> 1) ^ @intFromEnum(poly);
} else {
crc = (crc >> 1);
}
}
e.* = crc;
}
var i: usize = 0;
while (i < 256) : (i += 1) {
var crc = tables[0][i];
var j: usize = 1;
while (j < 8) : (j += 1) {
const index = @as(u8, @truncate(crc));
crc = tables[0][index] ^ (crc >> 8);
tables[j][i] = crc;
}
}
break :block tables;
};
crc: u32,
pub fn init() Self {
return Self{ .crc = 0xffffffff };
}
pub fn update(self: *Self, input: []const u8) void {
var i: usize = 0;
while (i + 8 <= input.len) : (i += 8) {
const p = input[i .. i + 8];
// Unrolling this way gives ~50Mb/s increase
self.crc ^= std.mem.readIntLittle(u32, p[0..4]);
self.crc =
lookup_tables[0][p[7]] ^
lookup_tables[1][p[6]] ^
lookup_tables[2][p[5]] ^
lookup_tables[3][p[4]] ^
lookup_tables[4][@as(u8, @truncate(self.crc >> 24))] ^
lookup_tables[5][@as(u8, @truncate(self.crc >> 16))] ^
lookup_tables[6][@as(u8, @truncate(self.crc >> 8))] ^
lookup_tables[7][@as(u8, @truncate(self.crc >> 0))];
}
while (i < input.len) : (i += 1) {
const index = @as(u8, @truncate(self.crc)) ^ input[i];
self.crc = (self.crc >> 8) ^ lookup_tables[0][index];
}
}
pub fn final(self: *Self) u32 {
return ~self.crc;
}
pub fn hash(input: []const u8) u32 {
var c = Self.init();
c.update(input);
return c.final();
}
};
}
const please_windows_dont_oom = builtin.os.tag == .windows;
test "crc32 ieee" {
if (please_windows_dont_oom) return error.SkipZigTest;
const Crc32Ieee = Crc32WithPoly(.IEEE);
try testing.expect(Crc32Ieee.hash("") == 0x00000000);
try testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
try testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
}
test "crc32 castagnoli" {
if (please_windows_dont_oom) return error.SkipZigTest;
const Crc32Castagnoli = Crc32WithPoly(.Castagnoli);
try testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
try testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
try testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
}
// half-byte lookup table implementation.
pub fn Crc32SmallWithPoly(comptime poly: Polynomial) type {
return struct {
const Self = @This();
const lookup_table = block: {
var table: [16]u32 = undefined;
for (table, 0..) |*e, i| {
var crc = @as(u32, @intCast(i * 16));
var j: usize = 0;
while (j < 8) : (j += 1) {
if (crc & 1 == 1) {
crc = (crc >> 1) ^ @intFromEnum(poly);
} else {
crc = (crc >> 1);
}
}
e.* = crc;
}
break :block table;
};
crc: u32,
pub fn init() Self {
return Self{ .crc = 0xffffffff };
}
pub fn update(self: *Self, input: []const u8) void {
for (input) |b| {
self.crc = lookup_table[@as(u4, @truncate(self.crc ^ (b >> 0)))] ^ (self.crc >> 4);
self.crc = lookup_table[@as(u4, @truncate(self.crc ^ (b >> 4)))] ^ (self.crc >> 4);
}
}
pub fn final(self: *Self) u32 {
return ~self.crc;
}
pub fn hash(input: []const u8) u32 {
var c = Self.init();
c.update(input);
return c.final();
}
};
}
test "small crc32 ieee" {
if (please_windows_dont_oom) return error.SkipZigTest;
const Crc32Ieee = Crc32SmallWithPoly(.IEEE);
try testing.expect(Crc32Ieee.hash("") == 0x00000000);
try testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
try testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
}
test "small crc32 castagnoli" {
if (please_windows_dont_oom) return error.SkipZigTest;
const Crc32Castagnoli = Crc32SmallWithPoly(.Castagnoli);
try testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
try testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
try testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/fnv.zig | // FNV1a - Fowler-Noll-Vo hash function
//
// FNV1a is a fast, non-cryptographic hash function with fairly good distribution properties.
//
// https://tools.ietf.org/html/draft-eastlake-fnv-14
const std = @import("../std.zig");
const testing = std.testing;
pub const Fnv1a_32 = Fnv1a(u32, 0x01000193, 0x811c9dc5);
pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325);
pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d);
fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type {
return struct {
const Self = @This();
value: T,
pub fn init() Self {
return Self{ .value = offset };
}
pub fn update(self: *Self, input: []const u8) void {
for (input) |b| {
self.value ^= b;
self.value *%= prime;
}
}
pub fn final(self: *Self) T {
return self.value;
}
pub fn hash(input: []const u8) T {
var c = Self.init();
c.update(input);
return c.final();
}
};
}
test "fnv1a-32" {
try testing.expect(Fnv1a_32.hash("") == 0x811c9dc5);
try testing.expect(Fnv1a_32.hash("a") == 0xe40c292c);
try testing.expect(Fnv1a_32.hash("foobar") == 0xbf9cf968);
}
test "fnv1a-64" {
try testing.expect(Fnv1a_64.hash("") == 0xcbf29ce484222325);
try testing.expect(Fnv1a_64.hash("a") == 0xaf63dc4c8601ec8c);
try testing.expect(Fnv1a_64.hash("foobar") == 0x85944171f73967e8);
}
test "fnv1a-128" {
try testing.expect(Fnv1a_128.hash("") == 0x6c62272e07bb014262b821756295c58d);
try testing.expect(Fnv1a_128.hash("a") == 0xd228cb696f1a8caf78912b704e4a8964);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/murmur.zig | const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const native_endian = builtin.target.cpu.arch.endian();
const default_seed: u32 = 0xc70f6907;
pub const Murmur2_32 = struct {
const Self = @This();
pub fn hash(str: []const u8) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashWithSeed, .{ str, default_seed });
}
pub fn hashWithSeed(str: []const u8, seed: u32) u32 {
const m: u32 = 0x5bd1e995;
const len = @as(u32, @truncate(str.len));
var h1: u32 = seed ^ len;
for (@as([*]align(1) const u32, @ptrCast(str.ptr))[0..(len >> 2)]) |v| {
var k1: u32 = v;
if (native_endian == .Big)
k1 = @byteSwap(k1);
k1 *%= m;
k1 ^= k1 >> 24;
k1 *%= m;
h1 *%= m;
h1 ^= k1;
}
const offset = len & 0xfffffffc;
const rest = len & 3;
if (rest >= 3) {
h1 ^= @as(u32, @intCast(str[offset + 2])) << 16;
}
if (rest >= 2) {
h1 ^= @as(u32, @intCast(str[offset + 1])) << 8;
}
if (rest >= 1) {
h1 ^= @as(u32, @intCast(str[offset + 0]));
h1 *%= m;
}
h1 ^= h1 >> 13;
h1 *%= m;
h1 ^= h1 >> 15;
return h1;
}
pub fn hashUint32(v: u32) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashUint32WithSeed, .{ v, default_seed });
}
pub fn hashUint32WithSeed(v: u32, seed: u32) u32 {
const m: u32 = 0x5bd1e995;
const len: u32 = 4;
var h1: u32 = seed ^ len;
var k1: u32 = undefined;
k1 = v *% m;
k1 ^= k1 >> 24;
k1 *%= m;
h1 *%= m;
h1 ^= k1;
h1 ^= h1 >> 13;
h1 *%= m;
h1 ^= h1 >> 15;
return h1;
}
pub fn hashUint64(v: u64) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashUint64WithSeed, .{ v, default_seed });
}
pub fn hashUint64WithSeed(v: u64, seed: u32) u32 {
const m: u32 = 0x5bd1e995;
const len: u32 = 8;
var h1: u32 = seed ^ len;
var k1: u32 = undefined;
k1 = @as(u32, @truncate(v)) *% m;
k1 ^= k1 >> 24;
k1 *%= m;
h1 *%= m;
h1 ^= k1;
k1 = @as(u32, @truncate(v >> 32)) *% m;
k1 ^= k1 >> 24;
k1 *%= m;
h1 *%= m;
h1 ^= k1;
h1 ^= h1 >> 13;
h1 *%= m;
h1 ^= h1 >> 15;
return h1;
}
};
pub const Murmur2_64 = struct {
const Self = @This();
pub fn hash(str: []const u8) u64 {
return @call(.{ .modifier = .always_inline }, Self.hashWithSeed, .{ str, default_seed });
}
pub fn hashWithSeed(str: []const u8, seed: u64) u64 {
const m: u64 = 0xc6a4a7935bd1e995;
const len = @as(u64, str.len);
var h1: u64 = seed ^ (len *% m);
for (@as([*]align(1) const u64, @ptrCast(str.ptr))[0..@as(usize, @intCast(len >> 3))]) |v| {
var k1: u64 = v;
if (native_endian == .Big)
k1 = @byteSwap(k1);
k1 *%= m;
k1 ^= k1 >> 47;
k1 *%= m;
h1 ^= k1;
h1 *%= m;
}
const rest = len & 7;
const offset = len - rest;
if (rest > 0) {
var k1: u64 = 0;
@memcpy(@as([*]u8, @ptrCast(&k1))[0..rest], str[offset..]);
if (native_endian == .Big)
k1 = @byteSwap(k1);
h1 ^= k1;
h1 *%= m;
}
h1 ^= h1 >> 47;
h1 *%= m;
h1 ^= h1 >> 47;
return h1;
}
pub fn hashUint32(v: u32) u64 {
return @call(.{ .modifier = .always_inline }, Self.hashUint32WithSeed, .{ v, default_seed });
}
pub fn hashUint32WithSeed(v: u32, seed: u64) u64 {
const m: u64 = 0xc6a4a7935bd1e995;
const len: u64 = 4;
var h1: u64 = seed ^ (len *% m);
var k1: u64 = v;
h1 ^= k1;
h1 *%= m;
h1 ^= h1 >> 47;
h1 *%= m;
h1 ^= h1 >> 47;
return h1;
}
pub fn hashUint64(v: u64) u64 {
return @call(.{ .modifier = .always_inline }, Self.hashUint64WithSeed, .{ v, default_seed });
}
pub fn hashUint64WithSeed(v: u64, seed: u64) u64 {
const m: u64 = 0xc6a4a7935bd1e995;
const len: u64 = 8;
var h1: u64 = seed ^ (len *% m);
var k1: u64 = undefined;
k1 = v *% m;
k1 ^= k1 >> 47;
k1 *%= m;
h1 ^= k1;
h1 *%= m;
h1 ^= h1 >> 47;
h1 *%= m;
h1 ^= h1 >> 47;
return h1;
}
};
pub const Murmur3_32 = struct {
const Self = @This();
fn rotl32(x: u32, comptime r: u32) u32 {
return (x << r) | (x >> (32 - r));
}
pub fn hash(str: []const u8) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashWithSeed, .{ str, default_seed });
}
pub fn hashWithSeed(str: []const u8, seed: u32) u32 {
const c1: u32 = 0xcc9e2d51;
const c2: u32 = 0x1b873593;
const len = @as(u32, @truncate(str.len));
var h1: u32 = seed;
for (@as([*]align(1) const u32, @ptrCast(str.ptr))[0..(len >> 2)]) |v| {
var k1: u32 = v;
if (native_endian == .Big)
k1 = @byteSwap(k1);
k1 *%= c1;
k1 = rotl32(k1, 15);
k1 *%= c2;
h1 ^= k1;
h1 = rotl32(h1, 13);
h1 *%= 5;
h1 +%= 0xe6546b64;
}
{
var k1: u32 = 0;
const offset = len & 0xfffffffc;
const rest = len & 3;
if (rest == 3) {
k1 ^= @as(u32, @intCast(str[offset + 2])) << 16;
}
if (rest >= 2) {
k1 ^= @as(u32, @intCast(str[offset + 1])) << 8;
}
if (rest >= 1) {
k1 ^= @as(u32, @intCast(str[offset + 0]));
k1 *%= c1;
k1 = rotl32(k1, 15);
k1 *%= c2;
h1 ^= k1;
}
}
h1 ^= len;
h1 ^= h1 >> 16;
h1 *%= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *%= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
pub fn hashUint32(v: u32) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashUint32WithSeed, .{ v, default_seed });
}
pub fn hashUint32WithSeed(v: u32, seed: u32) u32 {
const c1: u32 = 0xcc9e2d51;
const c2: u32 = 0x1b873593;
const len: u32 = 4;
var h1: u32 = seed;
var k1: u32 = undefined;
k1 = v *% c1;
k1 = rotl32(k1, 15);
k1 *%= c2;
h1 ^= k1;
h1 = rotl32(h1, 13);
h1 *%= 5;
h1 +%= 0xe6546b64;
h1 ^= len;
h1 ^= h1 >> 16;
h1 *%= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *%= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
pub fn hashUint64(v: u64) u32 {
return @call(.{ .modifier = .always_inline }, Self.hashUint64WithSeed, .{ v, default_seed });
}
pub fn hashUint64WithSeed(v: u64, seed: u32) u32 {
const c1: u32 = 0xcc9e2d51;
const c2: u32 = 0x1b873593;
const len: u32 = 8;
var h1: u32 = seed;
var k1: u32 = undefined;
k1 = @as(u32, @truncate(v)) *% c1;
k1 = rotl32(k1, 15);
k1 *%= c2;
h1 ^= k1;
h1 = rotl32(h1, 13);
h1 *%= 5;
h1 +%= 0xe6546b64;
k1 = @as(u32, @truncate(v >> 32)) *% c1;
k1 = rotl32(k1, 15);
k1 *%= c2;
h1 ^= k1;
h1 = rotl32(h1, 13);
h1 *%= 5;
h1 +%= 0xe6546b64;
h1 ^= len;
h1 ^= h1 >> 16;
h1 *%= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *%= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
};
fn SMHasherTest(comptime hash_fn: anytype, comptime hashbits: u32) u32 {
const hashbytes = hashbits / 8;
var key: [256]u8 = [1]u8{0} ** 256;
var hashes: [hashbytes * 256]u8 = [1]u8{0} ** (hashbytes * 256);
var i: u32 = 0;
while (i < 256) : (i += 1) {
key[i] = @as(u8, @truncate(i));
var h = hash_fn(key[0..i], 256 - i);
if (native_endian == .Big)
h = @byteSwap(h);
@memcpy(hashes[i * hashbytes ..][0..hashbytes], @as([*]u8, @ptrCast(&h)));
}
return @as(u32, @truncate(hash_fn(&hashes, 0)));
}
test "murmur2_32" {
try testing.expectEqual(SMHasherTest(Murmur2_32.hashWithSeed, 32), 0x27864C1E);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (native_endian == .Big) {
v0le = @byteSwap(v0le);
v1le = @byteSwap(v1le);
}
try testing.expectEqual(Murmur2_32.hash(@as([*]u8, @ptrCast(&v0le))[0..4]), Murmur2_32.hashUint32(v0));
try testing.expectEqual(Murmur2_32.hash(@as([*]u8, @ptrCast(&v1le))[0..8]), Murmur2_32.hashUint64(v1));
}
test "murmur2_64" {
try std.testing.expectEqual(SMHasherTest(Murmur2_64.hashWithSeed, 64), 0x1F0D3804);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (native_endian == .Big) {
v0le = @byteSwap(v0le);
v1le = @byteSwap(v1le);
}
try testing.expectEqual(Murmur2_64.hash(@as([*]u8, @ptrCast(&v0le))[0..4]), Murmur2_64.hashUint32(v0));
try testing.expectEqual(Murmur2_64.hash(@as([*]u8, @ptrCast(&v1le))[0..8]), Murmur2_64.hashUint64(v1));
}
test "murmur3_32" {
try std.testing.expectEqual(SMHasherTest(Murmur3_32.hashWithSeed, 32), 0xB0F57EE3);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (native_endian == .Big) {
v0le = @byteSwap(v0le);
v1le = @byteSwap(v1le);
}
try testing.expectEqual(Murmur3_32.hash(@as([*]u8, @ptrCast(&v0le))[0..4]), Murmur3_32.hashUint32(v0));
try testing.expectEqual(Murmur3_32.hash(@as([*]u8, @ptrCast(&v1le))[0..8]), Murmur3_32.hashUint64(v1));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/wyhash.zig | const std = @import("std");
const mem = std.mem;
const primes = [_]u64{
0xa0761d6478bd642f,
0xe7037ed1a0b428db,
0x8ebc6af09c88c6e3,
0x589965cc75374cc3,
0x1d8e4e27c47d124f,
};
fn read_bytes(comptime bytes: u8, data: []const u8) u64 {
const T = std.meta.Int(.unsigned, 8 * bytes);
return mem.readIntLittle(T, data[0..bytes]);
}
fn read_8bytes_swapped(data: []const u8) u64 {
return (read_bytes(4, data) << 32 | read_bytes(4, data[4..]));
}
fn mum(a: u64, b: u64) u64 {
var r = std.math.mulWide(u64, a, b);
r = (r >> 64) ^ r;
return @as(u64, @truncate(r));
}
fn mix0(a: u64, b: u64, seed: u64) u64 {
return mum(a ^ seed ^ primes[0], b ^ seed ^ primes[1]);
}
fn mix1(a: u64, b: u64, seed: u64) u64 {
return mum(a ^ seed ^ primes[2], b ^ seed ^ primes[3]);
}
// Wyhash version which does not store internal state for handling partial buffers.
// This is needed so that we can maximize the speed for the short key case, which will
// use the non-iterative api which the public Wyhash exposes.
const WyhashStateless = struct {
seed: u64,
msg_len: usize,
pub fn init(seed: u64) WyhashStateless {
return WyhashStateless{
.seed = seed,
.msg_len = 0,
};
}
fn round(self: *WyhashStateless, b: []const u8) void {
std.debug.assert(b.len == 32);
self.seed = mix0(
read_bytes(8, b[0..]),
read_bytes(8, b[8..]),
self.seed,
) ^ mix1(
read_bytes(8, b[16..]),
read_bytes(8, b[24..]),
self.seed,
);
}
pub fn update(self: *WyhashStateless, b: []const u8) void {
std.debug.assert(b.len % 32 == 0);
var off: usize = 0;
while (off < b.len) : (off += 32) {
@call(.{ .modifier = .always_inline }, self.round, .{b[off .. off + 32]});
}
self.msg_len += b.len;
}
pub fn final(self: *WyhashStateless, b: []const u8) u64 {
std.debug.assert(b.len < 32);
const seed = self.seed;
const rem_len = @as(u5, @intCast(b.len));
const rem_key = b[0..rem_len];
self.seed = switch (rem_len) {
0 => seed,
1 => mix0(read_bytes(1, rem_key), primes[4], seed),
2 => mix0(read_bytes(2, rem_key), primes[4], seed),
3 => mix0((read_bytes(2, rem_key) << 8) | read_bytes(1, rem_key[2..]), primes[4], seed),
4 => mix0(read_bytes(4, rem_key), primes[4], seed),
5 => mix0((read_bytes(4, rem_key) << 8) | read_bytes(1, rem_key[4..]), primes[4], seed),
6 => mix0((read_bytes(4, rem_key) << 16) | read_bytes(2, rem_key[4..]), primes[4], seed),
7 => mix0((read_bytes(4, rem_key) << 24) | (read_bytes(2, rem_key[4..]) << 8) | read_bytes(1, rem_key[6..]), primes[4], seed),
8 => mix0(read_8bytes_swapped(rem_key), primes[4], seed),
9 => mix0(read_8bytes_swapped(rem_key), read_bytes(1, rem_key[8..]), seed),
10 => mix0(read_8bytes_swapped(rem_key), read_bytes(2, rem_key[8..]), seed),
11 => mix0(read_8bytes_swapped(rem_key), (read_bytes(2, rem_key[8..]) << 8) | read_bytes(1, rem_key[10..]), seed),
12 => mix0(read_8bytes_swapped(rem_key), read_bytes(4, rem_key[8..]), seed),
13 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 8) | read_bytes(1, rem_key[12..]), seed),
14 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 16) | read_bytes(2, rem_key[12..]), seed),
15 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 24) | (read_bytes(2, rem_key[12..]) << 8) | read_bytes(1, rem_key[14..]), seed),
16 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed),
17 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(1, rem_key[16..]), primes[4], seed),
18 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(2, rem_key[16..]), primes[4], seed),
19 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(2, rem_key[16..]) << 8) | read_bytes(1, rem_key[18..]), primes[4], seed),
20 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(4, rem_key[16..]), primes[4], seed),
21 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 8) | read_bytes(1, rem_key[20..]), primes[4], seed),
22 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 16) | read_bytes(2, rem_key[20..]), primes[4], seed),
23 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 24) | (read_bytes(2, rem_key[20..]) << 8) | read_bytes(1, rem_key[22..]), primes[4], seed),
24 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), primes[4], seed),
25 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(1, rem_key[24..]), seed),
26 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(2, rem_key[24..]), seed),
27 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(2, rem_key[24..]) << 8) | read_bytes(1, rem_key[26..]), seed),
28 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(4, rem_key[24..]), seed),
29 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 8) | read_bytes(1, rem_key[28..]), seed),
30 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 16) | read_bytes(2, rem_key[28..]), seed),
31 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 24) | (read_bytes(2, rem_key[28..]) << 8) | read_bytes(1, rem_key[30..]), seed),
};
self.msg_len += b.len;
return mum(self.seed ^ self.msg_len, primes[4]);
}
pub fn hash(seed: u64, input: []const u8) u64 {
const aligned_len = input.len - (input.len % 32);
var c = WyhashStateless.init(seed);
@call(.{ .modifier = .always_inline }, c.update, .{input[0..aligned_len]});
return @call(.{ .modifier = .always_inline }, c.final, .{input[aligned_len..]});
}
};
/// Fast non-cryptographic 64bit hash function.
/// See https://github.com/wangyi-fudan/wyhash
pub const Wyhash = struct {
state: WyhashStateless,
buf: [32]u8,
buf_len: usize,
pub fn init(seed: u64) Wyhash {
return Wyhash{
.state = WyhashStateless.init(seed),
.buf = undefined,
.buf_len = 0,
};
}
pub fn update(self: *Wyhash, b: []const u8) void {
var off: usize = 0;
if (self.buf_len != 0 and self.buf_len + b.len >= 32) {
off += 32 - self.buf_len;
mem.copy(u8, self.buf[self.buf_len..], b[0..off]);
self.state.update(self.buf[0..]);
self.buf_len = 0;
}
const remain_len = b.len - off;
const aligned_len = remain_len - (remain_len % 32);
self.state.update(b[off .. off + aligned_len]);
mem.copy(u8, self.buf[self.buf_len..], b[off + aligned_len ..]);
self.buf_len += @as(u8, @intCast(b[off + aligned_len ..].len));
}
pub fn final(self: *Wyhash) u64 {
const rem_key = self.buf[0..self.buf_len];
return self.state.final(rem_key);
}
pub fn hash(seed: u64, input: []const u8) u64 {
return WyhashStateless.hash(seed, input);
}
};
const expectEqual = std.testing.expectEqual;
test "test vectors" {
const hash = Wyhash.hash;
try expectEqual(hash(0, ""), 0x0);
try expectEqual(hash(1, "a"), 0xbed235177f41d328);
try expectEqual(hash(2, "abc"), 0xbe348debe59b27c3);
try expectEqual(hash(3, "message digest"), 0x37320f657213a290);
try expectEqual(hash(4, "abcdefghijklmnopqrstuvwxyz"), 0xd0b270e1d8a7019c);
try expectEqual(hash(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0x602a1894d3bbfe7f);
try expectEqual(hash(6, "12345678901234567890123456789012345678901234567890123456789012345678901234567890"), 0x829e9c148b75970e);
}
test "test vectors streaming" {
var wh = Wyhash.init(5);
for ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") |e| {
wh.update(mem.asBytes(&e));
}
try expectEqual(wh.final(), 0x602a1894d3bbfe7f);
const pattern = "1234567890";
const count = 8;
const result = 0x829e9c148b75970e;
try expectEqual(Wyhash.hash(6, pattern ** 8), result);
wh = Wyhash.init(6);
var i: u32 = 0;
while (i < count) : (i += 1) {
wh.update(pattern);
}
try expectEqual(wh.final(), result);
}
test "iterative non-divisible update" {
var buf: [8192]u8 = undefined;
for (buf, 0..) |*e, i| {
e.* = @as(u8, @truncate(i));
}
const seed = 0x128dad08f;
var end: usize = 32;
while (end < buf.len) : (end += 32) {
const non_iterative_hash = Wyhash.hash(seed, buf[0..end]);
var wy = Wyhash.init(seed);
var i: usize = 0;
while (i < end) : (i += 33) {
wy.update(buf[i..std.math.min(i + 33, end)]);
}
const iterative_hash = wy.final();
try std.testing.expectEqual(iterative_hash, non_iterative_hash);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/cityhash.zig | const std = @import("std");
inline fn offsetPtr(ptr: [*]const u8, offset: usize) [*]const u8 {
// ptr + offset doesn't work at comptime so we need this instead.
return @as([*]const u8, @ptrCast(&ptr[offset]));
}
fn fetch32(ptr: [*]const u8, offset: usize) u32 {
return std.mem.readIntLittle(u32, offsetPtr(ptr, offset)[0..4]);
}
fn fetch64(ptr: [*]const u8, offset: usize) u64 {
return std.mem.readIntLittle(u64, offsetPtr(ptr, offset)[0..8]);
}
pub const CityHash32 = struct {
const Self = @This();
// Magic numbers for 32-bit hashing. Copied from Murmur3.
const c1: u32 = 0xcc9e2d51;
const c2: u32 = 0x1b873593;
// A 32-bit to 32-bit integer hash copied from Murmur3.
fn fmix(h: u32) u32 {
var h1: u32 = h;
h1 ^= h1 >> 16;
h1 *%= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *%= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
// Rotate right helper
fn rotr32(x: u32, comptime r: u32) u32 {
return (x >> r) | (x << (32 - r));
}
// Helper from Murmur3 for combining two 32-bit values.
fn mur(a: u32, h: u32) u32 {
var a1: u32 = a;
var h1: u32 = h;
a1 *%= c1;
a1 = rotr32(a1, 17);
a1 *%= c2;
h1 ^= a1;
h1 = rotr32(h1, 19);
return h1 *% 5 +% 0xe6546b64;
}
fn hash32Len0To4(str: []const u8) u32 {
const len: u32 = @as(u32, @truncate(str.len));
var b: u32 = 0;
var c: u32 = 9;
for (str) |v| {
b = b *% c1 +% @as(u32, @bitCast(@as(i32, @intCast(@as(i8, @bitCast(v))))));
c ^= b;
}
return fmix(mur(b, mur(len, c)));
}
fn hash32Len5To12(str: []const u8) u32 {
var a: u32 = @as(u32, @truncate(str.len));
var b: u32 = a *% 5;
var c: u32 = 9;
const d: u32 = b;
a +%= fetch32(str.ptr, 0);
b +%= fetch32(str.ptr, str.len - 4);
c +%= fetch32(str.ptr, (str.len >> 1) & 4);
return fmix(mur(c, mur(b, mur(a, d))));
}
fn hash32Len13To24(str: []const u8) u32 {
const len: u32 = @as(u32, @truncate(str.len));
const a: u32 = fetch32(str.ptr, (str.len >> 1) - 4);
const b: u32 = fetch32(str.ptr, 4);
const c: u32 = fetch32(str.ptr, str.len - 8);
const d: u32 = fetch32(str.ptr, str.len >> 1);
const e: u32 = fetch32(str.ptr, 0);
const f: u32 = fetch32(str.ptr, str.len - 4);
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, len)))))));
}
pub fn hash(str: []const u8) u32 {
if (str.len <= 24) {
if (str.len <= 4) {
return hash32Len0To4(str);
} else {
if (str.len <= 12)
return hash32Len5To12(str);
return hash32Len13To24(str);
}
}
const len: u32 = @as(u32, @truncate(str.len));
var h: u32 = len;
var g: u32 = c1 *% len;
var f: u32 = g;
const a0: u32 = rotr32(fetch32(str.ptr, str.len - 4) *% c1, 17) *% c2;
const a1: u32 = rotr32(fetch32(str.ptr, str.len - 8) *% c1, 17) *% c2;
const a2: u32 = rotr32(fetch32(str.ptr, str.len - 16) *% c1, 17) *% c2;
const a3: u32 = rotr32(fetch32(str.ptr, str.len - 12) *% c1, 17) *% c2;
const a4: u32 = rotr32(fetch32(str.ptr, str.len - 20) *% c1, 17) *% c2;
h ^= a0;
h = rotr32(h, 19);
h = h *% 5 +% 0xe6546b64;
h ^= a2;
h = rotr32(h, 19);
h = h *% 5 +% 0xe6546b64;
g ^= a1;
g = rotr32(g, 19);
g = g *% 5 +% 0xe6546b64;
g ^= a3;
g = rotr32(g, 19);
g = g *% 5 +% 0xe6546b64;
f +%= a4;
f = rotr32(f, 19);
f = f *% 5 +% 0xe6546b64;
var iters = (str.len - 1) / 20;
var ptr = str.ptr;
while (iters != 0) : (iters -= 1) {
const b0: u32 = rotr32(fetch32(ptr, 0) *% c1, 17) *% c2;
const b1: u32 = fetch32(ptr, 4);
const b2: u32 = rotr32(fetch32(ptr, 8) *% c1, 17) *% c2;
const b3: u32 = rotr32(fetch32(ptr, 12) *% c1, 17) *% c2;
const b4: u32 = fetch32(ptr, 16);
h ^= b0;
h = rotr32(h, 18);
h = h *% 5 +% 0xe6546b64;
f +%= b1;
f = rotr32(f, 19);
f = f *% c1;
g +%= b2;
g = rotr32(g, 18);
g = g *% 5 +% 0xe6546b64;
h ^= b3 +% b1;
h = rotr32(h, 19);
h = h *% 5 +% 0xe6546b64;
g ^= b4;
g = @byteSwap(g) *% 5;
h +%= b4 *% 5;
h = @byteSwap(h);
f +%= b0;
const t: u32 = h;
h = f;
f = g;
g = t;
ptr = offsetPtr(ptr, 20);
}
g = rotr32(g, 11) *% c1;
g = rotr32(g, 17) *% c1;
f = rotr32(f, 11) *% c1;
f = rotr32(f, 17) *% c1;
h = rotr32(h +% g, 19);
h = h *% 5 +% 0xe6546b64;
h = rotr32(h, 17) *% c1;
h = rotr32(h +% f, 19);
h = h *% 5 +% 0xe6546b64;
h = rotr32(h, 17) *% c1;
return h;
}
};
pub const CityHash64 = struct {
const Self = @This();
// Some primes between 2^63 and 2^64 for various uses.
const k0: u64 = 0xc3a5c85c97cb3127;
const k1: u64 = 0xb492b66fbe98f273;
const k2: u64 = 0x9ae16a3b2f90404f;
// Rotate right helper
fn rotr64(x: u64, comptime r: u64) u64 {
return (x >> r) | (x << (64 - r));
}
fn shiftmix(v: u64) u64 {
return v ^ (v >> 47);
}
fn hashLen16(u: u64, v: u64) u64 {
return @call(.{ .modifier = .always_inline }, hash128To64, .{ u, v });
}
fn hashLen16Mul(low: u64, high: u64, mul: u64) u64 {
var a: u64 = (low ^ high) *% mul;
a ^= (a >> 47);
var b: u64 = (high ^ a) *% mul;
b ^= (b >> 47);
b *%= mul;
return b;
}
fn hash128To64(low: u64, high: u64) u64 {
return @call(.{ .modifier = .always_inline }, hashLen16Mul, .{ low, high, 0x9ddfea08eb382d69 });
}
fn hashLen0To16(str: []const u8) u64 {
const len: u64 = @as(u64, str.len);
if (len >= 8) {
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr, 0) +% k2;
const b: u64 = fetch64(str.ptr, str.len - 8);
const c: u64 = rotr64(b, 37) *% mul +% a;
const d: u64 = (rotr64(a, 25) +% b) *% mul;
return hashLen16Mul(c, d, mul);
}
if (len >= 4) {
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch32(str.ptr, 0);
return hashLen16Mul(len +% (a << 3), fetch32(str.ptr, str.len - 4), mul);
}
if (len > 0) {
const a: u8 = str[0];
const b: u8 = str[str.len >> 1];
const c: u8 = str[str.len - 1];
const y: u32 = @as(u32, @intCast(a)) +% (@as(u32, @intCast(b)) << 8);
const z: u32 = @as(u32, @truncate(str.len)) +% (@as(u32, @intCast(c)) << 2);
return shiftmix(@as(u64, @intCast(y)) *% k2 ^ @as(u64, @intCast(z)) *% k0) *% k2;
}
return k2;
}
fn hashLen17To32(str: []const u8) u64 {
const len: u64 = @as(u64, str.len);
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr, 0) *% k1;
const b: u64 = fetch64(str.ptr, 8);
const c: u64 = fetch64(str.ptr, str.len - 8) *% mul;
const d: u64 = fetch64(str.ptr, str.len - 16) *% k2;
return hashLen16Mul(rotr64(a +% b, 43) +% rotr64(c, 30) +% d, a +% rotr64(b +% k2, 18) +% c, mul);
}
fn hashLen33To64(str: []const u8) u64 {
const len: u64 = @as(u64, str.len);
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr, 0) *% k2;
const b: u64 = fetch64(str.ptr, 8);
const c: u64 = fetch64(str.ptr, str.len - 24);
const d: u64 = fetch64(str.ptr, str.len - 32);
const e: u64 = fetch64(str.ptr, 16) *% k2;
const f: u64 = fetch64(str.ptr, 24) *% 9;
const g: u64 = fetch64(str.ptr, str.len - 8);
const h: u64 = fetch64(str.ptr, str.len - 16) *% mul;
const u: u64 = rotr64(a +% g, 43) +% (rotr64(b, 30) +% c) *% 9;
const v: u64 = ((a +% g) ^ d) +% f +% 1;
const w: u64 = @byteSwap((u +% v) *% mul) +% h;
const x: u64 = rotr64(e +% f, 42) +% c;
const y: u64 = (@byteSwap((v +% w) *% mul) +% g) *% mul;
const z: u64 = e +% f +% c;
const a1: u64 = @byteSwap((x +% z) *% mul +% y) +% b;
const b1: u64 = shiftmix((z +% a1) *% mul +% d +% h) *% mul;
return b1 +% x;
}
const WeakPair = struct {
first: u64,
second: u64,
};
fn weakHashLen32WithSeedsHelper(w: u64, x: u64, y: u64, z: u64, a: u64, b: u64) WeakPair {
var a1: u64 = a;
var b1: u64 = b;
a1 +%= w;
b1 = rotr64(b1 +% a1 +% z, 21);
var c: u64 = a1;
a1 +%= x;
a1 +%= y;
b1 +%= rotr64(a1, 44);
return WeakPair{ .first = a1 +% z, .second = b1 +% c };
}
fn weakHashLen32WithSeeds(ptr: [*]const u8, a: u64, b: u64) WeakPair {
return @call(.{ .modifier = .always_inline }, weakHashLen32WithSeedsHelper, .{
fetch64(ptr, 0),
fetch64(ptr, 8),
fetch64(ptr, 16),
fetch64(ptr, 24),
a,
b,
});
}
pub fn hash(str: []const u8) u64 {
if (str.len <= 32) {
if (str.len <= 16) {
return hashLen0To16(str);
} else {
return hashLen17To32(str);
}
} else if (str.len <= 64) {
return hashLen33To64(str);
}
var len: u64 = @as(u64, str.len);
var x: u64 = fetch64(str.ptr, str.len - 40);
var y: u64 = fetch64(str.ptr, str.len - 16) +% fetch64(str.ptr, str.len - 56);
var z: u64 = hashLen16(fetch64(str.ptr, str.len - 48) +% len, fetch64(str.ptr, str.len - 24));
var v: WeakPair = weakHashLen32WithSeeds(offsetPtr(str.ptr, str.len - 64), len, z);
var w: WeakPair = weakHashLen32WithSeeds(offsetPtr(str.ptr, str.len - 32), y +% k1, x);
x = x *% k1 +% fetch64(str.ptr, 0);
len = (len - 1) & ~@as(u64, @intCast(63));
var ptr: [*]const u8 = str.ptr;
while (true) {
x = rotr64(x +% y +% v.first +% fetch64(ptr, 8), 37) *% k1;
y = rotr64(y +% v.second +% fetch64(ptr, 48), 42) *% k1;
x ^= w.second;
y +%= v.first +% fetch64(ptr, 40);
z = rotr64(z +% w.first, 33) *% k1;
v = weakHashLen32WithSeeds(ptr, v.second *% k1, x +% w.first);
w = weakHashLen32WithSeeds(offsetPtr(ptr, 32), z +% w.second, y +% fetch64(ptr, 16));
const t: u64 = z;
z = x;
x = t;
ptr = offsetPtr(ptr, 64);
len -= 64;
if (len == 0)
break;
}
return hashLen16(hashLen16(v.first, w.first) +% shiftmix(y) *% k1 +% z, hashLen16(v.second, w.second) +% x);
}
pub fn hashWithSeed(str: []const u8, seed: u64) u64 {
return @call(.{ .modifier = .always_inline }, Self.hashWithSeeds, .{ str, k2, seed });
}
pub fn hashWithSeeds(str: []const u8, seed0: u64, seed1: u64) u64 {
return hashLen16(hash(str) -% seed0, seed1);
}
};
fn SMHasherTest(comptime hash_fn: anytype) u32 {
const HashResult = @typeInfo(@TypeOf(hash_fn)).Fn.return_type.?;
var key: [256]u8 = undefined;
var hashes_bytes: [256 * @sizeOf(HashResult)]u8 = undefined;
std.mem.set(u8, &key, 0);
std.mem.set(u8, &hashes_bytes, 0);
var i: u32 = 0;
while (i < 256) : (i += 1) {
key[i] = @as(u8, @intCast(i));
var h: HashResult = hash_fn(key[0..i], 256 - i);
// comptime can't really do reinterpret casting yet,
// so we need to write the bytes manually.
for (hashes_bytes[i * @sizeOf(HashResult) ..][0..@sizeOf(HashResult)]) |*byte| {
byte.* = @as(u8, @truncate(h));
h = h >> 8;
}
}
return @as(u32, @truncate(hash_fn(&hashes_bytes, 0)));
}
fn CityHash32hashIgnoreSeed(str: []const u8, seed: u32) u32 {
_ = seed;
return CityHash32.hash(str);
}
test "cityhash32" {
const Test = struct {
fn doTest() !void {
// Note: SMHasher doesn't provide a 32bit version of the algorithm.
// Note: The implementation was verified against the Google Abseil version.
try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
}
};
try Test.doTest();
// TODO This is uncommented to prevent OOM on the CI server. Re-enable this test
// case once we ship stage2.
//@setEvalBranchQuota(50000);
//comptime Test.doTest();
}
test "cityhash64" {
const Test = struct {
fn doTest() !void {
// Note: This is not compliant with the SMHasher implementation of CityHash64!
// Note: The implementation was verified against the Google Abseil version.
try std.testing.expectEqual(SMHasherTest(CityHash64.hashWithSeed), 0x5FABC5C5);
}
};
try Test.doTest();
// TODO This is uncommented to prevent OOM on the CI server. Re-enable this test
// case once we ship stage2.
//@setEvalBranchQuota(50000);
//comptime Test.doTest();
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/hash/adler.zig | // Adler32 checksum.
//
// https://tools.ietf.org/html/rfc1950#section-9
// https://github.com/madler/zlib/blob/master/adler32.c
const std = @import("../std.zig");
const testing = std.testing;
pub const Adler32 = struct {
const base = 65521;
const nmax = 5552;
adler: u32,
pub fn init() Adler32 {
return Adler32{ .adler = 1 };
}
// This fast variant is taken from zlib. It reduces the required modulos and unrolls longer
// buffer inputs and should be much quicker.
pub fn update(self: *Adler32, input: []const u8) void {
var s1 = self.adler & 0xffff;
var s2 = (self.adler >> 16) & 0xffff;
if (input.len == 1) {
s1 +%= input[0];
if (s1 >= base) {
s1 -= base;
}
s2 +%= s1;
if (s2 >= base) {
s2 -= base;
}
} else if (input.len < 16) {
for (input) |b| {
s1 +%= b;
s2 +%= s1;
}
if (s1 >= base) {
s1 -= base;
}
s2 %= base;
} else {
const n = nmax / 16; // note: 16 | nmax
var i: usize = 0;
while (i + nmax <= input.len) {
var rounds: usize = 0;
while (rounds < n) : (rounds += 1) {
comptime var j: usize = 0;
inline while (j < 16) : (j += 1) {
s1 +%= input[i + j];
s2 +%= s1;
}
i += 16;
}
s1 %= base;
s2 %= base;
}
if (i < input.len) {
while (i + 16 <= input.len) : (i += 16) {
comptime var j: usize = 0;
inline while (j < 16) : (j += 1) {
s1 +%= input[i + j];
s2 +%= s1;
}
}
while (i < input.len) : (i += 1) {
s1 +%= input[i];
s2 +%= s1;
}
s1 %= base;
s2 %= base;
}
}
self.adler = s1 | (s2 << 16);
}
pub fn final(self: *Adler32) u32 {
return self.adler;
}
pub fn hash(input: []const u8) u32 {
var c = Adler32.init();
c.update(input);
return c.final();
}
};
test "adler32 sanity" {
try testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a"));
try testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example"));
}
test "adler32 long" {
const long1 = [_]u8{1} ** 1024;
try testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..]));
const long2 = [_]u8{1} ** 1025;
try testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..]));
}
test "adler32 very long" {
const long = [_]u8{1} ** 5553;
try testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..]));
}
test "adler32 very long with variation" {
const long = comptime blk: {
@setEvalBranchQuota(7000);
var result: [6000]u8 = undefined;
var i: usize = 0;
while (i < result.len) : (i += 1) {
result[i] = @as(u8, @truncate(i));
}
break :blk result;
};
try testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..]));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/compress/zlib.zig | //
// Decompressor for ZLIB data streams (RFC1950)
const std = @import("std");
const io = std.io;
const fs = std.fs;
const testing = std.testing;
const mem = std.mem;
const deflate = std.compress.deflate;
pub fn ZlibStream(comptime ReaderType: type) type {
return struct {
const Self = @This();
pub const Error = ReaderType.Error ||
deflate.InflateStream(ReaderType).Error ||
error{ WrongChecksum, Unsupported };
pub const Reader = io.Reader(*Self, Error, read);
allocator: *mem.Allocator,
inflater: deflate.InflateStream(ReaderType),
in_reader: ReaderType,
hasher: std.hash.Adler32,
window_slice: []u8,
fn init(allocator: *mem.Allocator, source: ReaderType) !Self {
// Zlib header format is specified in RFC1950
const header = try source.readBytesNoEof(2);
const CM = @as(u4, @truncate(header[0]));
const CINFO = @as(u4, @truncate(header[0] >> 4));
const FCHECK = @as(u5, @truncate(header[1]));
_ = FCHECK;
const FDICT = @as(u1, @truncate(header[1] >> 5));
if ((@as(u16, header[0]) << 8 | header[1]) % 31 != 0)
return error.BadHeader;
// The CM field must be 8 to indicate the use of DEFLATE
if (CM != 8) return error.InvalidCompression;
// CINFO is the base-2 logarithm of the window size, minus 8.
// Values above 7 are unspecified and therefore rejected.
if (CINFO > 7) return error.InvalidWindowSize;
const window_size: u16 = @as(u16, 1) << (CINFO + 8);
// TODO: Support this case
if (FDICT != 0)
return error.Unsupported;
var window_slice = try allocator.alloc(u8, window_size);
return Self{
.allocator = allocator,
.inflater = deflate.inflateStream(source, window_slice),
.in_reader = source,
.hasher = std.hash.Adler32.init(),
.window_slice = window_slice,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.window_slice);
}
// Implements the io.Reader interface
pub fn read(self: *Self, buffer: []u8) Error!usize {
if (buffer.len == 0)
return 0;
// Read from the compressed stream and update the computed checksum
const r = try self.inflater.read(buffer);
if (r != 0) {
self.hasher.update(buffer[0..r]);
return r;
}
// We've reached the end of stream, check if the checksum matches
const hash = try self.in_reader.readIntBig(u32);
if (hash != self.hasher.final())
return error.WrongChecksum;
return 0;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn zlibStream(allocator: *mem.Allocator, reader: anytype) !ZlibStream(@TypeOf(reader)) {
return ZlibStream(@TypeOf(reader)).init(allocator, reader);
}
fn testReader(data: []const u8, comptime expected: []const u8) !void {
var in_stream = io.fixedBufferStream(data);
var zlib_stream = try zlibStream(testing.allocator, in_stream.reader());
defer zlib_stream.deinit();
// Read and decompress the whole file
const buf = try zlib_stream.reader().readAllAlloc(testing.allocator, std.math.maxInt(usize));
defer testing.allocator.free(buf);
// Calculate its SHA256 hash and check it against the reference
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(buf, hash[0..], .{});
try assertEqual(expected, &hash);
}
// Assert `expected` == `input` where `input` is a bytestring.
pub fn assertEqual(comptime expected: []const u8, input: []const u8) !void {
var expected_bytes: [expected.len / 2]u8 = undefined;
for (expected_bytes, 0..) |*r, i| {
r.* = std.fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
}
try testing.expectEqualSlices(u8, &expected_bytes, input);
}
// All the test cases are obtained by compressing the RFC1950 text
//
// https://tools.ietf.org/rfc/rfc1950.txt length=36944 bytes
// SHA256=5ebf4b5b7fe1c3a0c0ab9aa3ac8c0f3853a7dc484905e76e03b0b0f301350009
test "compressed data" {
// Compressed with compression level = 0
try testReader(
@embedFile("rfc1951.txt.z.0"),
"5ebf4b5b7fe1c3a0c0ab9aa3ac8c0f3853a7dc484905e76e03b0b0f301350009",
);
// Compressed with compression level = 9
try testReader(
@embedFile("rfc1951.txt.z.9"),
"5ebf4b5b7fe1c3a0c0ab9aa3ac8c0f3853a7dc484905e76e03b0b0f301350009",
);
// Compressed with compression level = 9 and fixed Huffman codes
try testReader(
@embedFile("rfc1951.txt.fixed.z.9"),
"5ebf4b5b7fe1c3a0c0ab9aa3ac8c0f3853a7dc484905e76e03b0b0f301350009",
);
}
test "don't read past deflate stream's end" {
try testReader(
&[_]u8{
0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0xc0, 0x00, 0xc1, 0xff,
0xff, 0x43, 0x30, 0x03, 0x03, 0xc3, 0xff, 0xff, 0xff, 0x01,
0x83, 0x95, 0x0b, 0xf5,
},
// SHA256 of
// 00ff 0000 00ff 0000 00ff 00ff ffff 00ff ffff 0000 0000 ffff ff
"3bbba1cc65408445c81abb61f3d2b86b1b60ee0d70b4c05b96d1499091a08c93",
);
}
test "sanity checks" {
// Truncated header
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{0x78}, ""),
);
// Failed FCHECK check
try testing.expectError(
error.BadHeader,
testReader(&[_]u8{ 0x78, 0x9D }, ""),
);
// Wrong CM
try testing.expectError(
error.InvalidCompression,
testReader(&[_]u8{ 0x79, 0x94 }, ""),
);
// Wrong CINFO
try testing.expectError(
error.InvalidWindowSize,
testReader(&[_]u8{ 0x88, 0x98 }, ""),
);
// Wrong checksum
try testing.expectError(
error.WrongChecksum,
testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 }, ""),
);
// Truncated checksum
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00 }, ""),
);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/compress/deflate.zig | //
// Decompressor for DEFLATE data streams (RFC1951)
//
// Heavily inspired by the simple decompressor puff.c by Mark Adler
const std = @import("std");
const io = std.io;
const math = std.math;
const mem = std.mem;
const assert = std.debug.assert;
const MAXBITS = 15;
const MAXLCODES = 286;
const MAXDCODES = 30;
const MAXCODES = MAXLCODES + MAXDCODES;
const FIXLCODES = 288;
// The maximum length of a Huffman code's prefix we can decode using the fast
// path. The factor 9 is inherited from Zlib, tweaking the value showed little
// or no changes in the profiler output.
const PREFIX_LUT_BITS = 9;
const Huffman = struct {
const LUTEntry = packed struct { symbol: u16, len: u16 };
// Number of codes for each possible length
count: [MAXBITS + 1]u16,
// Mapping between codes and symbols
symbol: [MAXCODES]u16,
// The decoding process uses a trick explained by Mark Adler in [1].
// We basically precompute for a fixed number of codes (0 <= x <= 2^N-1)
// the symbol and the effective code length we'd get if the decoder was run
// on the given N-bit sequence.
// A code with length 0 means the sequence is not a valid prefix for this
// canonical Huffman code and we have to decode it using a slower method.
//
// [1] https://github.com/madler/zlib/blob/v1.2.11/doc/algorithm.txt#L58
prefix_lut: [1 << PREFIX_LUT_BITS]LUTEntry,
// The following info refer to the codes of length PREFIX_LUT_BITS+1 and are
// used to bootstrap the bit-by-bit reading method if the fast-path fails.
last_code: u16,
last_index: u16,
min_code_len: u16,
const ConstructError = error{ Oversubscribed, IncompleteSet };
fn construct(self: *Huffman, code_length: []const u16) ConstructError!void {
for (self.count) |*val| {
val.* = 0;
}
self.min_code_len = math.maxInt(u16);
for (code_length) |len| {
if (len != 0 and len < self.min_code_len)
self.min_code_len = len;
self.count[len] += 1;
}
// All zero.
if (self.count[0] == code_length.len) {
self.min_code_len = 0;
return;
}
var left: isize = 1;
for (self.count[1..]) |val| {
// Each added bit doubles the amount of codes.
left *= 2;
// Make sure the number of codes with this length isn't too high.
left -= @as(isize, @as(i16, @bitCast(val)));
if (left < 0)
return error.Oversubscribed;
}
// Compute the offset of the first symbol represented by a code of a
// given length in the symbol table, together with the first canonical
// Huffman code for that length.
var offset: [MAXBITS + 1]u16 = undefined;
var codes: [MAXBITS + 1]u16 = undefined;
{
offset[1] = 0;
codes[1] = 0;
var len: usize = 1;
while (len < MAXBITS) : (len += 1) {
offset[len + 1] = offset[len] + self.count[len];
codes[len + 1] = (codes[len] + self.count[len]) << 1;
}
}
self.prefix_lut = mem.zeroes(@TypeOf(self.prefix_lut));
for (code_length, 0..) |len, symbol| {
if (len != 0) {
// Fill the symbol table.
// The symbols are assigned sequentially for each length.
self.symbol[offset[len]] = @as(u16, @truncate(symbol));
// Track the last assigned offset.
offset[len] += 1;
}
if (len == 0 or len > PREFIX_LUT_BITS)
continue;
// Given a Huffman code of length N we transform it into an index
// into the lookup table by reversing its bits and filling the
// remaining bits (PREFIX_LUT_BITS - N) with every possible
// combination of bits to act as a wildcard.
const bits_to_fill = @as(u5, @intCast(PREFIX_LUT_BITS - len));
const rev_code = bitReverse(u16, codes[len], len);
// Track the last used code, but only for lengths < PREFIX_LUT_BITS.
codes[len] += 1;
var j: usize = 0;
while (j < @as(usize, 1) << bits_to_fill) : (j += 1) {
const index = rev_code | (j << @as(u5, @intCast(len)));
assert(self.prefix_lut[index].len == 0);
self.prefix_lut[index] = .{
.symbol = @as(u16, @truncate(symbol)),
.len = @as(u16, @truncate(len)),
};
}
}
self.last_code = codes[PREFIX_LUT_BITS + 1];
self.last_index = offset[PREFIX_LUT_BITS + 1] - self.count[PREFIX_LUT_BITS + 1];
if (left > 0)
return error.IncompleteSet;
}
};
// Reverse bit-by-bit a N-bit code.
fn bitReverse(comptime T: type, value: T, N: usize) T {
const r: T = @bitReverse(value);
return r >> @as(math.Log2Int(T), @intCast(@typeInfo(T).Int.bits - N));
}
pub fn InflateStream(comptime ReaderType: type) type {
return struct {
const Self = @This();
pub const Error = ReaderType.Error || error{
EndOfStream,
BadCounts,
InvalidBlockType,
InvalidDistance,
InvalidFixedCode,
InvalidLength,
InvalidStoredSize,
InvalidSymbol,
InvalidTree,
MissingEOBCode,
NoLastLength,
OutOfCodes,
};
pub const Reader = io.Reader(*Self, Error, read);
inner_reader: ReaderType,
// True if the decoder met the end of the compressed stream, no further
// data can be decompressed
seen_eos: bool,
state: union(enum) {
// Parse a compressed block header and set up the internal state for
// decompressing its contents.
DecodeBlockHeader: void,
// Decode all the symbols in a compressed block.
DecodeBlockData: void,
// Copy N bytes of uncompressed data from the underlying stream into
// the window.
Copy: usize,
// Copy 1 byte into the window.
CopyLit: u8,
// Copy L bytes from the window itself, starting from D bytes
// behind.
CopyFrom: struct { distance: u16, length: u16 },
},
// Sliding window for the LZ77 algorithm
window: struct {
const WSelf = @This();
// invariant: buffer length is always a power of 2
buf: []u8,
// invariant: ri <= wi
wi: usize = 0, // Write index
ri: usize = 0, // Read index
el: usize = 0, // Number of readable elements
total_written: usize = 0,
fn readable(self: *WSelf) usize {
return self.el;
}
fn writable(self: *WSelf) usize {
return self.buf.len - self.el;
}
// Insert a single byte into the window.
// Returns 1 if there's enough space for the new byte and 0
// otherwise.
fn append(self: *WSelf, value: u8) usize {
if (self.writable() < 1) return 0;
self.appendUnsafe(value);
return 1;
}
// Insert a single byte into the window.
// Assumes there's enough space.
inline fn appendUnsafe(self: *WSelf, value: u8) void {
self.buf[self.wi] = value;
self.wi = (self.wi + 1) & (self.buf.len - 1);
self.el += 1;
self.total_written += 1;
}
// Fill dest[] with data from the window, starting from the read
// position. This updates the read pointer.
// Returns the number of read bytes or 0 if there's nothing to read
// yet.
fn read(self: *WSelf, dest: []u8) usize {
const N = math.min(dest.len, self.readable());
if (N == 0) return 0;
if (self.ri + N < self.buf.len) {
// The data doesn't wrap around
mem.copy(u8, dest, self.buf[self.ri .. self.ri + N]);
} else {
// The data wraps around the buffer, split the copy
std.mem.copy(u8, dest, self.buf[self.ri..]);
// How much data we've copied from `ri` to the end
const r = self.buf.len - self.ri;
std.mem.copy(u8, dest[r..], self.buf[0 .. N - r]);
}
self.ri = (self.ri + N) & (self.buf.len - 1);
self.el -= N;
return N;
}
// Copy `length` bytes starting from `distance` bytes behind the
// write pointer.
// Be careful as the length may be greater than the distance, that's
// how the compressor encodes run-length encoded sequences.
fn copyFrom(self: *WSelf, distance: usize, length: usize) usize {
const N = math.min(length, self.writable());
if (N == 0) return 0;
// TODO: Profile and, if needed, replace with smarter juggling
// of the window memory for the non-overlapping case.
var i: usize = 0;
while (i < N) : (i += 1) {
const index = (self.wi -% distance) & (self.buf.len - 1);
self.appendUnsafe(self.buf[index]);
}
return N;
}
},
// Compressor-local Huffman tables used to decompress blocks with
// dynamic codes.
huffman_tables: [2]Huffman = undefined,
// Huffman tables used for decoding length/distance pairs.
hdist: *Huffman,
hlen: *Huffman,
// Temporary buffer for the bitstream.
// Bits 0..`bits_left` are filled with data, the remaining ones are zeros.
bits: u32,
bits_left: usize,
fn peekBits(self: *Self, bits: usize) !u32 {
while (self.bits_left < bits) {
const byte = try self.inner_reader.readByte();
self.bits |= @as(u32, byte) << @as(u5, @intCast(self.bits_left));
self.bits_left += 8;
}
const mask = (@as(u32, 1) << @as(u5, @intCast(bits))) - 1;
return self.bits & mask;
}
fn readBits(self: *Self, bits: usize) !u32 {
const val = try self.peekBits(bits);
self.discardBits(bits);
return val;
}
fn discardBits(self: *Self, bits: usize) void {
self.bits >>= @as(u5, @intCast(bits));
self.bits_left -= bits;
}
fn stored(self: *Self) !void {
// Discard the remaining bits, the length field is always
// byte-aligned (and so is the data).
self.discardBits(self.bits_left);
const length = try self.inner_reader.readIntLittle(u16);
const length_cpl = try self.inner_reader.readIntLittle(u16);
if (length != ~length_cpl)
return error.InvalidStoredSize;
self.state = .{ .Copy = length };
}
fn fixed(self: *Self) !void {
comptime var lencode: Huffman = undefined;
comptime var distcode: Huffman = undefined;
// The Huffman codes are specified in the RFC1951, section 3.2.6
comptime {
@setEvalBranchQuota(100000);
const len_lengths =
[_]u16{8} ** 144 ++
[_]u16{9} ** 112 ++
[_]u16{7} ** 24 ++
[_]u16{8} ** 8;
assert(len_lengths.len == FIXLCODES);
try lencode.construct(len_lengths[0..]);
const dist_lengths = [_]u16{5} ** MAXDCODES;
distcode.construct(dist_lengths[0..]) catch |err| switch (err) {
// This error is expected because we only compute distance codes
// 0-29, which is fine since "distance codes 30-31 will never actually
// occur in the compressed data" (from section 3.2.6 of RFC1951).
error.IncompleteSet => {},
else => return err,
};
}
self.hlen = &lencode;
self.hdist = &distcode;
self.state = .DecodeBlockData;
}
fn dynamic(self: *Self) !void {
// Number of length codes
const nlen = (try self.readBits(5)) + 257;
// Number of distance codes
const ndist = (try self.readBits(5)) + 1;
// Number of code length codes
const ncode = (try self.readBits(4)) + 4;
if (nlen > MAXLCODES or ndist > MAXDCODES)
return error.BadCounts;
// Permutation of code length codes
const ORDER = [19]u16{
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4,
12, 3, 13, 2, 14, 1, 15,
};
// Build the Huffman table to decode the code length codes
var lencode: Huffman = undefined;
{
var lengths = std.mem.zeroes([19]u16);
// Read the code lengths, missing ones are left as zero
for (ORDER[0..ncode]) |val| {
lengths[val] = @as(u16, @intCast(try self.readBits(3)));
}
lencode.construct(lengths[0..]) catch return error.InvalidTree;
}
// Read the length/literal and distance code length tables.
// Zero the table by default so we can avoid explicitly writing out
// zeros for codes 17 and 18
var lengths = std.mem.zeroes([MAXCODES]u16);
var i: usize = 0;
while (i < nlen + ndist) {
const symbol = try self.decode(&lencode);
switch (symbol) {
0...15 => {
lengths[i] = symbol;
i += 1;
},
16 => {
// repeat last length 3..6 times
if (i == 0) return error.NoLastLength;
const last_length = lengths[i - 1];
const repeat = 3 + (try self.readBits(2));
const last_index = i + repeat;
if (last_index > lengths.len)
return error.InvalidLength;
while (i < last_index) : (i += 1) {
lengths[i] = last_length;
}
},
17 => {
// repeat zero 3..10 times
i += 3 + (try self.readBits(3));
},
18 => {
// repeat zero 11..138 times
i += 11 + (try self.readBits(7));
},
else => return error.InvalidSymbol,
}
}
if (i > nlen + ndist)
return error.InvalidLength;
// Check if the end of block code is present
if (lengths[256] == 0)
return error.MissingEOBCode;
self.huffman_tables[0].construct(lengths[0..nlen]) catch |err| switch (err) {
error.Oversubscribed => return error.InvalidTree,
error.IncompleteSet => {
// incomplete code ok only for single length 1 code
if (nlen != self.huffman_tables[0].count[0] + self.huffman_tables[0].count[1]) {
return error.InvalidTree;
}
},
};
self.huffman_tables[1].construct(lengths[nlen .. nlen + ndist]) catch |err| switch (err) {
error.Oversubscribed => return error.InvalidTree,
error.IncompleteSet => {
// incomplete code ok only for single length 1 code
if (ndist != self.huffman_tables[1].count[0] + self.huffman_tables[1].count[1]) {
return error.InvalidTree;
}
},
};
self.hlen = &self.huffman_tables[0];
self.hdist = &self.huffman_tables[1];
self.state = .DecodeBlockData;
}
fn codes(self: *Self, lencode: *Huffman, distcode: *Huffman) !bool {
// Size base for length codes 257..285
const LENS = [29]u16{
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258,
};
// Extra bits for length codes 257..285
const LEXT = [29]u16{
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
};
// Offset base for distance codes 0..29
const DISTS = [30]u16{
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
};
// Extra bits for distance codes 0..29
const DEXT = [30]u16{
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
};
while (true) {
const symbol = try self.decode(lencode);
switch (symbol) {
0...255 => {
// Literal value
const c = @as(u8, @truncate(symbol));
if (self.window.append(c) == 0) {
self.state = .{ .CopyLit = c };
return false;
}
},
256 => {
// End of block symbol
return true;
},
257...285 => {
// Length/distance pair
const length_symbol = symbol - 257;
const length = LENS[length_symbol] +
@as(u16, @intCast(try self.readBits(LEXT[length_symbol])));
const distance_symbol = try self.decode(distcode);
const distance = DISTS[distance_symbol] +
@as(u16, @intCast(try self.readBits(DEXT[distance_symbol])));
if (distance > self.window.buf.len or distance > self.window.total_written)
return error.InvalidDistance;
const written = self.window.copyFrom(distance, length);
if (written != length) {
self.state = .{
.CopyFrom = .{
.distance = distance,
.length = length - @as(u16, @truncate(written)),
},
};
return false;
}
},
else => return error.InvalidFixedCode,
}
}
}
fn decode(self: *Self, h: *Huffman) !u16 {
// Using u32 instead of u16 to reduce the number of casts needed.
var prefix: u32 = 0;
// Fast path, read some bits and hope they're the prefix of some code.
// We can't read PREFIX_LUT_BITS as we don't want to read past the
// deflate stream end, use an incremental approach instead.
var code_len = h.min_code_len;
if (code_len == 0)
return error.OutOfCodes;
while (true) {
_ = try self.peekBits(code_len);
// Small optimization win, use as many bits as possible in the
// table lookup.
prefix = self.bits & ((1 << PREFIX_LUT_BITS) - 1);
const lut_entry = &h.prefix_lut[prefix];
// The code is longer than PREFIX_LUT_BITS!
if (lut_entry.len == 0)
break;
// If the code lenght doesn't increase we found a match.
if (lut_entry.len <= code_len) {
self.discardBits(code_len);
return lut_entry.symbol;
}
code_len = lut_entry.len;
}
// The sequence we've read is not a prefix of any code of length <=
// PREFIX_LUT_BITS, keep decoding it using a slower method.
prefix = try self.readBits(PREFIX_LUT_BITS);
// Speed up the decoding by starting from the first code length
// that's not covered by the table.
var len: usize = PREFIX_LUT_BITS + 1;
var first: usize = h.last_code;
var index: usize = h.last_index;
// Reverse the prefix so that the LSB becomes the MSB and make space
// for the next bit.
var code = bitReverse(u32, prefix, PREFIX_LUT_BITS + 1);
while (len <= MAXBITS) : (len += 1) {
code |= try self.readBits(1);
const count = h.count[len];
if (code < first + count) {
return h.symbol[index + (code - first)];
}
index += count;
first += count;
first <<= 1;
code <<= 1;
}
return error.OutOfCodes;
}
fn step(self: *Self) !void {
while (true) {
switch (self.state) {
.DecodeBlockHeader => {
// The compressed stream is done.
if (self.seen_eos) return;
const last = @as(u1, @intCast(try self.readBits(1)));
const kind = @as(u2, @intCast(try self.readBits(2)));
self.seen_eos = last != 0;
// The next state depends on the block type.
switch (kind) {
0 => try self.stored(),
1 => try self.fixed(),
2 => try self.dynamic(),
3 => return error.InvalidBlockType,
}
},
.DecodeBlockData => {
if (!try self.codes(self.hlen, self.hdist)) {
return;
}
self.state = .DecodeBlockHeader;
},
.Copy => |*length| {
const N = math.min(self.window.writable(), length.*);
// TODO: This loop can be more efficient. On the other
// hand uncompressed blocks are not that common so...
var i: usize = 0;
while (i < N) : (i += 1) {
var tmp: [1]u8 = undefined;
if ((try self.inner_reader.read(&tmp)) != 1) {
// Unexpected end of stream, keep this error
// consistent with the use of readBitsNoEof.
return error.EndOfStream;
}
self.window.appendUnsafe(tmp[0]);
}
if (N != length.*) {
length.* -= N;
return;
}
self.state = .DecodeBlockHeader;
},
.CopyLit => |c| {
if (self.window.append(c) == 0) {
return;
}
self.state = .DecodeBlockData;
},
.CopyFrom => |*info| {
const written = self.window.copyFrom(info.distance, info.length);
if (written != info.length) {
info.length -= @as(u16, @truncate(written));
return;
}
self.state = .DecodeBlockData;
},
}
}
}
fn init(source: ReaderType, window_slice: []u8) Self {
assert(math.isPowerOfTwo(window_slice.len));
return Self{
.inner_reader = source,
.window = .{ .buf = window_slice },
.seen_eos = false,
.state = .DecodeBlockHeader,
.hdist = undefined,
.hlen = undefined,
.bits = 0,
.bits_left = 0,
};
}
// Implements the io.Reader interface
pub fn read(self: *Self, buffer: []u8) Error!usize {
if (buffer.len == 0)
return 0;
// Try reading as much as possible from the window
var read_amt: usize = self.window.read(buffer);
while (read_amt < buffer.len) {
// Run the state machine, we can detect the "effective" end of
// stream condition by checking if any progress was made.
// Why "effective"? Because even though `seen_eos` is true we
// may still have to finish processing other decoding steps.
try self.step();
// No progress was made
if (self.window.readable() == 0)
break;
read_amt += self.window.read(buffer[read_amt..]);
}
return read_amt;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn inflateStream(reader: anytype, window_slice: []u8) InflateStream(@TypeOf(reader)) {
return InflateStream(@TypeOf(reader)).init(reader, window_slice);
}
test "lengths overflow" {
// malformed final dynamic block, tries to write 321 code lengths (MAXCODES is 316)
// f dy hlit hdist hclen 16 17 18 0 (18) x138 (18) x138 (18) x39 (16) x6
// 1 10 11101 11101 0000 010 010 010 010 (11) 1111111 (11) 1111111 (11) 0011100 (01) 11
const stream = [_]u8{ 0b11101101, 0b00011101, 0b00100100, 0b11101001, 0b11111111, 0b11111111, 0b00111001, 0b00001110 };
try std.testing.expectError(error.InvalidLength, testInflate(stream[0..]));
}
test "empty distance alphabet" {
// dynamic block with empty distance alphabet is valid if only literals and end of data symbol are used
// f dy hlit hdist hclen 16 17 18 0 8 7 9 6 10 5 11 4 12 3 13 2 14 1 15 (18) x128 (18) x128 (1) ( 0) (256)
// 1 10 00000 00000 1111 000 000 010 010 000 000 000 000 000 000 000 000 000 000 000 000 000 001 000 (11) 1110101 (11) 1110101 (0) (10) (0)
const stream = [_]u8{ 0b00000101, 0b11100000, 0b00000001, 0b00001001, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00010000, 0b01011100, 0b10111111, 0b00101110 };
try testInflate(stream[0..]);
}
test "distance past beginning of output stream" {
// f fx ('A') ('B') ('C') <len=4, dist=4> (end)
// 1 01 (01110001) (01110010) (01110011) (0000010) (00011) (0000000)
const stream = [_]u8{ 0b01110011, 0b01110100, 0b01110010, 0b00000110, 0b01100001, 0b00000000 };
try std.testing.expectError(error.InvalidDistance, testInflate(stream[0..]));
}
test "inflateStream fuzzing" {
// see https://github.com/ziglang/zig/issues/9842
try std.testing.expectError(error.EndOfStream, testInflate("\x95\x90=o\xc20\x10\x86\xf30"));
try std.testing.expectError(error.OutOfCodes, testInflate("\x950\x00\x0000000"));
// Huffman.construct errors
// lencode
try std.testing.expectError(error.InvalidTree, testInflate("\x950000"));
try std.testing.expectError(error.InvalidTree, testInflate("\x05000"));
// hlen
try std.testing.expectError(error.InvalidTree, testInflate("\x05\xea\x01\t\x00\x00\x00\x01\x00\\\xbf.\t\x00"));
// hdist
try std.testing.expectError(error.InvalidTree, testInflate("\x05\xe0\x01A\x00\x00\x00\x00\x10\\\xbf."));
// Huffman.construct -> error.IncompleteSet returns that shouldn't give error.InvalidTree
// (like the "empty distance alphabet" test but for ndist instead of nlen)
try std.testing.expectError(error.EndOfStream, testInflate("\x05\xe0\x01\t\x00\x00\x00\x00\x10\\\xbf\xce"));
try testInflate("\x15\xe0\x01\t\x00\x00\x00\x00\x10\\\xbf.0");
}
fn testInflate(data: []const u8) !void {
var window: [0x8000]u8 = undefined;
const reader = std.io.fixedBufferStream(data).reader();
var inflate = inflateStream(reader, &window);
var inflated = try inflate.reader().readAllAlloc(std.testing.allocator, std.math.maxInt(usize));
defer std.testing.allocator.free(inflated);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/compress/gzip.zig | //
// Decompressor for GZIP data streams (RFC1952)
const std = @import("std");
const io = std.io;
const fs = std.fs;
const testing = std.testing;
const mem = std.mem;
const deflate = std.compress.deflate;
// Flags for the FLG field in the header
const FTEXT = 1 << 0;
const FHCRC = 1 << 1;
const FEXTRA = 1 << 2;
const FNAME = 1 << 3;
const FCOMMENT = 1 << 4;
pub fn GzipStream(comptime ReaderType: type) type {
return struct {
const Self = @This();
pub const Error = ReaderType.Error ||
deflate.InflateStream(ReaderType).Error ||
error{ CorruptedData, WrongChecksum };
pub const Reader = io.Reader(*Self, Error, read);
allocator: *mem.Allocator,
inflater: deflate.InflateStream(ReaderType),
in_reader: ReaderType,
hasher: std.hash.Crc32,
window_slice: []u8,
read_amt: usize,
info: struct {
filename: ?[]const u8,
comment: ?[]const u8,
modification_time: u32,
},
fn init(allocator: *mem.Allocator, source: ReaderType) !Self {
// gzip header format is specified in RFC1952
const header = try source.readBytesNoEof(10);
// Check the ID1/ID2 fields
if (header[0] != 0x1f or header[1] != 0x8b)
return error.BadHeader;
const CM = header[2];
// The CM field must be 8 to indicate the use of DEFLATE
if (CM != 8) return error.InvalidCompression;
// Flags
const FLG = header[3];
// Modification time, as a Unix timestamp.
// If zero there's no timestamp available.
const MTIME = mem.readIntLittle(u32, header[4..8]);
// Extra flags
const XFL = header[8];
// Operating system where the compression took place
const OS = header[9];
_ = XFL;
_ = OS;
if (FLG & FEXTRA != 0) {
// Skip the extra data, we could read and expose it to the user
// if somebody needs it.
const len = try source.readIntLittle(u16);
try source.skipBytes(len, .{});
}
var filename: ?[]const u8 = null;
if (FLG & FNAME != 0) {
filename = try source.readUntilDelimiterAlloc(
allocator,
0,
std.math.maxInt(usize),
);
}
errdefer if (filename) |p| allocator.free(p);
var comment: ?[]const u8 = null;
if (FLG & FCOMMENT != 0) {
comment = try source.readUntilDelimiterAlloc(
allocator,
0,
std.math.maxInt(usize),
);
}
errdefer if (comment) |p| allocator.free(p);
if (FLG & FHCRC != 0) {
// TODO: Evaluate and check the header checksum. The stdlib has
// no CRC16 yet :(
_ = try source.readIntLittle(u16);
}
// The RFC doesn't say anything about the DEFLATE window size to be
// used, default to 32K.
var window_slice = try allocator.alloc(u8, 32 * 1024);
return Self{
.allocator = allocator,
.inflater = deflate.inflateStream(source, window_slice),
.in_reader = source,
.hasher = std.hash.Crc32.init(),
.window_slice = window_slice,
.info = .{
.filename = filename,
.comment = comment,
.modification_time = MTIME,
},
.read_amt = 0,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.window_slice);
if (self.info.filename) |filename|
self.allocator.free(filename);
if (self.info.comment) |comment|
self.allocator.free(comment);
}
// Implements the io.Reader interface
pub fn read(self: *Self, buffer: []u8) Error!usize {
if (buffer.len == 0)
return 0;
// Read from the compressed stream and update the computed checksum
const r = try self.inflater.read(buffer);
if (r != 0) {
self.hasher.update(buffer[0..r]);
self.read_amt += r;
return r;
}
// We've reached the end of stream, check if the checksum matches
const hash = try self.in_reader.readIntLittle(u32);
if (hash != self.hasher.final())
return error.WrongChecksum;
// The ISIZE field is the size of the uncompressed input modulo 2^32
const input_size = try self.in_reader.readIntLittle(u32);
if (self.read_amt & 0xffffffff != input_size)
return error.CorruptedData;
return 0;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn gzipStream(allocator: *mem.Allocator, reader: anytype) !GzipStream(@TypeOf(reader)) {
return GzipStream(@TypeOf(reader)).init(allocator, reader);
}
fn testReader(data: []const u8, comptime expected: []const u8) !void {
var in_stream = io.fixedBufferStream(data);
var gzip_stream = try gzipStream(testing.allocator, in_stream.reader());
defer gzip_stream.deinit();
// Read and decompress the whole file
const buf = try gzip_stream.reader().readAllAlloc(testing.allocator, std.math.maxInt(usize));
defer testing.allocator.free(buf);
// Calculate its SHA256 hash and check it against the reference
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(buf, hash[0..], .{});
try assertEqual(expected, &hash);
}
// Assert `expected` == `input` where `input` is a bytestring.
pub fn assertEqual(comptime expected: []const u8, input: []const u8) !void {
var expected_bytes: [expected.len / 2]u8 = undefined;
for (expected_bytes, 0..) |*r, i| {
r.* = std.fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
}
try testing.expectEqualSlices(u8, &expected_bytes, input);
}
// All the test cases are obtained by compressing the RFC1952 text
//
// https://tools.ietf.org/rfc/rfc1952.txt length=25037 bytes
// SHA256=164ef0897b4cbec63abf1b57f069f3599bd0fb7c72c2a4dee21bd7e03ec9af67
test "compressed data" {
try testReader(
@embedFile("rfc1952.txt.gz"),
"164ef0897b4cbec63abf1b57f069f3599bd0fb7c72c2a4dee21bd7e03ec9af67",
);
}
test "sanity checks" {
// Truncated header
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{ 0x1f, 0x8B }, ""),
);
// Wrong CM
try testing.expectError(
error.InvalidCompression,
testReader(&[_]u8{
0x1f, 0x8b, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03,
}, ""),
);
// Wrong checksum
try testing.expectError(
error.WrongChecksum,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00,
}, ""),
);
// Truncated checksum
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00,
}, ""),
);
// Wrong initial size
try testing.expectError(
error.CorruptedData,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
}, ""),
);
// Truncated initial size field
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00,
}, ""),
);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/hermit.zig | const std = @import("std");
const maxInt = std.math.maxInt;
pub const pthread_mutex_t = extern struct {
inner: usize = ~@as(usize, 0),
};
pub const pthread_cond_t = extern struct {
inner: usize = ~@as(usize, 0),
};
pub const pthread_rwlock_t = extern struct {
ptr: usize = maxInt(usize),
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/openbsd.zig | const std = @import("../std.zig");
const maxInt = std.math.maxInt;
const builtin = @import("builtin");
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
extern "c" fn __errno() *c_int;
pub const _errno = __errno;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
pub extern "c" fn getthrid() pid_t;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub const pthread_mutex_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_cond_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_rwlock_t = extern struct {
ptr: ?*anyopaque = null,
};
pub const pthread_spinlock_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_attr_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_key_t = c_int;
pub const sem_t = ?*opaque {};
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub extern "c" fn pledge(promises: ?[*:0]const u8, execpromises: ?[*:0]const u8) c_int;
pub extern "c" fn unveil(path: ?[*:0]const u8, permissions: ?[*:0]const u8) c_int;
pub extern "c" fn pthread_set_name_np(thread: std.c.pthread_t, name: [*:0]const u8) void;
pub extern "c" fn pthread_get_name_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) void;
pub const blkcnt_t = i64;
pub const blksize_t = i32;
pub const clock_t = i64;
pub const dev_t = i32;
pub const fd_t = c_int;
pub const gid_t = u32;
pub const ino_t = u64;
pub const mode_t = u32;
pub const nlink_t = u32;
pub const off_t = i64;
pub const pid_t = i32;
pub const socklen_t = u32;
pub const time_t = i64;
pub const uid_t = u32;
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: c_short,
flags: u16,
fflags: c_uint,
data: i64,
udata: usize,
};
// Modes and flags for dlopen()
// include/dlfcn.h
pub const RTLD = struct {
/// Bind function calls lazily.
pub const LAZY = 1;
/// Bind function calls immediately.
pub const NOW = 2;
/// Make symbols globally available.
pub const GLOBAL = 0x100;
/// Opposite of GLOBAL, and the default.
pub const LOCAL = 0x000;
/// Trace loaded objects and exit.
pub const TRACE = 0x200;
};
pub const dl_phdr_info = extern struct {
dlpi_addr: std.elf.Addr,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: std.elf.Half,
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: c_short,
l_whence: c_short,
};
pub const addrinfo = extern struct {
flags: c_int,
family: c_int,
socktype: c_int,
protocol: c_int,
addrlen: socklen_t,
addr: ?*sockaddr,
canonname: ?[*:0]u8,
next: ?*addrinfo,
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = -9,
/// name could not be resolved at this time
AGAIN = -3,
/// flags parameter had an invalid value
BADFLAGS = -1,
/// non-recoverable failure in name resolution
FAIL = -4,
/// address family not recognized
FAMILY = -6,
/// memory allocation failure
MEMORY = -10,
/// no address associated with hostname
NODATA = -5,
/// name does not resolve
NONAME = -2,
/// service not recognized for socket type
SERVICE = -8,
/// intended socket type was not recognized
SOCKTYPE = -7,
/// system error returned in errno
SYSTEM = -11,
/// invalid value for hints
BADHINTS = -12,
/// resolved protocol is unknown
PROTOCOL = -13,
/// argument buffer overflow
OVERFLOW = -14,
_,
};
pub const EAI_MAX = 15;
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: c_uint,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: c_int,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: c_uint,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: c_int,
};
pub const Stat = extern struct {
mode: mode_t,
dev: dev_t,
ino: ino_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
size: off_t,
blocks: blkcnt_t,
blksize: blksize_t,
flags: u32,
gen: u32,
birthtim: timespec,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: time_t,
tv_nsec: c_long,
};
pub const timeval = extern struct {
tv_sec: time_t,
tv_usec: c_long,
};
pub const timezone = extern struct {
tz_minuteswest: c_int,
tz_dsttime: c_int,
};
pub const MAXNAMLEN = 255;
pub const dirent = extern struct {
d_fileno: ino_t,
d_off: off_t,
d_reclen: u16,
d_type: u8,
d_namlen: u8,
__d_padding: [4]u8,
d_name: [MAXNAMLEN + 1]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const sockaddr = extern struct {
/// total length
len: u8,
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 256;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// Definitions for UNIX IPC domain.
pub const un = extern struct {
/// total sockaddr length
len: u8 = @sizeOf(un),
family: sa_family_t = AF.LOCAL,
/// path name
path: [104]u8,
};
};
pub const AI = struct {
/// get address to use bind()
pub const PASSIVE = 1;
/// fill ai_canonname
pub const CANONNAME = 2;
/// prevent host name resolution
pub const NUMERICHOST = 4;
/// prevent service name resolution
pub const NUMERICSERV = 16;
/// only if any address is assigned
pub const ADDRCONFIG = 64;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const PROCESS_CPUTIME_ID = 2;
pub const MONOTONIC = 3;
pub const THREAD_CPUTIME_ID = 4;
};
pub const MAP = struct {
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const FIXED = 0x0010;
pub const RENAME = 0;
pub const NORESERVE = 0;
pub const INHERIT = 0;
pub const HASSEMAPHORE = 0;
pub const TRYFIXED = 0;
pub const FILE = 0;
pub const ANON = 0x1000;
pub const ANONYMOUS = ANON;
pub const STACK = 0x4000;
pub const CONCEAL = 0x8000;
};
pub const W = struct {
pub const NOHANG = 1;
pub const UNTRACED = 2;
pub const CONTINUED = 8;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast((s >> 8) & 0xff));
}
pub fn TERMSIG(s: u32) u32 {
return (s & 0x7f);
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFCONTINUED(s: u32) bool {
return ((s & 0o177777) == 0o177777);
}
pub fn IFSTOPPED(s: u32) bool {
return (s & 0xff == 0o177);
}
pub fn IFSIGNALED(s: u32) bool {
return (((s) & 0o177) != 0o177) and (((s) & 0o177) != 0);
}
};
pub const SA = struct {
pub const ONSTACK = 0x0001;
pub const RESTART = 0x0002;
pub const RESETHAND = 0x0004;
pub const NOCLDSTOP = 0x0008;
pub const NODEFER = 0x0010;
pub const NOCLDWAIT = 0x0020;
pub const SIGINFO = 0x0040;
};
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
/// open for reading only
pub const RDONLY = 0x00000000;
/// open for writing only
pub const WRONLY = 0x00000001;
/// open for reading and writing
pub const RDWR = 0x00000002;
/// mask for above modes
pub const ACCMODE = 0x00000003;
/// no delay
pub const NONBLOCK = 0x00000004;
/// set append mode
pub const APPEND = 0x00000008;
/// open with shared file lock
pub const SHLOCK = 0x00000010;
/// open with exclusive file lock
pub const EXLOCK = 0x00000020;
/// signal pgrp when data ready
pub const ASYNC = 0x00000040;
/// synchronous writes
pub const SYNC = 0x00000080;
/// don't follow symlinks on the last
pub const NOFOLLOW = 0x00000100;
/// create if nonexistent
pub const CREAT = 0x00000200;
/// truncate to zero length
pub const TRUNC = 0x00000400;
/// error if already exists
pub const EXCL = 0x00000800;
/// don't assign controlling terminal
pub const NOCTTY = 0x00008000;
/// write: I/O data completion
pub const DSYNC = SYNC;
/// read: I/O completion as for write
pub const RSYNC = SYNC;
/// fail if not a directory
pub const DIRECTORY = 0x20000;
/// set close on exec
pub const CLOEXEC = 0x10000;
};
pub const F = struct {
pub const DUPFD = 0;
pub const GETFD = 1;
pub const SETFD = 2;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 7;
pub const SETLK = 8;
pub const SETLKW = 9;
pub const RDLCK = 1;
pub const UNLCK = 2;
pub const WRLCK = 3;
};
pub const LOCK = struct {
pub const SH = 0x01;
pub const EX = 0x02;
pub const NB = 0x04;
pub const UN = 0x08;
};
pub const FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const CLOEXEC = 0x8000;
pub const NONBLOCK = 0x4000;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const TIMESTAMP = 0x0800;
pub const BINDANY = 0x1000;
pub const ZEROIZE = 0x2000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const NETPROC = 0x1020;
pub const RTABLE = 0x1021;
pub const PEERCRED = 0x1022;
pub const SPLICE = 0x1023;
pub const DOMAIN = 0x1024;
pub const PROTOCOL = 0x1025;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = AF.UNIX;
pub const INET = AF.INET;
pub const APPLETALK = AF.APPLETALK;
pub const INET6 = AF.INET6;
pub const DECnet = AF.DECnet;
pub const KEY = AF.KEY;
pub const ROUTE = AF.ROUTE;
pub const SNA = AF.SNA;
pub const MPLS = AF.MPLS;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const ISDN = AF.ISDN;
pub const MAX = AF.MAX;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const UNIX = 1;
pub const LOCAL = UNIX;
pub const INET = 2;
pub const APPLETALK = 16;
pub const INET6 = 24;
pub const KEY = 30;
pub const ROUTE = 17;
pub const SNA = 11;
pub const MPLS = 33;
pub const BLUETOOTH = 32;
pub const ISDN = 26;
pub const MAX = 36;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14; // XXX
};
pub const EV_ADD = 0x0001;
pub const EV_DELETE = 0x0002;
pub const EV_ENABLE = 0x0004;
pub const EV_DISABLE = 0x0008;
pub const EV_ONESHOT = 0x0010;
pub const EV_CLEAR = 0x0020;
pub const EV_RECEIPT = 0x0040;
pub const EV_DISPATCH = 0x0080;
pub const EV_FLAG1 = 0x2000;
pub const EV_ERROR = 0x4000;
pub const EV_EOF = 0x8000;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
pub const EVFILT_AIO = -3;
pub const EVFILT_VNODE = -4;
pub const EVFILT_PROC = -5;
pub const EVFILT_SIGNAL = -6;
pub const EVFILT_TIMER = -7;
pub const EVFILT_EXCEPT = -9;
// data/hint flags for EVFILT_{READ|WRITE}
pub const NOTE_LOWAT = 0x0001;
pub const NOTE_EOF = 0x0002;
// data/hint flags for EVFILT_EXCEPT and EVFILT_{READ|WRITE}
pub const NOTE_OOB = 0x0004;
// data/hint flags for EVFILT_VNODE
pub const NOTE_DELETE = 0x0001;
pub const NOTE_WRITE = 0x0002;
pub const NOTE_EXTEND = 0x0004;
pub const NOTE_ATTRIB = 0x0008;
pub const NOTE_LINK = 0x0010;
pub const NOTE_RENAME = 0x0020;
pub const NOTE_REVOKE = 0x0040;
pub const NOTE_TRUNCATE = 0x0080;
// data/hint flags for EVFILT_PROC
pub const NOTE_EXIT = 0x80000000;
pub const NOTE_FORK = 0x40000000;
pub const NOTE_EXEC = 0x20000000;
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = 0xf0000000;
pub const NOTE_TRACK = 0x00000001;
pub const NOTE_TRACKERR = 0x00000002;
pub const NOTE_CHILD = 0x00000004;
// data/hint flags for EVFILT_DEVICE
pub const NOTE_CHANGE = 0x00000001;
pub const T = struct {
pub const IOCCBRK = 0x2000747a;
pub const IOCCDTR = 0x20007478;
pub const IOCCONS = 0x80047462;
pub const IOCDCDTIMESTAMP = 0x40107458;
pub const IOCDRAIN = 0x2000745e;
pub const IOCEXCL = 0x2000740d;
pub const IOCEXT = 0x80047460;
pub const IOCFLAG_CDTRCTS = 0x10;
pub const IOCFLAG_CLOCAL = 0x2;
pub const IOCFLAG_CRTSCTS = 0x4;
pub const IOCFLAG_MDMBUF = 0x8;
pub const IOCFLAG_SOFTCAR = 0x1;
pub const IOCFLUSH = 0x80047410;
pub const IOCGETA = 0x402c7413;
pub const IOCGETD = 0x4004741a;
pub const IOCGFLAGS = 0x4004745d;
pub const IOCGLINED = 0x40207442;
pub const IOCGPGRP = 0x40047477;
pub const IOCGQSIZE = 0x40047481;
pub const IOCGRANTPT = 0x20007447;
pub const IOCGSID = 0x40047463;
pub const IOCGSIZE = 0x40087468;
pub const IOCGWINSZ = 0x40087468;
pub const IOCMBIC = 0x8004746b;
pub const IOCMBIS = 0x8004746c;
pub const IOCMGET = 0x4004746a;
pub const IOCMSET = 0x8004746d;
pub const IOCM_CAR = 0x40;
pub const IOCM_CD = 0x40;
pub const IOCM_CTS = 0x20;
pub const IOCM_DSR = 0x100;
pub const IOCM_DTR = 0x2;
pub const IOCM_LE = 0x1;
pub const IOCM_RI = 0x80;
pub const IOCM_RNG = 0x80;
pub const IOCM_RTS = 0x4;
pub const IOCM_SR = 0x10;
pub const IOCM_ST = 0x8;
pub const IOCNOTTY = 0x20007471;
pub const IOCNXCL = 0x2000740e;
pub const IOCOUTQ = 0x40047473;
pub const IOCPKT = 0x80047470;
pub const IOCPKT_DATA = 0x0;
pub const IOCPKT_DOSTOP = 0x20;
pub const IOCPKT_FLUSHREAD = 0x1;
pub const IOCPKT_FLUSHWRITE = 0x2;
pub const IOCPKT_IOCTL = 0x40;
pub const IOCPKT_NOSTOP = 0x10;
pub const IOCPKT_START = 0x8;
pub const IOCPKT_STOP = 0x4;
pub const IOCPTMGET = 0x40287446;
pub const IOCPTSNAME = 0x40287448;
pub const IOCRCVFRAME = 0x80087445;
pub const IOCREMOTE = 0x80047469;
pub const IOCSBRK = 0x2000747b;
pub const IOCSCTTY = 0x20007461;
pub const IOCSDTR = 0x20007479;
pub const IOCSETA = 0x802c7414;
pub const IOCSETAF = 0x802c7416;
pub const IOCSETAW = 0x802c7415;
pub const IOCSETD = 0x8004741b;
pub const IOCSFLAGS = 0x8004745c;
pub const IOCSIG = 0x2000745f;
pub const IOCSLINED = 0x80207443;
pub const IOCSPGRP = 0x80047476;
pub const IOCSQSIZE = 0x80047480;
pub const IOCSSIZE = 0x80087467;
pub const IOCSTART = 0x2000746e;
pub const IOCSTAT = 0x80047465;
pub const IOCSTI = 0x80017472;
pub const IOCSTOP = 0x2000746f;
pub const IOCSWINSZ = 0x80087467;
pub const IOCUCNTL = 0x80047466;
pub const IOCXMTFRAME = 0x80087444;
};
pub const winsize = extern struct {
ws_row: c_ushort,
ws_col: c_ushort,
ws_xpixel: c_ushort,
ws_ypixel: c_ushort,
};
const NSIG = 33;
pub const SIG = struct {
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const CATCH = @as(?Sigaction.sigaction_fn, @ptrFromInt(2));
pub const HOLD = @as(?Sigaction.sigaction_fn, @ptrFromInt(3));
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const IO = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const INFO = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const PWR = 32;
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
/// signal mask to apply
mask: sigset_t,
/// signal options
flags: c_uint,
};
pub const sigval = extern union {
int: c_int,
ptr: ?*anyopaque,
};
pub const siginfo_t = extern struct {
signo: c_int,
code: c_int,
errno: c_int,
data: extern union {
proc: extern struct {
pid: pid_t,
pdata: extern union {
kill: extern struct {
uid: uid_t,
value: sigval,
},
cld: extern struct {
utime: clock_t,
stime: clock_t,
status: c_int,
},
},
},
fault: extern struct {
addr: ?*anyopaque,
trapno: c_int,
},
__pad: [128 - 3 * @sizeOf(c_int)]u8,
},
};
comptime {
if (@sizeOf(usize) == 4)
std.debug.assert(@sizeOf(siginfo_t) == 128)
else
// Take into account the padding between errno and data fields.
std.debug.assert(@sizeOf(siginfo_t) == 136);
}
const arch_bits = switch (builtin.cpu.arch) {
.x86_64 => struct {
pub const ucontext_t = extern struct {
sc_rdi: c_long,
sc_rsi: c_long,
sc_rdx: c_long,
sc_rcx: c_long,
sc_r8: c_long,
sc_r9: c_long,
sc_r10: c_long,
sc_r11: c_long,
sc_r12: c_long,
sc_r13: c_long,
sc_r14: c_long,
sc_r15: c_long,
sc_rbp: c_long,
sc_rbx: c_long,
sc_rax: c_long,
sc_gs: c_long,
sc_fs: c_long,
sc_es: c_long,
sc_ds: c_long,
sc_trapno: c_long,
sc_err: c_long,
sc_rip: c_long,
sc_cs: c_long,
sc_rflags: c_long,
sc_rsp: c_long,
sc_ss: c_long,
sc_fpstate: arch_bits.fxsave64,
__sc_unused: c_int,
sc_mask: c_int,
sc_cookie: c_long,
};
pub const fxsave64 = packed struct {
fx_fcw: u16,
fx_fsw: u16,
fx_ftw: u8,
fx_unused1: u8,
fx_fop: u16,
fx_rip: u64,
fx_rdp: u64,
fx_mxcsr: u32,
fx_mxcsr_mask: u32,
fx_st: [8][2]u64,
fx_xmm: [16][2]u64,
fx_unused3: [96]u8,
};
},
else => struct {},
};
pub const ucontext_t = arch_bits.ucontext_t;
pub const fxsave64 = arch_bits.fxsave64;
pub const sigset_t = c_uint;
pub const empty_sigset: sigset_t = 0;
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1, // Operation not permitted
NOENT = 2, // No such file or directory
SRCH = 3, // No such process
INTR = 4, // Interrupted system call
IO = 5, // Input/output error
NXIO = 6, // Device not configured
@"2BIG" = 7, // Argument list too long
NOEXEC = 8, // Exec format error
BADF = 9, // Bad file descriptor
CHILD = 10, // No child processes
DEADLK = 11, // Resource deadlock avoided
// 11 was AGAIN
NOMEM = 12, // Cannot allocate memory
ACCES = 13, // Permission denied
FAULT = 14, // Bad address
NOTBLK = 15, // Block device required
BUSY = 16, // Device busy
EXIST = 17, // File exists
XDEV = 18, // Cross-device link
NODEV = 19, // Operation not supported by device
NOTDIR = 20, // Not a directory
ISDIR = 21, // Is a directory
INVAL = 22, // Invalid argument
NFILE = 23, // Too many open files in system
MFILE = 24, // Too many open files
NOTTY = 25, // Inappropriate ioctl for device
TXTBSY = 26, // Text file busy
FBIG = 27, // File too large
NOSPC = 28, // No space left on device
SPIPE = 29, // Illegal seek
ROFS = 30, // Read-only file system
MLINK = 31, // Too many links
PIPE = 32, // Broken pipe
// math software
DOM = 33, // Numerical argument out of domain
RANGE = 34, // Result too large or too small
// non-blocking and interrupt i/o
// also: WOULDBLOCK: operation would block
AGAIN = 35, // Resource temporarily unavailable
INPROGRESS = 36, // Operation now in progress
ALREADY = 37, // Operation already in progress
// ipc/network software -- argument errors
NOTSOCK = 38, // Socket operation on non-socket
DESTADDRREQ = 39, // Destination address required
MSGSIZE = 40, // Message too long
PROTOTYPE = 41, // Protocol wrong type for socket
NOPROTOOPT = 42, // Protocol option not available
PROTONOSUPPORT = 43, // Protocol not supported
SOCKTNOSUPPORT = 44, // Socket type not supported
OPNOTSUPP = 45, // Operation not supported
PFNOSUPPORT = 46, // Protocol family not supported
AFNOSUPPORT = 47, // Address family not supported by protocol family
ADDRINUSE = 48, // Address already in use
ADDRNOTAVAIL = 49, // Can't assign requested address
// ipc/network software -- operational errors
NETDOWN = 50, // Network is down
NETUNREACH = 51, // Network is unreachable
NETRESET = 52, // Network dropped connection on reset
CONNABORTED = 53, // Software caused connection abort
CONNRESET = 54, // Connection reset by peer
NOBUFS = 55, // No buffer space available
ISCONN = 56, // Socket is already connected
NOTCONN = 57, // Socket is not connected
SHUTDOWN = 58, // Can't send after socket shutdown
TOOMANYREFS = 59, // Too many references: can't splice
TIMEDOUT = 60, // Operation timed out
CONNREFUSED = 61, // Connection refused
LOOP = 62, // Too many levels of symbolic links
NAMETOOLONG = 63, // File name too long
// should be rearranged
HOSTDOWN = 64, // Host is down
HOSTUNREACH = 65, // No route to host
NOTEMPTY = 66, // Directory not empty
// quotas & mush
PROCLIM = 67, // Too many processes
USERS = 68, // Too many users
DQUOT = 69, // Disc quota exceeded
// Network File System
STALE = 70, // Stale NFS file handle
REMOTE = 71, // Too many levels of remote in path
BADRPC = 72, // RPC struct is bad
RPCMISMATCH = 73, // RPC version wrong
PROGUNAVAIL = 74, // RPC prog. not avail
PROGMISMATCH = 75, // Program version wrong
PROCUNAVAIL = 76, // Bad procedure for program
NOLCK = 77, // No locks available
NOSYS = 78, // Function not implemented
FTYPE = 79, // Inappropriate file type or format
AUTH = 80, // Authentication error
NEEDAUTH = 81, // Need authenticator
IPSEC = 82, // IPsec processing failure
NOATTR = 83, // Attribute not found
// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
ILSEQ = 84, // Illegal byte sequence
NOMEDIUM = 85, // No medium found
MEDIUMTYPE = 86, // Wrong medium type
OVERFLOW = 87, // Value too large to be stored in data type
CANCELED = 88, // Operation canceled
IDRM = 89, // Identifier removed
NOMSG = 90, // No message of desired type
NOTSUP = 91, // Not supported
BADMSG = 92, // Bad or Corrupt message
NOTRECOVERABLE = 93, // State not recoverable
OWNERDEAD = 94, // Previous owner died
PROTO = 95, // Protocol error
_,
};
const _MAX_PAGE_SHIFT = switch (builtin.cpu.arch) {
.i386 => 12,
.sparcv9 => 13,
};
pub const MINSIGSTKSZ = 1 << _MAX_PAGE_SHIFT;
pub const SIGSTKSZ = MINSIGSTKSZ + (1 << _MAX_PAGE_SHIFT) * 4;
pub const SS_ONSTACK = 0x0001;
pub const SS_DISABLE = 0x0004;
pub const stack_t = extern struct {
sp: [*]u8,
size: usize,
flags: c_int,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
};
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = -100;
/// Check access using effective user and group ID
pub const EACCESS = 0x01;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x02;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x04;
/// Remove directory instead of file
pub const REMOVEDIR = 0x08;
};
pub const HOST_NAME_MAX = 255;
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// IP6 hop-by-hop options
pub const HOPOPTS = IP;
/// control message protocol
pub const ICMP = 1;
/// group mgmt protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IP header
pub const IPV4 = IPIP;
/// IP inside IP
pub const IPIP = 4;
/// tcp
pub const TCP = 6;
/// exterior gateway protocol
pub const EGP = 8;
/// pup
pub const PUP = 12;
/// user datagram protocol
pub const UDP = 17;
/// xns idp
pub const IDP = 22;
/// tp-4 w/ class negotiation
pub const TP = 29;
/// IP6 header
pub const IPV6 = 41;
/// IP6 routing header
pub const ROUTING = 43;
/// IP6 fragmentation header
pub const FRAGMENT = 44;
/// resource reservation
pub const RSVP = 46;
/// GRE encaps RFC 1701
pub const GRE = 47;
/// encap. security payload
pub const ESP = 50;
/// authentication header
pub const AH = 51;
/// IP Mobility RFC 2004
pub const MOBILE = 55;
/// IPv6 ICMP
pub const IPV6_ICMP = 58;
/// ICMP6
pub const ICMPV6 = 58;
/// IP6 no next header
pub const NONE = 59;
/// IP6 destination option
pub const DSTOPTS = 60;
/// ISO cnlp
pub const EON = 80;
/// Ethernet-in-IP
pub const ETHERIP = 97;
/// encapsulation header
pub const ENCAP = 98;
/// Protocol indep. multicast
pub const PIM = 103;
/// IP Payload Comp. Protocol
pub const IPCOMP = 108;
/// VRRP RFC 2338
pub const VRRP = 112;
/// Common Address Resolution Protocol
pub const CARP = 112;
/// PFSYNC
pub const PFSYNC = 240;
/// raw IP packet
pub const RAW = 255;
};
pub const rlimit_resource = enum(c_int) {
CPU,
FSIZE,
DATA,
STACK,
CORE,
RSS,
MEMLOCK,
NPROC,
NOFILE,
_,
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const nfds_t = c_uint;
pub const pollfd = extern struct {
fd: fd_t,
events: c_short,
revents: c_short,
};
pub const POLL = struct {
pub const IN = 0x0001;
pub const PRI = 0x0002;
pub const OUT = 0x0004;
pub const ERR = 0x0008;
pub const HUP = 0x0010;
pub const NVAL = 0x0020;
pub const RDNORM = 0x0040;
pub const NORM = RDNORM;
pub const WRNORM = OUT;
pub const RDBAND = 0x0080;
pub const WRBAND = 0x0100;
};
pub const CTL = struct {
pub const UNSPEC = 0;
pub const KERN = 1;
pub const VM = 2;
pub const FS = 3;
pub const NET = 4;
pub const DEBUG = 5;
pub const HW = 6;
pub const MACHDEP = 7;
pub const DDB = 9;
pub const VFS = 10;
};
pub const KERN = struct {
pub const OSTYPE = 1;
pub const OSRELEASE = 2;
pub const OSREV = 3;
pub const VERSION = 4;
pub const MAXVNODES = 5;
pub const MAXPROC = 6;
pub const MAXFILES = 7;
pub const ARGMAX = 8;
pub const SECURELVL = 9;
pub const HOSTNAME = 10;
pub const HOSTID = 11;
pub const CLOCKRATE = 12;
pub const PROF = 16;
pub const POSIX1 = 17;
pub const NGROUPS = 18;
pub const JOB_CONTROL = 19;
pub const SAVED_IDS = 20;
pub const BOOTTIME = 21;
pub const DOMAINNAME = 22;
pub const MAXPARTITIONS = 23;
pub const RAWPARTITION = 24;
pub const MAXTHREAD = 25;
pub const NTHREADS = 26;
pub const OSVERSION = 27;
pub const SOMAXCONN = 28;
pub const SOMINCONN = 29;
pub const NOSUIDCOREDUMP = 32;
pub const FSYNC = 33;
pub const SYSVMSG = 34;
pub const SYSVSEM = 35;
pub const SYSVSHM = 36;
pub const MSGBUFSIZE = 38;
pub const MALLOCSTATS = 39;
pub const CPTIME = 40;
pub const NCHSTATS = 41;
pub const FORKSTAT = 42;
pub const NSELCOLL = 43;
pub const TTY = 44;
pub const CCPU = 45;
pub const FSCALE = 46;
pub const NPROCS = 47;
pub const MSGBUF = 48;
pub const POOL = 49;
pub const STACKGAPRANDOM = 50;
pub const SYSVIPC_INFO = 51;
pub const ALLOWKMEM = 52;
pub const WITNESSWATCH = 53;
pub const SPLASSERT = 54;
pub const PROC_ARGS = 55;
pub const NFILES = 56;
pub const TTYCOUNT = 57;
pub const NUMVNODES = 58;
pub const MBSTAT = 59;
pub const WITNESS = 60;
pub const SEMINFO = 61;
pub const SHMINFO = 62;
pub const INTRCNT = 63;
pub const WATCHDOG = 64;
pub const ALLOWDT = 65;
pub const PROC = 66;
pub const MAXCLUSTERS = 67;
pub const EVCOUNT = 68;
pub const TIMECOUNTER = 69;
pub const MAXLOCKSPERUID = 70;
pub const CPTIME2 = 71;
pub const CACHEPCT = 72;
pub const FILE = 73;
pub const WXABORT = 74;
pub const CONSDEV = 75;
pub const NETLIVELOCKS = 76;
pub const POOL_DEBUG = 77;
pub const PROC_CWD = 78;
pub const PROC_NOBROADCASTKILL = 79;
pub const PROC_VMMAP = 80;
pub const GLOBAL_PTRACE = 81;
pub const CONSBUFSIZE = 82;
pub const CONSBUF = 83;
pub const AUDIO = 84;
pub const CPUSTATS = 85;
pub const PFSTATUS = 86;
pub const TIMEOUT_STATS = 87;
pub const UTC_OFFSET = 88;
pub const VIDEO = 89;
pub const PROC_ALL = 0;
pub const PROC_PID = 1;
pub const PROC_PGRP = 2;
pub const PROC_SESSION = 3;
pub const PROC_TTY = 4;
pub const PROC_UID = 5;
pub const PROC_RUID = 6;
pub const PROC_KTHREAD = 7;
pub const PROC_SHOW_THREADS = 0x40000000;
pub const PROC_ARGV = 1;
pub const PROC_NARGV = 2;
pub const PROC_ENV = 3;
pub const PROC_NENV = 4;
};
pub const HW_MACHINE = 1;
pub const HW_MODEL = 2;
pub const HW_NCPU = 3;
pub const HW_BYTEORDER = 4;
pub const HW_PHYSMEM = 5;
pub const HW_USERMEM = 6;
pub const HW_PAGESIZE = 7;
pub const HW_DISKNAMES = 8;
pub const HW_DISKSTATS = 9;
pub const HW_DISKCOUNT = 10;
pub const HW_SENSORS = 11;
pub const HW_CPUSPEED = 12;
pub const HW_SETPERF = 13;
pub const HW_VENDOR = 14;
pub const HW_PRODUCT = 15;
pub const HW_VERSION = 16;
pub const HW_SERIALNO = 17;
pub const HW_UUID = 18;
pub const HW_PHYSMEM64 = 19;
pub const HW_USERMEM64 = 20;
pub const HW_NCPUFOUND = 21;
pub const HW_ALLOWPOWERDOWN = 22;
pub const HW_PERFPOLICY = 23;
pub const HW_SMT = 24;
pub const HW_NCPUONLINE = 25;
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/wasi.zig | const std = @import("../std.zig");
const wasi = std.os.wasi;
const FDFLAG = wasi.FDFLAG;
extern threadlocal var errno: c_int;
pub fn _errno() *c_int {
return &errno;
}
pub const fd_t = wasi.fd_t;
pub const pid_t = c_int;
pub const uid_t = u32;
pub const gid_t = u32;
pub const off_t = i64;
pub const ino_t = wasi.ino_t;
pub const mode_t = wasi.mode_t;
pub const time_t = wasi.time_t;
pub const timespec = wasi.timespec;
pub const STDERR_FILENO = wasi.STDERR_FILENO;
pub const STDIN_FILENO = wasi.STDIN_FILENO;
pub const STDOUT_FILENO = wasi.STDOUT_FILENO;
pub const E = wasi.E;
pub const CLOCK = wasi.CLOCK;
pub const S = wasi.S;
pub const IOV_MAX = wasi.IOV_MAX;
pub const AT = wasi.AT;
pub const Stat = extern struct {
dev: i32,
ino: ino_t,
nlink: u64,
mode: mode_t,
uid: uid_t,
gid: gid_t,
__pad0: isize,
rdev: i32,
size: off_t,
blksize: i32,
blocks: i64,
atimesec: time_t,
atimensec: isize,
mtimesec: time_t,
mtimensec: isize,
ctimesec: time_t,
ctimensec: isize,
pub fn atime(self: @This()) timespec {
return timespec{
.tv_sec = self.atimesec,
.tv_nsec = self.atimensec,
};
}
pub fn mtime(self: @This()) timespec {
return timespec{
.tv_sec = self.mtimesec,
.tv_nsec = self.mtimensec,
};
}
pub fn ctime(self: @This()) timespec {
return timespec{
.tv_sec = self.ctimesec,
.tv_nsec = self.ctimensec,
};
}
};
/// Derived from
/// https://github.com/WebAssembly/wasi-libc/blob/main/expected/wasm32-wasi/predefined-macros.txt
pub const O = struct {
pub const ACCMODE = (EXEC | RDWR | SEARCH);
pub const APPEND = FDFLAG.APPEND;
pub const CLOEXEC = (0);
pub const CREAT = ((1 << 0) << 12); // = __WASI_OFLAGS_CREAT << 12
pub const DIRECTORY = ((1 << 1) << 12); // = __WASI_OFLAGS_DIRECTORY << 12
pub const DSYNC = FDFLAG.DSYNC;
pub const EXCL = ((1 << 2) << 12); // = __WASI_OFLAGS_EXCL << 12
pub const EXEC = (0x02000000);
pub const NOCTTY = (0);
pub const NOFOLLOW = (0x01000000);
pub const NONBLOCK = (1 << FDFLAG.NONBLOCK);
pub const RDONLY = (0x04000000);
pub const RDWR = (RDONLY | WRONLY);
pub const RSYNC = (1 << FDFLAG.RSYNC);
pub const SEARCH = (0x08000000);
pub const SYNC = (1 << FDFLAG.SYNC);
pub const TRUNC = ((1 << 3) << 12); // = __WASI_OFLAGS_TRUNC << 12
pub const TTY_INIT = (0);
pub const WRONLY = (0x10000000);
};
pub const SEEK = struct {
pub const SET: wasi.whence_t = .SET;
pub const CUR: wasi.whence_t = .CUR;
pub const END: wasi.whence_t = .END;
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/netbsd.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
const timezone = std.c.timezone;
const rusage = std.c.rusage;
extern "c" fn __errno() *c_int;
pub const _errno = __errno;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn _lwp_self() lwpid_t;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
pub extern "c" fn __fstat50(fd: fd_t, buf: *Stat) c_int;
pub const fstat = __fstat50;
pub extern "c" fn __stat50(path: [*:0]const u8, buf: *Stat) c_int;
pub const stat = __stat50;
pub extern "c" fn __clock_gettime50(clk_id: c_int, tp: *timespec) c_int;
pub const clock_gettime = __clock_gettime50;
pub extern "c" fn __clock_getres50(clk_id: c_int, tp: *timespec) c_int;
pub const clock_getres = __clock_getres50;
pub extern "c" fn __getdents30(fd: c_int, buf_ptr: [*]u8, nbytes: usize) c_int;
pub const getdents = __getdents30;
pub extern "c" fn __sigaltstack14(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub const sigaltstack = __sigaltstack14;
pub extern "c" fn __nanosleep50(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub const nanosleep = __nanosleep50;
pub extern "c" fn __sigaction14(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int;
pub const sigaction = __sigaction14;
pub extern "c" fn __sigprocmask14(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub const sigprocmask = __sigaction14;
pub extern "c" fn __socket30(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub const socket = __socket30;
pub extern "c" fn __gettimeofday50(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub const gettimeofday = __gettimeofday50;
pub extern "c" fn __getrusage50(who: c_int, usage: *rusage) c_int;
pub const getrusage = __getrusage50;
pub extern "c" fn __libc_thr_yield() c_int;
pub const sched_yield = __libc_thr_yield;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub const pthread_mutex_t = extern struct {
magic: u32 = 0x33330003,
errorcheck: padded_pthread_spin_t = 0,
ceiling: padded_pthread_spin_t = 0,
owner: usize = 0,
waiters: ?*u8 = null,
recursed: u32 = 0,
spare2: ?*anyopaque = null,
};
pub const pthread_cond_t = extern struct {
magic: u32 = 0x55550005,
lock: pthread_spin_t = 0,
waiters_first: ?*u8 = null,
waiters_last: ?*u8 = null,
mutex: ?*pthread_mutex_t = null,
private: ?*anyopaque = null,
};
pub const pthread_rwlock_t = extern struct {
magic: c_uint = 0x99990009,
interlock: switch (builtin.cpu.arch) {
.aarch64, .sparc, .x86_64, .i386 => u8,
.arm, .powerpc => c_int,
else => unreachable,
} = 0,
rblocked_first: ?*u8 = null,
rblocked_last: ?*u8 = null,
wblocked_first: ?*u8 = null,
wblocked_last: ?*u8 = null,
nreaders: c_uint = 0,
owner: std.c.pthread_t = null,
private: ?*anyopaque = null,
};
const pthread_spin_t = switch (builtin.cpu.arch) {
.aarch64, .aarch64_be, .aarch64_32 => u8,
.mips, .mipsel, .mips64, .mips64el => u32,
.powerpc, .powerpc64, .powerpc64le => i32,
.i386, .x86_64 => u8,
.arm, .armeb, .thumb, .thumbeb => i32,
.sparc, .sparcel, .sparcv9 => u8,
.riscv32, .riscv64 => u32,
else => @compileError("undefined pthread_spin_t for this arch"),
};
const padded_pthread_spin_t = switch (builtin.cpu.arch) {
.i386, .x86_64 => u32,
.sparc, .sparcel, .sparcv9 => u32,
else => pthread_spin_t,
};
pub const pthread_attr_t = extern struct {
pta_magic: u32,
pta_flags: i32,
pta_private: ?*anyopaque,
};
pub const sem_t = ?*opaque {};
pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*anyopaque) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub const blkcnt_t = i64;
pub const blksize_t = i32;
pub const clock_t = u32;
pub const dev_t = u64;
pub const fd_t = i32;
pub const gid_t = u32;
pub const ino_t = u64;
pub const mode_t = u32;
pub const nlink_t = u32;
pub const off_t = i64;
pub const pid_t = i32;
pub const socklen_t = u32;
pub const time_t = i64;
pub const uid_t = u32;
pub const lwpid_t = i32;
pub const suseconds_t = c_int;
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i32,
flags: u32,
fflags: u32,
data: i64,
udata: usize,
};
pub const RTLD = struct {
pub const LAZY = 1;
pub const NOW = 2;
pub const GLOBAL = 0x100;
pub const LOCAL = 0x200;
pub const NODELETE = 0x01000;
pub const NOLOAD = 0x02000;
pub const NEXT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -1)))));
pub const DEFAULT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -2)))));
pub const SELF = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -3)))));
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
/// The stat structure used by libc.
pub const Stat = extern struct {
dev: dev_t,
mode: mode_t,
ino: ino_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
birthtim: timespec,
size: off_t,
blocks: blkcnt_t,
blksize: blksize_t,
flags: u32,
gen: u32,
__spare: [2]u32,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: i64,
tv_nsec: isize,
};
pub const timeval = extern struct {
/// seconds
tv_sec: time_t,
/// microseconds
tv_usec: suseconds_t,
};
pub const MAXNAMLEN = 511;
pub const dirent = extern struct {
d_fileno: ino_t,
d_reclen: u16,
d_namlen: u16,
d_type: u8,
d_name: [MAXNAMLEN:0]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const CONN_DGRAM = 6;
pub const DCCP = CONN_DGRAM;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
pub const NOSIGPIPE = 0x40000000;
pub const FLAGS_MASK = 0xf0000000;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const NOSIGPIPE = 0x0800;
pub const ACCEPTFILTER = 0x1000;
pub const TIMESTAMP = 0x2000;
pub const RERROR = 0x4000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const OVERFLOWED = 0x1009;
pub const NOHEADER = 0x100a;
pub const SNDTIMEO = 0x100b;
pub const RCVTIMEO = 0x100c;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NS = AF.NS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const SNA = AF.SNA;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const OROUTE = AF.OROUTE;
pub const LINK = AF.LINK;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const INET6 = AF.INET6;
pub const IPX = AF.IPX;
pub const ISDN = AF.ISDN;
pub const E164 = AF.E164;
pub const NATM = AF.NATM;
pub const ARP = AF.ARP;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const MPLS = AF.MPLS;
pub const ROUTE = AF.ROUTE;
pub const CAN = AF.CAN;
pub const ETHER = AF.ETHER;
pub const MAX = AF.MAX;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const LOCAL = 1;
pub const UNIX = LOCAL;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const OROUTE = 17;
pub const LINK = 18;
pub const COIP = 20;
pub const CNT = 21;
pub const IPX = 23;
pub const INET6 = 24;
pub const ISDN = 26;
pub const E164 = ISDN;
pub const NATM = 27;
pub const ARP = 28;
pub const BLUETOOTH = 31;
pub const IEEE80211 = 32;
pub const MPLS = 33;
pub const ROUTE = 34;
pub const CAN = 35;
pub const ETHER = 36;
pub const MAX = 37;
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const sockaddr = extern struct {
/// total length
len: u8,
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// Definitions for UNIX IPC domain.
pub const un = extern struct {
/// total sockaddr length
len: u8 = @sizeOf(un),
family: sa_family_t = AF.LOCAL,
/// path name
path: [104]u8,
};
};
pub const AI = struct {
/// get address to use bind()
pub const PASSIVE = 0x00000001;
/// fill ai_canonname
pub const CANONNAME = 0x00000002;
/// prevent host name resolution
pub const NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const NUMERICSERV = 0x00000008;
/// only if any address is assigned
pub const ADDRCONFIG = 0x00000400;
};
pub const CTL = struct {
pub const KERN = 1;
pub const DEBUG = 5;
};
pub const KERN = struct {
pub const PROC_ARGS = 48; // struct: process argv/env
pub const PROC_PATHNAME = 5; // path to executable
pub const IOV_MAX = 38;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = KERN.IOV_MAX;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const VIRTUAL = 1;
pub const PROF = 2;
pub const MONOTONIC = 3;
pub const THREAD_CPUTIME_ID = 0x20000000;
pub const PROCESS_CPUTIME_ID = 0x40000000;
};
pub const MAP = struct {
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const REMAPDUP = 0x0004;
pub const FIXED = 0x0010;
pub const RENAME = 0x0020;
pub const NORESERVE = 0x0040;
pub const INHERIT = 0x0080;
pub const HASSEMAPHORE = 0x0200;
pub const TRYFIXED = 0x0400;
pub const WIRED = 0x0800;
pub const FILE = 0x0000;
pub const NOSYNC = 0x0800;
pub const ANON = 0x1000;
pub const ANONYMOUS = ANON;
pub const STACK = 0x2000;
};
pub const W = struct {
pub const NOHANG = 0x00000001;
pub const UNTRACED = 0x00000002;
pub const STOPPED = UNTRACED;
pub const CONTINUED = 0x00000010;
pub const NOWAIT = 0x00010000;
pub const EXITED = 0x00000020;
pub const TRAPPED = 0x00000040;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast((s >> 8) & 0xff));
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFCONTINUED(s: u32) bool {
return ((s & 0x7f) == 0xffff);
}
pub fn IFSTOPPED(s: u32) bool {
return ((s & 0x7f != 0x7f) and !IFCONTINUED(s));
}
pub fn IFSIGNALED(s: u32) bool {
return !IFSTOPPED(s) and !IFCONTINUED(s) and !IFEXITED(s);
}
};
pub const SA = struct {
pub const ONSTACK = 0x0001;
pub const RESTART = 0x0002;
pub const RESETHAND = 0x0004;
pub const NOCLDSTOP = 0x0008;
pub const NODEFER = 0x0010;
pub const NOCLDWAIT = 0x0020;
pub const SIGINFO = 0x0040;
};
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
/// open for reading only
pub const RDONLY = 0x00000000;
/// open for writing only
pub const WRONLY = 0x00000001;
/// open for reading and writing
pub const RDWR = 0x00000002;
/// mask for above modes
pub const ACCMODE = 0x00000003;
/// no delay
pub const NONBLOCK = 0x00000004;
/// set append mode
pub const APPEND = 0x00000008;
/// open with shared file lock
pub const SHLOCK = 0x00000010;
/// open with exclusive file lock
pub const EXLOCK = 0x00000020;
/// signal pgrp when data ready
pub const ASYNC = 0x00000040;
/// synchronous writes
pub const SYNC = 0x00000080;
/// don't follow symlinks on the last
pub const NOFOLLOW = 0x00000100;
/// create if nonexistent
pub const CREAT = 0x00000200;
/// truncate to zero length
pub const TRUNC = 0x00000400;
/// error if already exists
pub const EXCL = 0x00000800;
/// don't assign controlling terminal
pub const NOCTTY = 0x00008000;
/// write: I/O data completion
pub const DSYNC = 0x00010000;
/// read: I/O completion as for write
pub const RSYNC = 0x00020000;
/// use alternate i/o semantics
pub const ALT_IO = 0x00040000;
/// direct I/O hint
pub const DIRECT = 0x00080000;
/// fail if not a directory
pub const DIRECTORY = 0x00200000;
/// set close on exec
pub const CLOEXEC = 0x00400000;
/// skip search permission checks
pub const SEARCH = 0x00800000;
};
pub const F = struct {
pub const DUPFD = 0;
pub const GETFD = 1;
pub const SETFD = 2;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 7;
pub const SETLK = 8;
pub const SETLKW = 9;
pub const RDLCK = 1;
pub const WRLCK = 3;
pub const UNLCK = 2;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
pub const EVFILT_READ = 0;
pub const EVFILT_WRITE = 1;
/// attached to aio requests
pub const EVFILT_AIO = 2;
/// attached to vnodes
pub const EVFILT_VNODE = 3;
/// attached to struct proc
pub const EVFILT_PROC = 4;
/// attached to struct proc
pub const EVFILT_SIGNAL = 5;
/// timers
pub const EVFILT_TIMER = 6;
/// Filesystem events
pub const EVFILT_FS = 7;
/// User events
pub const EVFILT_USER = 1;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x08000000;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = 0xf0000000;
pub const T = struct {
pub const IOCCBRK = 0x2000747a;
pub const IOCCDTR = 0x20007478;
pub const IOCCONS = 0x80047462;
pub const IOCDCDTIMESTAMP = 0x40107458;
pub const IOCDRAIN = 0x2000745e;
pub const IOCEXCL = 0x2000740d;
pub const IOCEXT = 0x80047460;
pub const IOCFLAG_CDTRCTS = 0x10;
pub const IOCFLAG_CLOCAL = 0x2;
pub const IOCFLAG_CRTSCTS = 0x4;
pub const IOCFLAG_MDMBUF = 0x8;
pub const IOCFLAG_SOFTCAR = 0x1;
pub const IOCFLUSH = 0x80047410;
pub const IOCGETA = 0x402c7413;
pub const IOCGETD = 0x4004741a;
pub const IOCGFLAGS = 0x4004745d;
pub const IOCGLINED = 0x40207442;
pub const IOCGPGRP = 0x40047477;
pub const IOCGQSIZE = 0x40047481;
pub const IOCGRANTPT = 0x20007447;
pub const IOCGSID = 0x40047463;
pub const IOCGSIZE = 0x40087468;
pub const IOCGWINSZ = 0x40087468;
pub const IOCMBIC = 0x8004746b;
pub const IOCMBIS = 0x8004746c;
pub const IOCMGET = 0x4004746a;
pub const IOCMSET = 0x8004746d;
pub const IOCM_CAR = 0x40;
pub const IOCM_CD = 0x40;
pub const IOCM_CTS = 0x20;
pub const IOCM_DSR = 0x100;
pub const IOCM_DTR = 0x2;
pub const IOCM_LE = 0x1;
pub const IOCM_RI = 0x80;
pub const IOCM_RNG = 0x80;
pub const IOCM_RTS = 0x4;
pub const IOCM_SR = 0x10;
pub const IOCM_ST = 0x8;
pub const IOCNOTTY = 0x20007471;
pub const IOCNXCL = 0x2000740e;
pub const IOCOUTQ = 0x40047473;
pub const IOCPKT = 0x80047470;
pub const IOCPKT_DATA = 0x0;
pub const IOCPKT_DOSTOP = 0x20;
pub const IOCPKT_FLUSHREAD = 0x1;
pub const IOCPKT_FLUSHWRITE = 0x2;
pub const IOCPKT_IOCTL = 0x40;
pub const IOCPKT_NOSTOP = 0x10;
pub const IOCPKT_START = 0x8;
pub const IOCPKT_STOP = 0x4;
pub const IOCPTMGET = 0x40287446;
pub const IOCPTSNAME = 0x40287448;
pub const IOCRCVFRAME = 0x80087445;
pub const IOCREMOTE = 0x80047469;
pub const IOCSBRK = 0x2000747b;
pub const IOCSCTTY = 0x20007461;
pub const IOCSDTR = 0x20007479;
pub const IOCSETA = 0x802c7414;
pub const IOCSETAF = 0x802c7416;
pub const IOCSETAW = 0x802c7415;
pub const IOCSETD = 0x8004741b;
pub const IOCSFLAGS = 0x8004745c;
pub const IOCSIG = 0x2000745f;
pub const IOCSLINED = 0x80207443;
pub const IOCSPGRP = 0x80047476;
pub const IOCSQSIZE = 0x80047480;
pub const IOCSSIZE = 0x80087467;
pub const IOCSTART = 0x2000746e;
pub const IOCSTAT = 0x80047465;
pub const IOCSTI = 0x80017472;
pub const IOCSTOP = 0x2000746f;
pub const IOCSWINSZ = 0x80087467;
pub const IOCUCNTL = 0x80047466;
pub const IOCXMTFRAME = 0x80087444;
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
const NSIG = 32;
pub const SIG = struct {
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const WORDS = 4;
pub const MAXSIG = 128;
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const IO = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const INFO = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const PWR = 32;
pub const RTMIN = 33;
pub const RTMAX = 63;
pub inline fn IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn WORD(sig: usize) usize {
return IDX(sig) >> 5;
}
pub inline fn BIT(sig: usize) usize {
return 1 << (IDX(sig) & 31);
}
pub inline fn VALID(sig: usize) usize {
return sig <= MAXSIG and sig > 0;
}
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
/// signal mask to apply
mask: sigset_t,
/// signal options
flags: c_uint,
};
pub const sigval_t = extern union {
int: i32,
ptr: ?*anyopaque,
};
pub const siginfo_t = extern union {
pad: [128]u8,
info: _ksiginfo,
};
pub const _ksiginfo = extern struct {
signo: i32,
code: i32,
errno: i32,
// 64bit architectures insert 4bytes of padding here, this is done by
// correctly aligning the reason field
reason: extern union {
rt: extern struct {
pid: pid_t,
uid: uid_t,
value: sigval_t,
},
child: extern struct {
pid: pid_t,
uid: uid_t,
status: i32,
utime: clock_t,
stime: clock_t,
},
fault: extern struct {
addr: ?*anyopaque,
trap: i32,
trap2: i32,
trap3: i32,
},
poll: extern struct {
band: i32,
fd: i32,
},
syscall: extern struct {
sysnum: i32,
retval: [2]i32,
@"error": i32,
args: [8]u64,
},
ptrace_state: extern struct {
pe_report_event: i32,
option: extern union {
pe_other_pid: pid_t,
pe_lwp: lwpid_t,
},
},
} align(@sizeOf(usize)),
};
pub const sigset_t = extern struct {
__bits: [SIG.WORDS]u32,
};
pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** SIG.WORDS };
// XXX x86_64 specific
pub const mcontext_t = extern struct {
gregs: [26]u64,
mc_tlsbase: u64,
fpregs: [512]u8 align(8),
};
pub const REG = struct {
pub const RBP = 12;
pub const RIP = 21;
pub const RSP = 24;
};
pub const ucontext_t = extern struct {
flags: u32,
link: ?*ucontext_t,
sigmask: sigset_t,
stack: stack_t,
mcontext: mcontext_t,
__pad: [
switch (builtin.cpu.arch) {
.i386 => 4,
.mips, .mipsel, .mips64, .mips64el => 14,
.arm, .armeb, .thumb, .thumbeb => 1,
.sparc, .sparcel, .sparcv9 => if (@sizeOf(usize) == 4) 43 else 8,
else => 0,
}
]u32,
};
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1, // Operation not permitted
NOENT = 2, // No such file or directory
SRCH = 3, // No such process
INTR = 4, // Interrupted system call
IO = 5, // Input/output error
NXIO = 6, // Device not configured
@"2BIG" = 7, // Argument list too long
NOEXEC = 8, // Exec format error
BADF = 9, // Bad file descriptor
CHILD = 10, // No child processes
DEADLK = 11, // Resource deadlock avoided
// 11 was AGAIN
NOMEM = 12, // Cannot allocate memory
ACCES = 13, // Permission denied
FAULT = 14, // Bad address
NOTBLK = 15, // Block device required
BUSY = 16, // Device busy
EXIST = 17, // File exists
XDEV = 18, // Cross-device link
NODEV = 19, // Operation not supported by device
NOTDIR = 20, // Not a directory
ISDIR = 21, // Is a directory
INVAL = 22, // Invalid argument
NFILE = 23, // Too many open files in system
MFILE = 24, // Too many open files
NOTTY = 25, // Inappropriate ioctl for device
TXTBSY = 26, // Text file busy
FBIG = 27, // File too large
NOSPC = 28, // No space left on device
SPIPE = 29, // Illegal seek
ROFS = 30, // Read-only file system
MLINK = 31, // Too many links
PIPE = 32, // Broken pipe
// math software
DOM = 33, // Numerical argument out of domain
RANGE = 34, // Result too large or too small
// non-blocking and interrupt i/o
// also: WOULDBLOCK: operation would block
AGAIN = 35, // Resource temporarily unavailable
INPROGRESS = 36, // Operation now in progress
ALREADY = 37, // Operation already in progress
// ipc/network software -- argument errors
NOTSOCK = 38, // Socket operation on non-socket
DESTADDRREQ = 39, // Destination address required
MSGSIZE = 40, // Message too long
PROTOTYPE = 41, // Protocol wrong type for socket
NOPROTOOPT = 42, // Protocol option not available
PROTONOSUPPORT = 43, // Protocol not supported
SOCKTNOSUPPORT = 44, // Socket type not supported
OPNOTSUPP = 45, // Operation not supported
PFNOSUPPORT = 46, // Protocol family not supported
AFNOSUPPORT = 47, // Address family not supported by protocol family
ADDRINUSE = 48, // Address already in use
ADDRNOTAVAIL = 49, // Can't assign requested address
// ipc/network software -- operational errors
NETDOWN = 50, // Network is down
NETUNREACH = 51, // Network is unreachable
NETRESET = 52, // Network dropped connection on reset
CONNABORTED = 53, // Software caused connection abort
CONNRESET = 54, // Connection reset by peer
NOBUFS = 55, // No buffer space available
ISCONN = 56, // Socket is already connected
NOTCONN = 57, // Socket is not connected
SHUTDOWN = 58, // Can't send after socket shutdown
TOOMANYREFS = 59, // Too many references: can't splice
TIMEDOUT = 60, // Operation timed out
CONNREFUSED = 61, // Connection refused
LOOP = 62, // Too many levels of symbolic links
NAMETOOLONG = 63, // File name too long
// should be rearranged
HOSTDOWN = 64, // Host is down
HOSTUNREACH = 65, // No route to host
NOTEMPTY = 66, // Directory not empty
// quotas & mush
PROCLIM = 67, // Too many processes
USERS = 68, // Too many users
DQUOT = 69, // Disc quota exceeded
// Network File System
STALE = 70, // Stale NFS file handle
REMOTE = 71, // Too many levels of remote in path
BADRPC = 72, // RPC struct is bad
RPCMISMATCH = 73, // RPC version wrong
PROGUNAVAIL = 74, // RPC prog. not avail
PROGMISMATCH = 75, // Program version wrong
PROCUNAVAIL = 76, // Bad procedure for program
NOLCK = 77, // No locks available
NOSYS = 78, // Function not implemented
FTYPE = 79, // Inappropriate file type or format
AUTH = 80, // Authentication error
NEEDAUTH = 81, // Need authenticator
// SystemV IPC
IDRM = 82, // Identifier removed
NOMSG = 83, // No message of desired type
OVERFLOW = 84, // Value too large to be stored in data type
// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
ILSEQ = 85, // Illegal byte sequence
// From IEEE Std 1003.1-2001
// Base, Realtime, Threads or Thread Priority Scheduling option errors
NOTSUP = 86, // Not supported
// Realtime option errors
CANCELED = 87, // Operation canceled
// Realtime, XSI STREAMS option errors
BADMSG = 88, // Bad or Corrupt message
// XSI STREAMS option errors
NODATA = 89, // No message available
NOSR = 90, // No STREAM resources
NOSTR = 91, // Not a STREAM
TIME = 92, // STREAM ioctl timeout
// File system extended attribute errors
NOATTR = 93, // Attribute not found
// Realtime, XSI STREAMS option errors
MULTIHOP = 94, // Multihop attempted
NOLINK = 95, // Link has been severed
PROTO = 96, // Protocol error
_,
};
pub const MINSIGSTKSZ = 8192;
pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = -100;
/// Check access using effective user and group ID
pub const EACCESS = 0x0100;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x0200;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x0400;
/// Remove directory instead of file
pub const REMOVEDIR = 0x0800;
};
pub const HOST_NAME_MAX = 255;
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// IP6 hop-by-hop options
pub const HOPOPTS = 0;
/// control message protocol
pub const ICMP = 1;
/// group mgmt protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IP header
pub const IPV4 = 4;
/// IP inside IP
pub const IPIP = 4;
/// tcp
pub const TCP = 6;
/// exterior gateway protocol
pub const EGP = 8;
/// pup
pub const PUP = 12;
/// user datagram protocol
pub const UDP = 17;
/// xns idp
pub const IDP = 22;
/// tp-4 w/ class negotiation
pub const TP = 29;
/// DCCP
pub const DCCP = 33;
/// IP6 header
pub const IPV6 = 41;
/// IP6 routing header
pub const ROUTING = 43;
/// IP6 fragmentation header
pub const FRAGMENT = 44;
/// resource reservation
pub const RSVP = 46;
/// GRE encaps RFC 1701
pub const GRE = 47;
/// encap. security payload
pub const ESP = 50;
/// authentication header
pub const AH = 51;
/// IP Mobility RFC 2004
pub const MOBILE = 55;
/// IPv6 ICMP
pub const IPV6_ICMP = 58;
/// ICMP6
pub const ICMPV6 = 58;
/// IP6 no next header
pub const NONE = 59;
/// IP6 destination option
pub const DSTOPTS = 60;
/// ISO cnlp
pub const EON = 80;
/// Ethernet-in-IP
pub const ETHERIP = 97;
/// encapsulation header
pub const ENCAP = 98;
/// Protocol indep. multicast
pub const PIM = 103;
/// IP Payload Comp. Protocol
pub const IPCOMP = 108;
/// VRRP RFC 2338
pub const VRRP = 112;
/// Common Address Resolution Protocol
pub const CARP = 112;
/// L2TPv3
pub const L2TP = 115;
/// SCTP
pub const SCTP = 132;
/// PFSYNC
pub const PFSYNC = 240;
/// raw IP packet
pub const RAW = 255;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
NTHR = 11,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
/// Testable events (may be specified in events field).
pub const IN = 0x0001;
pub const PRI = 0x0002;
pub const OUT = 0x0004;
pub const RDNORM = 0x0040;
pub const WRNORM = OUT;
pub const RDBAND = 0x0080;
pub const WRBAND = 0x0100;
/// Non-testable events (may not be specified in events field).
pub const ERR = 0x0008;
pub const HUP = 0x0010;
pub const NVAL = 0x0020;
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/freebsd.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
extern "c" fn __error() *c_int;
pub const _errno = __error;
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn pthread_getthreadid_np() c_int;
pub extern "c" fn pthread_set_name_np(thread: std.c.pthread_t, name: [*:0]const u8) void;
pub extern "c" fn pthread_get_name_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) void;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub extern "c" fn malloc_usable_size(?*const anyopaque) usize;
pub const sf_hdtr = extern struct {
headers: [*]const iovec_const,
hdr_cnt: c_int,
trailers: [*]const iovec_const,
trl_cnt: c_int,
};
pub extern "c" fn sendfile(
in_fd: fd_t,
out_fd: fd_t,
offset: off_t,
nbytes: usize,
sf_hdtr: ?*sf_hdtr,
sbytes: ?*off_t,
flags: u32,
) c_int;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub const pthread_mutex_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_cond_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_rwlock_t = extern struct {
ptr: ?*anyopaque = null,
};
pub const pthread_attr_t = extern struct {
__size: [56]u8,
__align: c_long,
};
pub const sem_t = extern struct {
_magic: u32,
_kern: extern struct {
_count: u32,
_flags: u32,
},
_padding: u32,
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const AI = struct {
/// get address to use bind()
pub const PASSIVE = 0x00000001;
/// fill ai_canonname
pub const CANONNAME = 0x00000002;
/// prevent host name resolution
pub const NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const NUMERICSERV = 0x00000008;
/// valid flags for addrinfo (not a standard def, apps should not use it)
pub const MASK = (PASSIVE | CANONNAME | NUMERICHOST | NUMERICSERV | ADDRCONFIG | ALL | V4MAPPED);
/// IPv6 and IPv4-mapped (with V4MAPPED)
pub const ALL = 0x00000100;
/// accept IPv4-mapped if kernel supports
pub const V4MAPPED_CFG = 0x00000200;
/// only if any address is assigned
pub const ADDRCONFIG = 0x00000400;
/// accept IPv4-mapped IPv6 address
pub const V4MAPPED = 0x00000800;
/// special recommended flags for getipnodebyname
pub const DEFAULT = (V4MAPPED_CFG | ADDRCONFIG);
};
pub const blksize_t = i32;
pub const blkcnt_t = i64;
pub const clockid_t = i32;
pub const fsblkcnt_t = u64;
pub const fsfilcnt_t = u64;
pub const nlink_t = u64;
pub const fd_t = i32;
pub const pid_t = i32;
pub const uid_t = u32;
pub const gid_t = u32;
pub const mode_t = u16;
pub const off_t = i64;
pub const ino_t = u64;
pub const dev_t = u64;
pub const time_t = i64;
// The signedness is not constant across different architectures.
pub const clock_t = isize;
pub const socklen_t = u32;
pub const suseconds_t = c_long;
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: usize,
// TODO ext
};
// Modes and flags for dlopen()
// include/dlfcn.h
pub const RTLD = struct {
/// Bind function calls lazily.
pub const LAZY = 1;
/// Bind function calls immediately.
pub const NOW = 2;
pub const MODEMASK = 0x3;
/// Make symbols globally available.
pub const GLOBAL = 0x100;
/// Opposite of GLOBAL, and the default.
pub const LOCAL = 0;
/// Trace loaded objects and exit.
pub const TRACE = 0x200;
/// Do not remove members.
pub const NODELETE = 0x01000;
/// Do not load if not already loaded.
pub const NOLOAD = 0x02000;
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
l_sysid: i32,
__unused: [4]u8,
};
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const Stat = extern struct {
dev: dev_t,
ino: ino_t,
nlink: nlink_t,
mode: mode_t,
__pad0: u16,
uid: uid_t,
gid: gid_t,
__pad1: u32,
rdev: dev_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
birthtim: timespec,
size: off_t,
blocks: i64,
blksize: isize,
flags: u32,
gen: u64,
__spare: [10]u64,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const timeval = extern struct {
/// seconds
tv_sec: time_t,
/// microseconds
tv_usec: suseconds_t,
};
pub const dirent = extern struct {
d_fileno: usize,
d_off: i64,
d_reclen: u16,
d_type: u8,
d_pad0: u8,
d_namlen: u16,
d_pad1: u16,
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const sockaddr = extern struct {
/// total length
len: u8,
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
pub const un = extern struct {
len: u8 = @sizeOf(un),
family: sa_family_t = AF.UNIX,
path: [104]u8,
};
};
pub const CTL = struct {
pub const KERN = 1;
pub const DEBUG = 5;
};
pub const KERN = struct {
pub const PROC = 14; // struct: process entries
pub const PROC_PATHNAME = 12; // path to executable
pub const IOV_MAX = 35;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = KERN.IOV_MAX;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const VIRTUAL = 1;
pub const PROF = 2;
pub const MONOTONIC = 4;
pub const UPTIME = 5;
pub const UPTIME_PRECISE = 7;
pub const UPTIME_FAST = 8;
pub const REALTIME_PRECISE = 9;
pub const REALTIME_FAST = 10;
pub const MONOTONIC_PRECISE = 11;
pub const MONOTONIC_FAST = 12;
pub const SECOND = 13;
pub const THREAD_CPUTIME_ID = 14;
pub const PROCESS_CPUTIME_ID = 15;
};
pub const MAP = struct {
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const FIXED = 0x0010;
pub const STACK = 0x0400;
pub const NOSYNC = 0x0800;
pub const ANON = 0x1000;
pub const ANONYMOUS = ANON;
pub const FILE = 0;
pub const GUARD = 0x00002000;
pub const EXCL = 0x00004000;
pub const NOCORE = 0x00020000;
pub const PREFAULT_READ = 0x00040000;
pub const @"32BIT" = 0x00080000;
};
pub const W = struct {
pub const NOHANG = 1;
pub const UNTRACED = 2;
pub const STOPPED = UNTRACED;
pub const CONTINUED = 4;
pub const NOWAIT = 8;
pub const EXITED = 16;
pub const TRAPPED = 32;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast((s & 0xff00) >> 8));
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return @as(u16, @truncate((((s & 0xffff) *% 0x10001) >> 8))) > 0x7f00;
}
pub fn IFSIGNALED(s: u32) bool {
return (s & 0xffff) -% 1 < 0xff;
}
};
pub const SA = struct {
pub const ONSTACK = 0x0001;
pub const RESTART = 0x0002;
pub const RESETHAND = 0x0004;
pub const NOCLDSTOP = 0x0008;
pub const NODEFER = 0x0010;
pub const NOCLDWAIT = 0x0020;
pub const SIGINFO = 0x0040;
};
pub const SIG = struct {
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const IO = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const INFO = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const THR = 32;
pub const LWP = THR;
pub const LIBRT = 33;
pub const RTMIN = 65;
pub const RTMAX = 126;
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const WORDS = 4;
pub const MAXSIG = 128;
pub inline fn IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn WORD(sig: usize) usize {
return IDX(sig) >> 5;
}
pub inline fn BIT(sig: usize) usize {
return 1 << (IDX(sig) & 31);
}
pub inline fn VALID(sig: usize) usize {
return sig <= MAXSIG and sig > 0;
}
};
pub const sigval = extern union {
int: c_int,
ptr: ?*anyopaque,
};
pub const sigset_t = extern struct {
__bits: [SIG.WORDS]u32,
};
pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** SIG.WORDS };
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const ACCMODE = 0x0003;
pub const SHLOCK = 0x0010;
pub const EXLOCK = 0x0020;
pub const CREAT = 0x0200;
pub const EXCL = 0x0800;
pub const NOCTTY = 0x8000;
pub const TRUNC = 0x0400;
pub const APPEND = 0x0008;
pub const NONBLOCK = 0x0004;
pub const DSYNC = 0o10000;
pub const SYNC = 0x0080;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0x20000;
pub const NOFOLLOW = 0x0100;
pub const CLOEXEC = 0x00100000;
pub const ASYNC = 0x0040;
pub const DIRECT = 0x00010000;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
pub const NDELAY = NONBLOCK;
};
pub const F = struct {
pub const DUPFD = 0;
pub const GETFD = 1;
pub const SETFD = 2;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 11;
pub const SETLK = 12;
pub const SETLKW = 13;
pub const RDLCK = 1;
pub const WRLCK = 3;
pub const UNLCK = 2;
pub const SETOWN_EX = 15;
pub const GETOWN_EX = 16;
pub const GETOWNER_UIDS = 17;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
};
pub const SO = struct {
pub const DEBUG = 0x00000001;
pub const ACCEPTCONN = 0x00000002;
pub const REUSEADDR = 0x00000004;
pub const KEEPALIVE = 0x00000008;
pub const DONTROUTE = 0x00000010;
pub const BROADCAST = 0x00000020;
pub const USELOOPBACK = 0x00000040;
pub const LINGER = 0x00000080;
pub const OOBINLINE = 0x00000100;
pub const REUSEPORT = 0x00000200;
pub const TIMESTAMP = 0x00000400;
pub const NOSIGPIPE = 0x00000800;
pub const ACCEPTFILTER = 0x00001000;
pub const BINTIME = 0x00002000;
pub const NO_OFFLOAD = 0x00004000;
pub const NO_DDP = 0x00008000;
pub const REUSEPORT_LB = 0x00010000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const LABEL = 0x1009;
pub const PEERLABEL = 0x1010;
pub const LISTENQLIMIT = 0x1011;
pub const LISTENQLEN = 0x1012;
pub const LISTENINCQLEN = 0x1013;
pub const SETFIB = 0x1014;
pub const USER_COOKIE = 0x1015;
pub const PROTOCOL = 0x1016;
pub const PROTOTYPE = PROTOCOL;
pub const TS_CLOCK = 0x1017;
pub const MAX_PACING_RATE = 0x1018;
pub const DOMAIN = 0x1019;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NETBIOS = AF.NETBIOS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const XTP = AF.pseudo_XTP;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const SIP = AF.SIP;
pub const IPX = AF.IPX;
pub const RTIP = AF.pseudo_RTIP;
pub const PIP = AF.pseudo_PIP;
pub const ISDN = AF.ISDN;
pub const KEY = AF.pseudo_KEY;
pub const INET6 = AF.pseudo_INET6;
pub const NATM = AF.NATM;
pub const ATM = AF.ATM;
pub const NETGRAPH = AF.NETGRAPH;
pub const SLOW = AF.SLOW;
pub const SCLUSTER = AF.SCLUSTER;
pub const ARP = AF.ARP;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const IEEE80211 = AF.IEEE80211;
pub const INET_SDP = AF.INET_SDP;
pub const INET6_SDP = AF.INET6_SDP;
pub const MAX = AF.MAX;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const UNIX = 1;
pub const LOCAL = UNIX;
pub const FILE = LOCAL;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NETBIOS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const pseudo_XTP = 19;
pub const COIP = 20;
pub const CNT = 21;
pub const pseudo_RTIP = 22;
pub const IPX = 23;
pub const SIP = 24;
pub const pseudo_PIP = 25;
pub const ISDN = 26;
pub const E164 = ISDN;
pub const pseudo_KEY = 27;
pub const INET6 = 28;
pub const NATM = 29;
pub const ATM = 30;
pub const pseudo_HDRCMPLT = 31;
pub const NETGRAPH = 32;
pub const SLOW = 33;
pub const SCLUSTER = 34;
pub const ARP = 35;
pub const BLUETOOTH = 36;
pub const IEEE80211 = 37;
pub const INET_SDP = 40;
pub const INET6_SDP = 42;
pub const MAX = 42;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// error, event data contains errno
pub const EV_ERROR = 0x4000;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Process descriptors
pub const EVFILT_PROCDESC = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
pub const EVFILT_LIO = -10;
/// User events
pub const EVFILT_USER = -11;
/// Sendfile events
pub const EVFILT_SENDFILE = -12;
pub const EVFILT_EMPTY = -13;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;
/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;
/// and fflags
pub const NOTE_FFAND = 0x40000000;
/// or fflags
pub const NOTE_FFOR = 0x80000000;
/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;
/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// behave like poll()
pub const NOTE_FILE_POLL = 0x00000002;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// vnode was opened
pub const NOTE_OPEN = 0x00000080;
/// file closed, fd did not allow write
pub const NOTE_CLOSE = 0x00000100;
/// file closed, fd did allow write
pub const NOTE_CLOSE_WRITE = 0x00000200;
/// file was read
pub const NOTE_READ = 0x00000400;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);
/// data is seconds
pub const NOTE_SECONDS = 0x00000001;
/// data is milliseconds
pub const NOTE_MSECONDS = 0x00000002;
/// data is microseconds
pub const NOTE_USECONDS = 0x00000004;
/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000008;
/// timeout is absolute
pub const NOTE_ABSTIME = 0x00000010;
pub const T = struct {
pub const IOCEXCL = 0x2000740d;
pub const IOCNXCL = 0x2000740e;
pub const IOCSCTTY = 0x20007461;
pub const IOCGPGRP = 0x40047477;
pub const IOCSPGRP = 0x80047476;
pub const IOCOUTQ = 0x40047473;
pub const IOCSTI = 0x80017472;
pub const IOCGWINSZ = 0x40087468;
pub const IOCSWINSZ = 0x80087467;
pub const IOCMGET = 0x4004746a;
pub const IOCMBIS = 0x8004746c;
pub const IOCMBIC = 0x8004746b;
pub const IOCMSET = 0x8004746d;
pub const FIONREAD = 0x4004667f;
pub const IOCCONS = 0x80047462;
pub const IOCPKT = 0x80047470;
pub const FIONBIO = 0x8004667e;
pub const IOCNOTTY = 0x20007471;
pub const IOCSETD = 0x8004741b;
pub const IOCGETD = 0x4004741a;
pub const IOCSBRK = 0x2000747b;
pub const IOCCBRK = 0x2000747a;
pub const IOCGSID = 0x40047463;
pub const IOCGPTN = 0x4004740f;
pub const IOCSIG = 0x2004745f;
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
const NSIG = 32;
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
/// see signal options
flags: c_uint,
/// signal mask to apply
mask: sigset_t,
};
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: pid_t,
uid: uid_t,
status: c_int,
addr: ?*anyopaque,
value: sigval,
reason: extern union {
fault: extern struct {
trapno: c_int,
},
timer: extern struct {
timerid: c_int,
overrun: c_int,
},
mesgq: extern struct {
mqd: c_int,
},
poll: extern struct {
band: c_long,
},
spare: extern struct {
spare1: c_long,
spare2: [7]c_int,
},
},
};
pub usingnamespace switch (builtin.cpu.arch) {
.x86_64 => struct {
pub const ucontext_t = extern struct {
sigmask: sigset_t,
mcontext: mcontext_t,
link: ?*ucontext_t,
stack: stack_t,
flags: c_int,
__spare__: [4]c_int,
};
/// XXX x86_64 specific
pub const mcontext_t = extern struct {
onstack: u64,
rdi: u64,
rsi: u64,
rdx: u64,
rcx: u64,
r8: u64,
r9: u64,
rax: u64,
rbx: u64,
rbp: u64,
r10: u64,
r11: u64,
r12: u64,
r13: u64,
r14: u64,
r15: u64,
trapno: u32,
fs: u16,
gs: u16,
addr: u64,
flags: u32,
es: u16,
ds: u16,
err: u64,
rip: u64,
cs: u64,
rflags: u64,
rsp: u64,
ss: u64,
};
},
else => struct {},
};
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1, // Operation not permitted
NOENT = 2, // No such file or directory
SRCH = 3, // No such process
INTR = 4, // Interrupted system call
IO = 5, // Input/output error
NXIO = 6, // Device not configured
@"2BIG" = 7, // Argument list too long
NOEXEC = 8, // Exec format error
BADF = 9, // Bad file descriptor
CHILD = 10, // No child processes
DEADLK = 11, // Resource deadlock avoided
// 11 was AGAIN
NOMEM = 12, // Cannot allocate memory
ACCES = 13, // Permission denied
FAULT = 14, // Bad address
NOTBLK = 15, // Block device required
BUSY = 16, // Device busy
EXIST = 17, // File exists
XDEV = 18, // Cross-device link
NODEV = 19, // Operation not supported by device
NOTDIR = 20, // Not a directory
ISDIR = 21, // Is a directory
INVAL = 22, // Invalid argument
NFILE = 23, // Too many open files in system
MFILE = 24, // Too many open files
NOTTY = 25, // Inappropriate ioctl for device
TXTBSY = 26, // Text file busy
FBIG = 27, // File too large
NOSPC = 28, // No space left on device
SPIPE = 29, // Illegal seek
ROFS = 30, // Read-only filesystem
MLINK = 31, // Too many links
PIPE = 32, // Broken pipe
// math software
DOM = 33, // Numerical argument out of domain
RANGE = 34, // Result too large
// non-blocking and interrupt i/o
/// Resource temporarily unavailable
/// This code is also used for `WOULDBLOCK`: operation would block.
AGAIN = 35,
INPROGRESS = 36, // Operation now in progress
ALREADY = 37, // Operation already in progress
// ipc/network software -- argument errors
NOTSOCK = 38, // Socket operation on non-socket
DESTADDRREQ = 39, // Destination address required
MSGSIZE = 40, // Message too long
PROTOTYPE = 41, // Protocol wrong type for socket
NOPROTOOPT = 42, // Protocol not available
PROTONOSUPPORT = 43, // Protocol not supported
SOCKTNOSUPPORT = 44, // Socket type not supported
/// Operation not supported
/// This code is also used for `NOTSUP`.
OPNOTSUPP = 45,
PFNOSUPPORT = 46, // Protocol family not supported
AFNOSUPPORT = 47, // Address family not supported by protocol family
ADDRINUSE = 48, // Address already in use
ADDRNOTAVAIL = 49, // Can't assign requested address
// ipc/network software -- operational errors
NETDOWN = 50, // Network is down
NETUNREACH = 51, // Network is unreachable
NETRESET = 52, // Network dropped connection on reset
CONNABORTED = 53, // Software caused connection abort
CONNRESET = 54, // Connection reset by peer
NOBUFS = 55, // No buffer space available
ISCONN = 56, // Socket is already connected
NOTCONN = 57, // Socket is not connected
SHUTDOWN = 58, // Can't send after socket shutdown
TOOMANYREFS = 59, // Too many references: can't splice
TIMEDOUT = 60, // Operation timed out
CONNREFUSED = 61, // Connection refused
LOOP = 62, // Too many levels of symbolic links
NAMETOOLONG = 63, // File name too long
// should be rearranged
HOSTDOWN = 64, // Host is down
HOSTUNREACH = 65, // No route to host
NOTEMPTY = 66, // Directory not empty
// quotas & mush
PROCLIM = 67, // Too many processes
USERS = 68, // Too many users
DQUOT = 69, // Disc quota exceeded
// Network File System
STALE = 70, // Stale NFS file handle
REMOTE = 71, // Too many levels of remote in path
BADRPC = 72, // RPC struct is bad
RPCMISMATCH = 73, // RPC version wrong
PROGUNAVAIL = 74, // RPC prog. not avail
PROGMISMATCH = 75, // Program version wrong
PROCUNAVAIL = 76, // Bad procedure for program
NOLCK = 77, // No locks available
NOSYS = 78, // Function not implemented
FTYPE = 79, // Inappropriate file type or format
AUTH = 80, // Authentication error
NEEDAUTH = 81, // Need authenticator
IDRM = 82, // Identifier removed
NOMSG = 83, // No message of desired type
OVERFLOW = 84, // Value too large to be stored in data type
CANCELED = 85, // Operation canceled
ILSEQ = 86, // Illegal byte sequence
NOATTR = 87, // Attribute not found
DOOFUS = 88, // Programming error
BADMSG = 89, // Bad message
MULTIHOP = 90, // Multihop attempted
NOLINK = 91, // Link has been severed
PROTO = 92, // Protocol error
NOTCAPABLE = 93, // Capabilities insufficient
CAPMODE = 94, // Not permitted in capability mode
NOTRECOVERABLE = 95, // State not recoverable
OWNERDEAD = 96, // Previous owner died
_,
};
pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {
.i386, .x86_64 => 2048,
.arm, .aarch64 => 4096,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
};
pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const HOST_NAME_MAX = 255;
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = -100;
/// Check access using effective user and group ID
pub const EACCESS = 0x0100;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x0200;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x0400;
/// Remove directory instead of file
pub const REMOVEDIR = 0x0800;
/// Fail if not under dirfd
pub const BENEATH = 0x1000;
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// control message protocol
pub const ICMP = 1;
/// tcp
pub const TCP = 6;
/// user datagram protocol
pub const UDP = 17;
/// IP6 header
pub const IPV6 = 41;
/// raw IP packet
pub const RAW = 255;
/// IP6 hop-by-hop options
pub const HOPOPTS = 0;
/// group mgmt protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IPv4 encapsulation
pub const IPV4 = 4;
/// for compatibility
pub const IPIP = IPV4;
/// Stream protocol II
pub const ST = 7;
/// exterior gateway protocol
pub const EGP = 8;
/// private interior gateway
pub const PIGP = 9;
/// BBN RCC Monitoring
pub const RCCMON = 10;
/// network voice protocol
pub const NVPII = 11;
/// pup
pub const PUP = 12;
/// Argus
pub const ARGUS = 13;
/// EMCON
pub const EMCON = 14;
/// Cross Net Debugger
pub const XNET = 15;
/// Chaos
pub const CHAOS = 16;
/// Multiplexing
pub const MUX = 18;
/// DCN Measurement Subsystems
pub const MEAS = 19;
/// Host Monitoring
pub const HMP = 20;
/// Packet Radio Measurement
pub const PRM = 21;
/// xns idp
pub const IDP = 22;
/// Trunk-1
pub const TRUNK1 = 23;
/// Trunk-2
pub const TRUNK2 = 24;
/// Leaf-1
pub const LEAF1 = 25;
/// Leaf-2
pub const LEAF2 = 26;
/// Reliable Data
pub const RDP = 27;
/// Reliable Transaction
pub const IRTP = 28;
/// tp-4 w/ class negotiation
pub const TP = 29;
/// Bulk Data Transfer
pub const BLT = 30;
/// Network Services
pub const NSP = 31;
/// Merit Internodal
pub const INP = 32;
/// Datagram Congestion Control Protocol
pub const DCCP = 33;
/// Third Party Connect
pub const @"3PC" = 34;
/// InterDomain Policy Routing
pub const IDPR = 35;
/// XTP
pub const XTP = 36;
/// Datagram Delivery
pub const DDP = 37;
/// Control Message Transport
pub const CMTP = 38;
/// TP++ Transport
pub const TPXX = 39;
/// IL transport protocol
pub const IL = 40;
/// Source Demand Routing
pub const SDRP = 42;
/// IP6 routing header
pub const ROUTING = 43;
/// IP6 fragmentation header
pub const FRAGMENT = 44;
/// InterDomain Routing
pub const IDRP = 45;
/// resource reservation
pub const RSVP = 46;
/// General Routing Encap.
pub const GRE = 47;
/// Mobile Host Routing
pub const MHRP = 48;
/// BHA
pub const BHA = 49;
/// IP6 Encap Sec. Payload
pub const ESP = 50;
/// IP6 Auth Header
pub const AH = 51;
/// Integ. Net Layer Security
pub const INLSP = 52;
/// IP with encryption
pub const SWIPE = 53;
/// Next Hop Resolution
pub const NHRP = 54;
/// IP Mobility
pub const MOBILE = 55;
/// Transport Layer Security
pub const TLSP = 56;
/// SKIP
pub const SKIP = 57;
/// ICMP6
pub const ICMPV6 = 58;
/// IP6 no next header
pub const NONE = 59;
/// IP6 destination option
pub const DSTOPTS = 60;
/// any host internal protocol
pub const AHIP = 61;
/// CFTP
pub const CFTP = 62;
/// "hello" routing protocol
pub const HELLO = 63;
/// SATNET/Backroom EXPAK
pub const SATEXPAK = 64;
/// Kryptolan
pub const KRYPTOLAN = 65;
/// Remote Virtual Disk
pub const RVD = 66;
/// Pluribus Packet Core
pub const IPPC = 67;
/// Any distributed FS
pub const ADFS = 68;
/// Satnet Monitoring
pub const SATMON = 69;
/// VISA Protocol
pub const VISA = 70;
/// Packet Core Utility
pub const IPCV = 71;
/// Comp. Prot. Net. Executive
pub const CPNX = 72;
/// Comp. Prot. HeartBeat
pub const CPHB = 73;
/// Wang Span Network
pub const WSN = 74;
/// Packet Video Protocol
pub const PVP = 75;
/// BackRoom SATNET Monitoring
pub const BRSATMON = 76;
/// Sun net disk proto (temp.)
pub const ND = 77;
/// WIDEBAND Monitoring
pub const WBMON = 78;
/// WIDEBAND EXPAK
pub const WBEXPAK = 79;
/// ISO cnlp
pub const EON = 80;
/// VMTP
pub const VMTP = 81;
/// Secure VMTP
pub const SVMTP = 82;
/// Banyon VINES
pub const VINES = 83;
/// TTP
pub const TTP = 84;
/// NSFNET-IGP
pub const IGP = 85;
/// dissimilar gateway prot.
pub const DGP = 86;
/// TCF
pub const TCF = 87;
/// Cisco/GXS IGRP
pub const IGRP = 88;
/// OSPFIGP
pub const OSPFIGP = 89;
/// Strite RPC protocol
pub const SRPC = 90;
/// Locus Address Resoloution
pub const LARP = 91;
/// Multicast Transport
pub const MTP = 92;
/// AX.25 Frames
pub const AX25 = 93;
/// IP encapsulated in IP
pub const IPEIP = 94;
/// Mobile Int.ing control
pub const MICP = 95;
/// Semaphore Comm. security
pub const SCCSP = 96;
/// Ethernet IP encapsulation
pub const ETHERIP = 97;
/// encapsulation header
pub const ENCAP = 98;
/// any private encr. scheme
pub const APES = 99;
/// GMTP
pub const GMTP = 100;
/// payload compression (IPComp)
pub const IPCOMP = 108;
/// SCTP
pub const SCTP = 132;
/// IPv6 Mobility Header
pub const MH = 135;
/// UDP-Lite
pub const UDPLITE = 136;
/// IP6 Host Identity Protocol
pub const HIP = 139;
/// IP6 Shim6 Protocol
pub const SHIM6 = 140;
/// Protocol Independent Mcast
pub const PIM = 103;
/// CARP
pub const CARP = 112;
/// PGM
pub const PGM = 113;
/// MPLS-in-IP
pub const MPLS = 137;
/// PFSYNC
pub const PFSYNC = 240;
/// Reserved
pub const RESERVED_253 = 253;
/// Reserved
pub const RESERVED_254 = 254;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
NPTS = 11,
SWAP = 12,
KQUEUES = 13,
UMTXP = 14,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
/// any readable data available.
pub const IN = 0x0001;
/// OOB/Urgent readable data.
pub const PRI = 0x0002;
/// file descriptor is writeable.
pub const OUT = 0x0004;
/// non-OOB/URG data available.
pub const RDNORM = 0x0040;
/// no write type differentiation.
pub const WRNORM = OUT;
/// OOB/Urgent readable data.
pub const RDBAND = 0x0080;
/// OOB/Urgent data can be written.
pub const WRBAND = 0x0100;
/// like IN, except ignore EOF.
pub const INIGNEOF = 0x2000;
/// some poll error occurred.
pub const ERR = 0x0008;
/// file descriptor was "hung up".
pub const HUP = 0x0010;
/// requested events "invalid".
pub const NVAL = 0x0020;
pub const STANDARD = IN | PRI | OUT | RDNORM | RDBAND | WRBAND | ERR | HUP | NVAL;
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/darwin.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const macho = std.macho;
const native_arch = builtin.target.cpu.arch;
const maxInt = std.math.maxInt;
const iovec_const = std.os.iovec_const;
extern "c" fn __error() *c_int;
pub extern "c" fn NSVersionOfRunTimeLibrary(library_name: [*:0]const u8) u32;
pub extern "c" fn _NSGetExecutablePath(buf: [*:0]u8, bufsize: *u32) c_int;
pub extern "c" fn _dyld_image_count() u32;
pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
pub extern "c" fn _dyld_get_image_vmaddr_slide(image_index: u32) usize;
pub extern "c" fn _dyld_get_image_name(image_index: u32) [*:0]const u8;
pub const COPYFILE_ACL = 1 << 0;
pub const COPYFILE_STAT = 1 << 1;
pub const COPYFILE_XATTR = 1 << 2;
pub const COPYFILE_DATA = 1 << 3;
pub const copyfile_state_t = *opaque {};
pub extern "c" fn fcopyfile(from: fd_t, to: fd_t, state: ?copyfile_state_t, flags: u32) c_int;
pub extern "c" fn @"realpath$DARWIN_EXTSN"(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub const realpath = @"realpath$DARWIN_EXTSN";
pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) isize;
const private = struct {
extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
/// On x86_64 Darwin, fstat has to be manully linked with $INODE64 suffix to
/// force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstat$INODE64"(fd: fd_t, buf: *Stat) c_int;
extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
/// On x86_64 Darwin, fstatat has to be manully linked with $INODE64 suffix to
/// force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstatat$INODE64"(dirfd: fd_t, path_name: [*:0]const u8, buf: *Stat, flags: u32) c_int;
};
pub const fstat = if (native_arch == .aarch64) private.fstat else private.@"fstat$INODE64";
pub const fstatat = if (native_arch == .aarch64) private.fstatat else private.@"fstatat$INODE64";
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void;
pub extern "c" fn malloc_size(?*const anyopaque) usize;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub extern "c" fn kevent64(
kq: c_int,
changelist: [*]const kevent64_s,
nchanges: c_int,
eventlist: [*]kevent64_s,
nevents: c_int,
flags: c_uint,
timeout: ?*const timespec,
) c_int;
const mach_hdr = if (@sizeOf(usize) == 8) mach_header_64 else mach_header;
/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
/// of the mach header in a Mach-O executable file type. It does not appear in
/// any file type other than a MH_EXECUTE file type. The type of the symbol is
/// absolute as the header is not part of any section.
/// This symbol is populated when linking the system's libc, which is guaranteed
/// on this operating system. However when building object files or libraries,
/// the system libc won't be linked until the final executable. So we
/// export a weak symbol here, to be overridden by the real one.
var dummy_execute_header: mach_hdr = undefined;
pub extern var _mh_execute_header: mach_hdr;
comptime {
if (builtin.target.isDarwin()) {
@export(dummy_execute_header, .{ .name = "_mh_execute_header", .linkage = .Weak });
}
}
pub const mach_header_64 = macho.mach_header_64;
pub const mach_header = macho.mach_header;
pub const _errno = __error;
pub extern "c" fn @"close$NOCANCEL"(fd: fd_t) c_int;
pub extern "c" fn mach_host_self() mach_port_t;
pub extern "c" fn clock_get_time(clock_serv: clock_serv_t, cur_time: *mach_timespec_t) kern_return_t;
pub const sf_hdtr = extern struct {
headers: [*]const iovec_const,
hdr_cnt: c_int,
trailers: [*]const iovec_const,
trl_cnt: c_int,
};
pub extern "c" fn sendfile(
in_fd: fd_t,
out_fd: fd_t,
offset: off_t,
len: *off_t,
sf_hdtr: ?*sf_hdtr,
flags: u32,
) c_int;
pub fn sigaddset(set: *sigset_t, signo: u5) void {
set.* |= @as(u32, 1) << (signo - 1);
}
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub const AI = struct {
/// get address to use bind()
pub const PASSIVE = 0x00000001;
/// fill ai_canonname
pub const CANONNAME = 0x00000002;
/// prevent host name resolution
pub const NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const NUMERICSERV = 0x00001000;
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// temporary failure in name resolution
AGAIN = 2,
/// invalid value for ai_flags
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// ai_family not supported
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// hostname nor servname provided, or not known
NONAME = 8,
/// servname not supported for ai_socktype
SERVICE = 9,
/// ai_socktype not supported
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const pthread_mutex_t = extern struct {
__sig: c_long = 0x32AAABA7,
__opaque: [__PTHREAD_MUTEX_SIZE__]u8 = [_]u8{0} ** __PTHREAD_MUTEX_SIZE__,
};
pub const pthread_cond_t = extern struct {
__sig: c_long = 0x3CB0B1BB,
__opaque: [__PTHREAD_COND_SIZE__]u8 = [_]u8{0} ** __PTHREAD_COND_SIZE__,
};
pub const pthread_rwlock_t = extern struct {
__sig: c_long = 0x2DA8B3B4,
__opaque: [192]u8 = [_]u8{0} ** 192,
};
pub const sem_t = c_int;
const __PTHREAD_MUTEX_SIZE__ = if (@sizeOf(usize) == 8) 56 else 40;
const __PTHREAD_COND_SIZE__ = if (@sizeOf(usize) == 8) 40 else 24;
pub const pthread_attr_t = extern struct {
__sig: c_long,
__opaque: [56]u8,
};
const pthread_t = std.c.pthread_t;
pub extern "c" fn pthread_threadid_np(thread: ?pthread_t, thread_id: *u64) c_int;
pub extern "c" fn pthread_setname_np(name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
// Grand Central Dispatch is exposed by libSystem.
pub extern "c" fn dispatch_release(object: *anyopaque) void;
pub const dispatch_semaphore_t = *opaque {};
pub extern "c" fn dispatch_semaphore_create(value: isize) ?dispatch_semaphore_t;
pub extern "c" fn dispatch_semaphore_wait(dsema: dispatch_semaphore_t, timeout: dispatch_time_t) isize;
pub extern "c" fn dispatch_semaphore_signal(dsema: dispatch_semaphore_t) isize;
pub const dispatch_time_t = u64;
pub const DISPATCH_TIME_NOW = @as(dispatch_time_t, 0);
pub const DISPATCH_TIME_FOREVER = ~@as(dispatch_time_t, 0);
pub extern "c" fn dispatch_time(when: dispatch_time_t, delta: i64) dispatch_time_t;
const dispatch_once_t = usize;
const dispatch_function_t = fn (?*anyopaque) callconv(.C) void;
pub extern fn dispatch_once_f(
predicate: *dispatch_once_t,
context: ?*anyopaque,
function: dispatch_function_t,
) void;
// Undocumented futex-like API available on darwin 16+
// (macOS 10.12+, iOS 10.0+, tvOS 10.0+, watchOS 3.0+, catalyst 13.0+).
//
// [ulock.h]: https://github.com/apple/darwin-xnu/blob/master/bsd/sys/ulock.h
// [sys_ulock.c]: https://github.com/apple/darwin-xnu/blob/master/bsd/kern/sys_ulock.c
pub const UL_COMPARE_AND_WAIT = 1;
pub const UL_UNFAIR_LOCK = 2;
// Obsolete/deprecated
pub const UL_OSSPINLOCK = UL_COMPARE_AND_WAIT;
pub const UL_HANDOFFLOCK = UL_UNFAIR_LOCK;
pub const ULF_WAKE_ALL = 0x100;
pub const ULF_WAKE_THREAD = 0x200;
pub const ULF_WAIT_WORKQ_DATA_CONTENTION = 0x10000;
pub const ULF_WAIT_CANCEL_POINT = 0x20000;
pub const ULF_NO_ERRNO = 0x1000000;
// The following are only supported on darwin 19+
// (macOS 10.15+, iOS 13.0+)
pub const UL_COMPARE_AND_WAIT_SHARED = 3;
pub const UL_UNFAIR_LOCK64_SHARED = 4;
pub const UL_COMPARE_AND_WAIT64 = 5;
pub const UL_COMPARE_AND_WAIT64_SHARED = 6;
pub const ULF_WAIT_ADAPTIVE_SPIN = 0x40000;
pub extern "c" fn __ulock_wait2(op: u32, addr: ?*const anyopaque, val: u64, timeout_ns: u64, val2: u64) c_int;
pub extern "c" fn __ulock_wait(op: u32, addr: ?*const anyopaque, val: u64, timeout_us: u32) c_int;
pub extern "c" fn __ulock_wake(op: u32, addr: ?*const anyopaque, val: u64) c_int;
pub const OS_UNFAIR_LOCK_INIT = os_unfair_lock{};
pub const os_unfair_lock_t = *os_unfair_lock;
pub const os_unfair_lock = extern struct {
_os_unfair_lock_opaque: u32 = 0,
};
pub extern "c" fn os_unfair_lock_lock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_unlock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_trylock(o: os_unfair_lock_t) bool;
pub extern "c" fn os_unfair_lock_assert_owner(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_assert_not_owner(o: os_unfair_lock_t) void;
// XXX: close -> close$NOCANCEL
// XXX: getdirentries -> _getdirentries64
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
pub extern "c" fn sigfillset(set: ?*sigset_t) void;
pub extern "c" fn alarm(seconds: c_uint) c_uint;
pub extern "c" fn sigwait(set: ?*sigset_t, sig: ?*c_int) c_int;
// See: https://opensource.apple.com/source/xnu/xnu-6153.141.1/bsd/sys/_types.h.auto.html
// TODO: audit mode_t/pid_t, should likely be u16/i32
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const sockaddr = extern struct {
len: u8,
family: sa_family_t,
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// UNIX domain socket
pub const un = extern struct {
len: u8 = @sizeOf(un),
family: sa_family_t = AF.UNIX,
path: [104]u8,
};
};
pub const timeval = extern struct {
tv_sec: c_long,
tv_usec: i32,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mach_timebase_info_data = extern struct {
numer: u32,
denom: u32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
};
pub const Stat = extern struct {
dev: i32,
mode: u16,
nlink: u16,
ino: ino_t,
uid: uid_t,
gid: gid_t,
rdev: i32,
atimesec: isize,
atimensec: isize,
mtimesec: isize,
mtimensec: isize,
ctimesec: isize,
ctimensec: isize,
birthtimesec: isize,
birthtimensec: isize,
size: off_t,
blocks: i64,
blksize: i32,
flags: u32,
gen: u32,
lspare: i32,
qspare: [2]i64,
pub fn atime(self: @This()) timespec {
return timespec{
.tv_sec = self.atimesec,
.tv_nsec = self.atimensec,
};
}
pub fn mtime(self: @This()) timespec {
return timespec{
.tv_sec = self.mtimesec,
.tv_nsec = self.mtimensec,
};
}
pub fn ctime(self: @This()) timespec {
return timespec{
.tv_sec = self.ctimesec,
.tv_nsec = self.ctimensec,
};
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const sigset_t = u32;
pub const empty_sigset: sigset_t = 0;
pub const SIG = struct {
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const HOLD = @as(?Sigaction.sigaction_fn, @ptrFromInt(5));
/// block specified signal set
pub const _BLOCK = 1;
/// unblock specified signal set
pub const _UNBLOCK = 2;
/// set specified signal set
pub const _SETMASK = 3;
/// hangup
pub const HUP = 1;
/// interrupt
pub const INT = 2;
/// quit
pub const QUIT = 3;
/// illegal instruction (not reset when caught)
pub const ILL = 4;
/// trace trap (not reset when caught)
pub const TRAP = 5;
/// abort()
pub const ABRT = 6;
/// pollable event ([XSR] generated, not supported)
pub const POLL = 7;
/// compatibility
pub const IOT = ABRT;
/// EMT instruction
pub const EMT = 7;
/// floating point exception
pub const FPE = 8;
/// kill (cannot be caught or ignored)
pub const KILL = 9;
/// bus error
pub const BUS = 10;
/// segmentation violation
pub const SEGV = 11;
/// bad argument to system call
pub const SYS = 12;
/// write on a pipe with no one to read it
pub const PIPE = 13;
/// alarm clock
pub const ALRM = 14;
/// software termination signal from kill
pub const TERM = 15;
/// urgent condition on IO channel
pub const URG = 16;
/// sendable stop signal not from tty
pub const STOP = 17;
/// stop signal from tty
pub const TSTP = 18;
/// continue a stopped process
pub const CONT = 19;
/// to parent on child stop or exit
pub const CHLD = 20;
/// to readers pgrp upon background tty read
pub const TTIN = 21;
/// like TTIN for output if (tp->t_local<OSTOP)
pub const TTOU = 22;
/// input/output possible signal
pub const IO = 23;
/// exceeded CPU time limit
pub const XCPU = 24;
/// exceeded file size limit
pub const XFSZ = 25;
/// virtual time alarm
pub const VTALRM = 26;
/// profiling time alarm
pub const PROF = 27;
/// window size changes
pub const WINCH = 28;
/// information request
pub const INFO = 29;
/// user defined signal 1
pub const USR1 = 30;
/// user defined signal 2
pub const USR2 = 31;
};
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: pid_t,
uid: uid_t,
status: c_int,
addr: *anyopaque,
value: extern union {
int: c_int,
ptr: *anyopaque,
},
si_band: c_long,
_pad: [7]c_ulong,
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
mask: sigset_t,
flags: c_uint,
};
pub const dirent = extern struct {
d_ino: usize,
d_seekoff: usize,
d_reclen: u16,
d_namlen: u16,
d_type: u8,
d_name: u8, // field address is address of first byte of name
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: isize,
udata: usize,
};
// sys/types.h on macos uses #pragma pack(4) so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@offsetOf(Kevent, "ident") == 0);
assert(@offsetOf(Kevent, "filter") == 8);
assert(@offsetOf(Kevent, "flags") == 10);
assert(@offsetOf(Kevent, "fflags") == 12);
assert(@offsetOf(Kevent, "data") == 16);
assert(@offsetOf(Kevent, "udata") == 24);
}
pub const kevent64_s = extern struct {
ident: u64,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: u64,
ext: [2]u64,
};
// sys/types.h on macos uses #pragma pack() so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@offsetOf(kevent64_s, "ident") == 0);
assert(@offsetOf(kevent64_s, "filter") == 8);
assert(@offsetOf(kevent64_s, "flags") == 10);
assert(@offsetOf(kevent64_s, "fflags") == 12);
assert(@offsetOf(kevent64_s, "data") == 16);
assert(@offsetOf(kevent64_s, "udata") == 24);
assert(@offsetOf(kevent64_s, "ext") == 32);
}
pub const mach_port_t = c_uint;
pub const clock_serv_t = mach_port_t;
pub const clock_res_t = c_int;
pub const mach_port_name_t = natural_t;
pub const natural_t = c_uint;
pub const mach_timespec_t = extern struct {
tv_sec: c_uint,
tv_nsec: clock_res_t,
};
pub const kern_return_t = c_int;
pub const host_t = mach_port_t;
pub const CALENDAR_CLOCK = 1;
pub const PATH_MAX = 1024;
pub const IOV_MAX = 16;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
/// [MC2] no permissions
pub const NONE = 0x00;
/// [MC2] pages can be read
pub const READ = 0x01;
/// [MC2] pages can be written
pub const WRITE = 0x02;
/// [MC2] pages can be executed
pub const EXEC = 0x04;
};
pub const MAP = struct {
/// allocated from memory, swap space
pub const ANONYMOUS = 0x1000;
/// map from file (default)
pub const FILE = 0x0000;
/// interpret addr exactly
pub const FIXED = 0x0010;
/// region may contain semaphores
pub const HASSEMAPHORE = 0x0200;
/// changes are private
pub const PRIVATE = 0x0002;
/// share changes
pub const SHARED = 0x0001;
/// don't cache pages for this mapping
pub const NOCACHE = 0x0400;
/// don't reserve needed swap area
pub const NORESERVE = 0x0040;
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
};
pub const SA = struct {
/// take signal on signal stack
pub const ONSTACK = 0x0001;
/// restart system on signal return
pub const RESTART = 0x0002;
/// reset to SIG.DFL when taking signal
pub const RESETHAND = 0x0004;
/// do not generate SIG.CHLD on child stop
pub const NOCLDSTOP = 0x0008;
/// don't mask the signal we're delivering
pub const NODEFER = 0x0010;
/// don't keep zombies around
pub const NOCLDWAIT = 0x0020;
/// signal handler with SIGINFO args
pub const SIGINFO = 0x0040;
/// do not bounce off kernel's sigtramp
pub const USERTRAMP = 0x0100;
/// signal handler with SIGINFO args with 64bit regs information
pub const @"64REGSET" = 0x0200;
};
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
pub const O = struct {
pub const PATH = 0x0000;
/// open for reading only
pub const RDONLY = 0x0000;
/// open for writing only
pub const WRONLY = 0x0001;
/// open for reading and writing
pub const RDWR = 0x0002;
/// do not block on open or for data to become available
pub const NONBLOCK = 0x0004;
/// append on each write
pub const APPEND = 0x0008;
/// create file if it does not exist
pub const CREAT = 0x0200;
/// truncate size to 0
pub const TRUNC = 0x0400;
/// error if CREAT and the file exists
pub const EXCL = 0x0800;
/// atomically obtain a shared lock
pub const SHLOCK = 0x0010;
/// atomically obtain an exclusive lock
pub const EXLOCK = 0x0020;
/// do not follow symlinks
pub const NOFOLLOW = 0x0100;
/// allow open of symlinks
pub const SYMLINK = 0x200000;
/// descriptor requested for event notifications only
pub const EVTONLY = 0x8000;
/// mark as close-on-exec
pub const CLOEXEC = 0x1000000;
pub const ACCMODE = 3;
pub const ALERT = 536870912;
pub const ASYNC = 64;
pub const DIRECTORY = 1048576;
pub const DP_GETRAWENCRYPTED = 1;
pub const DP_GETRAWUNENCRYPTED = 2;
pub const DSYNC = 4194304;
pub const FSYNC = SYNC;
pub const NOCTTY = 131072;
pub const POPUP = 2147483648;
pub const SYNC = 128;
};
pub const SEEK = struct {
pub const SET = 0x0;
pub const CUR = 0x1;
pub const END = 0x2;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// no flag value
pub const KEVENT_FLAG_NONE = 0x000;
/// immediate timeout
pub const KEVENT_FLAG_IMMEDIATE = 0x001;
/// output events only include change
pub const KEVENT_FLAG_ERROR_EVENTS = 0x002;
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
/// unique kevent per udata value
pub const EV_UDATA_SPECIFIC = 0x0100;
/// ... in combination with EV_DELETE
/// will defer delete until udata-specific
/// event enabled. EINPROGRESS will be
/// returned to indicate the deferral
pub const EV_DISPATCH2 = EV_DISPATCH | EV_UDATA_SPECIFIC;
/// report that source has vanished
/// ... only valid with EV_DISPATCH2
pub const EV_VANISHED = 0x0200;
/// reserved by system
pub const EV_SYSFLAGS = 0xF000;
/// filter-specific flag
pub const EV_FLAG0 = 0x1000;
/// filter-specific flag
pub const EV_FLAG1 = 0x2000;
/// EOF detected
pub const EV_EOF = 0x8000;
/// error, data contains errno
pub const EV_ERROR = 0x4000;
pub const EV_POLL = EV_FLAG0;
pub const EV_OOBAND = EV_FLAG1;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Mach portsets
pub const EVFILT_MACHPORT = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
/// User events
pub const EVFILT_USER = -10;
/// Virtual memory events
pub const EVFILT_VM = -12;
/// Exception events
pub const EVFILT_EXCEPT = -15;
pub const EVFILT_SYSCOUNT = 17;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;
/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;
/// and fflags
pub const NOTE_FFAND = 0x40000000;
/// or fflags
pub const NOTE_FFOR = 0x80000000;
/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;
/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// OOB data
pub const NOTE_OOB = 0x00000002;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// No specific vnode event: to test for EVFILT_READ activation
pub const NOTE_NONE = 0x00000080;
/// vnode was unlocked by flock(2)
pub const NOTE_FUNLOCK = 0x00000100;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// shared with EVFILT_SIGNAL
pub const NOTE_SIGNAL = 0x08000000;
/// exit status to be returned, valid for child process only
pub const NOTE_EXITSTATUS = 0x04000000;
/// provide details on reasons for exit
pub const NOTE_EXIT_DETAIL = 0x02000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);
pub const NOTE_EXIT_DETAIL_MASK = 0x00070000;
pub const NOTE_EXIT_DECRYPTFAIL = 0x00010000;
pub const NOTE_EXIT_MEMORY = 0x00020000;
pub const NOTE_EXIT_CSERROR = 0x00040000;
/// will react on memory pressure
pub const NOTE_VM_PRESSURE = 0x80000000;
/// will quit on memory pressure, possibly after cleaning up dirty state
pub const NOTE_VM_PRESSURE_TERMINATE = 0x40000000;
/// will quit immediately on memory pressure
pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000;
/// there was an error
pub const NOTE_VM_ERROR = 0x10000000;
/// data is seconds
pub const NOTE_SECONDS = 0x00000001;
/// data is microseconds
pub const NOTE_USECONDS = 0x00000002;
/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000004;
/// absolute timeout
pub const NOTE_ABSOLUTE = 0x00000008;
/// ext[1] holds leeway for power aware timers
pub const NOTE_LEEWAY = 0x00000010;
/// system does minimal timer coalescing
pub const NOTE_CRITICAL = 0x00000020;
/// system does maximum timer coalescing
pub const NOTE_BACKGROUND = 0x00000040;
pub const NOTE_MACH_CONTINUOUS_TIME = 0x00000080;
/// data is mach absolute time units
pub const NOTE_MACHTIME = 0x00000100;
pub const AF = struct {
pub const UNSPEC = 0;
pub const LOCAL = 1;
pub const UNIX = LOCAL;
pub const INET = 2;
pub const SYS_CONTROL = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const XTP = 19;
pub const COIP = 20;
pub const CNT = 21;
pub const RTIP = 22;
pub const IPX = 23;
pub const SIP = 24;
pub const PIP = 25;
pub const ISDN = 28;
pub const E164 = ISDN;
pub const KEY = 29;
pub const INET6 = 30;
pub const NATM = 31;
pub const SYSTEM = 32;
pub const NETBIOS = 33;
pub const PPP = 34;
pub const MAX = 40;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NS = AF.NS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const SNA = AF.SNA;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const XTP = AF.XTP;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const SIP = AF.SIP;
pub const IPX = AF.IPX;
pub const RTIP = AF.RTIP;
pub const PIP = AF.PIP;
pub const ISDN = AF.ISDN;
pub const KEY = AF.KEY;
pub const INET6 = AF.INET6;
pub const NATM = AF.NATM;
pub const SYSTEM = AF.SYSTEM;
pub const NETBIOS = AF.NETBIOS;
pub const PPP = AF.PPP;
pub const MAX = AF.MAX;
};
pub const SYSPROTO_EVENT = 1;
pub const SYSPROTO_CONTROL = 2;
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const MAXADDRLEN = 255;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other `SOCK` bits.
pub const CLOEXEC = 1 << 15;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other `SOCK` bits.
pub const NONBLOCK = 1 << 16;
};
pub const IPPROTO = struct {
pub const ICMP = 1;
pub const ICMPV6 = 58;
pub const TCP = 6;
pub const UDP = 17;
pub const IP = 0;
pub const IPV6 = 41;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x1080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const ACCEPTFILTER = 0x1000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const NREAD = 0x1020;
pub const NKE = 0x1021;
pub const NOSIGPIPE = 0x1022;
pub const NOADDRERR = 0x1023;
pub const NWRITE = 0x1024;
pub const REUSESHAREUID = 0x1025;
};
pub const W = struct {
/// [XSI] no hang in wait/no child to reap
pub const NOHANG = 0x00000001;
/// [XSI] notify on stop, untraced child
pub const UNTRACED = 0x00000002;
pub fn EXITSTATUS(x: u32) u8 {
return @as(u8, @intCast(x >> 8));
}
pub fn TERMSIG(x: u32) u32 {
return status(x);
}
pub fn STOPSIG(x: u32) u32 {
return x >> 8;
}
pub fn IFEXITED(x: u32) bool {
return status(x) == 0;
}
pub fn IFSTOPPED(x: u32) bool {
return status(x) == stopped and STOPSIG(x) != 0x13;
}
pub fn IFSIGNALED(x: u32) bool {
return status(x) != stopped and status(x) != 0;
}
fn status(x: u32) u32 {
return x & 0o177;
}
const stopped = 0o177;
};
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
/// Operation not permitted
PERM = 1,
/// No such file or directory
NOENT = 2,
/// No such process
SRCH = 3,
/// Interrupted system call
INTR = 4,
/// Input/output error
IO = 5,
/// Device not configured
NXIO = 6,
/// Argument list too long
@"2BIG" = 7,
/// Exec format error
NOEXEC = 8,
/// Bad file descriptor
BADF = 9,
/// No child processes
CHILD = 10,
/// Resource deadlock avoided
DEADLK = 11,
/// Cannot allocate memory
NOMEM = 12,
/// Permission denied
ACCES = 13,
/// Bad address
FAULT = 14,
/// Block device required
NOTBLK = 15,
/// Device / Resource busy
BUSY = 16,
/// File exists
EXIST = 17,
/// Cross-device link
XDEV = 18,
/// Operation not supported by device
NODEV = 19,
/// Not a directory
NOTDIR = 20,
/// Is a directory
ISDIR = 21,
/// Invalid argument
INVAL = 22,
/// Too many open files in system
NFILE = 23,
/// Too many open files
MFILE = 24,
/// Inappropriate ioctl for device
NOTTY = 25,
/// Text file busy
TXTBSY = 26,
/// File too large
FBIG = 27,
/// No space left on device
NOSPC = 28,
/// Illegal seek
SPIPE = 29,
/// Read-only file system
ROFS = 30,
/// Too many links
MLINK = 31,
/// Broken pipe
PIPE = 32,
// math software
/// Numerical argument out of domain
DOM = 33,
/// Result too large
RANGE = 34,
// non-blocking and interrupt i/o
/// Resource temporarily unavailable
/// This is the same code used for `WOULDBLOCK`.
AGAIN = 35,
/// Operation now in progress
INPROGRESS = 36,
/// Operation already in progress
ALREADY = 37,
// ipc/network software -- argument errors
/// Socket operation on non-socket
NOTSOCK = 38,
/// Destination address required
DESTADDRREQ = 39,
/// Message too long
MSGSIZE = 40,
/// Protocol wrong type for socket
PROTOTYPE = 41,
/// Protocol not available
NOPROTOOPT = 42,
/// Protocol not supported
PROTONOSUPPORT = 43,
/// Socket type not supported
SOCKTNOSUPPORT = 44,
/// Operation not supported
/// The same code is used for `NOTSUP`.
OPNOTSUPP = 45,
/// Protocol family not supported
PFNOSUPPORT = 46,
/// Address family not supported by protocol family
AFNOSUPPORT = 47,
/// Address already in use
ADDRINUSE = 48,
/// Can't assign requested address
// ipc/network software -- operational errors
ADDRNOTAVAIL = 49,
/// Network is down
NETDOWN = 50,
/// Network is unreachable
NETUNREACH = 51,
/// Network dropped connection on reset
NETRESET = 52,
/// Software caused connection abort
CONNABORTED = 53,
/// Connection reset by peer
CONNRESET = 54,
/// No buffer space available
NOBUFS = 55,
/// Socket is already connected
ISCONN = 56,
/// Socket is not connected
NOTCONN = 57,
/// Can't send after socket shutdown
SHUTDOWN = 58,
/// Too many references: can't splice
TOOMANYREFS = 59,
/// Operation timed out
TIMEDOUT = 60,
/// Connection refused
CONNREFUSED = 61,
/// Too many levels of symbolic links
LOOP = 62,
/// File name too long
NAMETOOLONG = 63,
/// Host is down
HOSTDOWN = 64,
/// No route to host
HOSTUNREACH = 65,
/// Directory not empty
// quotas & mush
NOTEMPTY = 66,
/// Too many processes
PROCLIM = 67,
/// Too many users
USERS = 68,
/// Disc quota exceeded
// Network File System
DQUOT = 69,
/// Stale NFS file handle
STALE = 70,
/// Too many levels of remote in path
REMOTE = 71,
/// RPC struct is bad
BADRPC = 72,
/// RPC version wrong
RPCMISMATCH = 73,
/// RPC prog. not avail
PROGUNAVAIL = 74,
/// Program version wrong
PROGMISMATCH = 75,
/// Bad procedure for program
PROCUNAVAIL = 76,
/// No locks available
NOLCK = 77,
/// Function not implemented
NOSYS = 78,
/// Inappropriate file type or format
FTYPE = 79,
/// Authentication error
AUTH = 80,
/// Need authenticator
NEEDAUTH = 81,
// Intelligent device errors
/// Device power is off
PWROFF = 82,
/// Device error, e.g. paper out
DEVERR = 83,
/// Value too large to be stored in data type
OVERFLOW = 84,
// Program loading errors
/// Bad executable
BADEXEC = 85,
/// Bad CPU type in executable
BADARCH = 86,
/// Shared library version mismatch
SHLIBVERS = 87,
/// Malformed Macho file
BADMACHO = 88,
/// Operation canceled
CANCELED = 89,
/// Identifier removed
IDRM = 90,
/// No message of desired type
NOMSG = 91,
/// Illegal byte sequence
ILSEQ = 92,
/// Attribute not found
NOATTR = 93,
/// Bad message
BADMSG = 94,
/// Reserved
MULTIHOP = 95,
/// No message available on STREAM
NODATA = 96,
/// Reserved
NOLINK = 97,
/// No STREAM resources
NOSR = 98,
/// Not a STREAM
NOSTR = 99,
/// Protocol error
PROTO = 100,
/// STREAM ioctl timeout
TIME = 101,
/// No such policy registered
NOPOLICY = 103,
/// State not recoverable
NOTRECOVERABLE = 104,
/// Previous owner died
OWNERDEAD = 105,
/// Interface output queue is full
QFULL = 106,
_,
};
pub const SIGSTKSZ = 131072;
pub const MINSIGSTKSZ = 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const HOST_NAME_MAX = 72;
pub const AT = struct {
pub const FDCWD = -2;
/// Use effective ids in access check
pub const EACCESS = 0x0010;
/// Act on the symlink itself not the target
pub const SYMLINK_NOFOLLOW = 0x0020;
/// Act on target of symlink
pub const SYMLINK_FOLLOW = 0x0040;
/// Path refers to directory
pub const REMOVEDIR = 0x0080;
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const RTLD = struct {
pub const LAZY = 0x1;
pub const NOW = 0x2;
pub const LOCAL = 0x4;
pub const GLOBAL = 0x8;
pub const NOLOAD = 0x10;
pub const NODELETE = 0x80;
pub const FIRST = 0x100;
pub const NEXT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -1)))));
pub const DEFAULT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -2)))));
pub const SELF = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -3)))));
pub const MAIN_ONLY = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -5)))));
};
pub const F = struct {
/// duplicate file descriptor
pub const DUPFD = 0;
/// get file descriptor flags
pub const GETFD = 1;
/// set file descriptor flags
pub const SETFD = 2;
/// get file status flags
pub const GETFL = 3;
/// set file status flags
pub const SETFL = 4;
/// get SIGIO/SIGURG proc/pgrp
pub const GETOWN = 5;
/// set SIGIO/SIGURG proc/pgrp
pub const SETOWN = 6;
/// get record locking information
pub const GETLK = 7;
/// set record locking information
pub const SETLK = 8;
/// F.SETLK; wait if blocked
pub const SETLKW = 9;
/// F.SETLK; wait if blocked, return on timeout
pub const SETLKWTIMEOUT = 10;
pub const FLUSH_DATA = 40;
/// Used for regression test
pub const CHKCLEAN = 41;
/// Preallocate storage
pub const PREALLOCATE = 42;
/// Truncate a file without zeroing space
pub const SETSIZE = 43;
/// Issue an advisory read async with no copy to user
pub const RDADVISE = 44;
/// turn read ahead off/on for this fd
pub const RDAHEAD = 45;
/// turn data caching off/on for this fd
pub const NOCACHE = 48;
/// file offset to device offset
pub const LOG2PHYS = 49;
/// return the full path of the fd
pub const GETPATH = 50;
/// fsync + ask the drive to flush to the media
pub const FULLFSYNC = 51;
/// find which component (if any) is a package
pub const PATHPKG_CHECK = 52;
/// "freeze" all fs operations
pub const FREEZE_FS = 53;
/// "thaw" all fs operations
pub const THAW_FS = 54;
/// turn data caching off/on (globally) for this file
pub const GLOBAL_NOCACHE = 55;
/// add detached signatures
pub const ADDSIGS = 59;
/// add signature from same file (used by dyld for shared libs)
pub const ADDFILESIGS = 61;
/// used in conjunction with F.NOCACHE to indicate that DIRECT, synchonous writes
/// should not be used (i.e. its ok to temporaily create cached pages)
pub const NODIRECT = 62;
///Get the protection class of a file from the EA, returns int
pub const GETPROTECTIONCLASS = 63;
///Set the protection class of a file for the EA, requires int
pub const SETPROTECTIONCLASS = 64;
///file offset to device offset, extended
pub const LOG2PHYS_EXT = 65;
///get record locking information, per-process
pub const GETLKPID = 66;
///Mark the file as being the backing store for another filesystem
pub const SETBACKINGSTORE = 70;
///return the full path of the FD, but error in specific mtmd circumstances
pub const GETPATH_MTMINFO = 71;
///Returns the code directory, with associated hashes, to the caller
pub const GETCODEDIR = 72;
///No SIGPIPE generated on EPIPE
pub const SETNOSIGPIPE = 73;
///Status of SIGPIPE for this fd
pub const GETNOSIGPIPE = 74;
///For some cases, we need to rewrap the key for AKS/MKB
pub const TRANSCODEKEY = 75;
///file being written to a by single writer... if throttling enabled, writes
///may be broken into smaller chunks with throttling in between
pub const SINGLE_WRITER = 76;
///Get the protection version number for this filesystem
pub const GETPROTECTIONLEVEL = 77;
///Add detached code signatures (used by dyld for shared libs)
pub const FINDSIGS = 78;
///Add signature from same file, only if it is signed by Apple (used by dyld for simulator)
pub const ADDFILESIGS_FOR_DYLD_SIM = 83;
///fsync + issue barrier to drive
pub const BARRIERFSYNC = 85;
///Add signature from same file, return end offset in structure on success
pub const ADDFILESIGS_RETURN = 97;
///Check if Library Validation allows this Mach-O file to be mapped into the calling process
pub const CHECK_LV = 98;
///Deallocate a range of the file
pub const PUNCHHOLE = 99;
///Trim an active file
pub const TRIM_ACTIVE_FILE = 100;
///mark the dup with FD_CLOEXEC
pub const DUPFD_CLOEXEC = 67;
/// shared or read lock
pub const RDLCK = 1;
/// unlock
pub const UNLCK = 2;
/// exclusive or write lock
pub const WRLCK = 3;
};
pub const FCNTL_FS_SPECIFIC_BASE = 0x00010000;
///close-on-exec flag
pub const FD_CLOEXEC = 1;
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
pub const IN = 0x001;
pub const PRI = 0x002;
pub const OUT = 0x004;
pub const RDNORM = 0x040;
pub const WRNORM = OUT;
pub const RDBAND = 0x080;
pub const WRBAND = 0x100;
pub const EXTEND = 0x0200;
pub const ATTRIB = 0x0400;
pub const NLINK = 0x0800;
pub const WRITE = 0x1000;
pub const ERR = 0x008;
pub const HUP = 0x010;
pub const NVAL = 0x020;
pub const STANDARD = IN | PRI | OUT | RDNORM | RDBAND | WRBAND | ERR | HUP | NVAL;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const MONOTONIC = 6;
pub const MONOTONIC_RAW = 4;
pub const MONOTONIC_RAW_APPROX = 5;
pub const UPTIME_RAW = 8;
pub const UPTIME_RAW_APPROX = 9;
pub const PROCESS_CPUTIME_ID = 12;
pub const THREAD_CPUTIME_ID = 16;
};
/// Max open files per process
/// https://opensource.apple.com/source/xnu/xnu-4903.221.2/bsd/sys/syslimits.h.auto.html
pub const OPEN_MAX = 10240;
pub const RUSAGE_SELF = 0;
pub const RUSAGE_CHILDREN = -1;
pub const rusage = extern struct {
utime: timeval,
stime: timeval,
maxrss: isize,
ixrss: isize,
idrss: isize,
isrss: isize,
minflt: isize,
majflt: isize,
nswap: isize,
inblock: isize,
oublock: isize,
msgsnd: isize,
msgrcv: isize,
nsignals: isize,
nvcsw: isize,
nivcsw: isize,
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
_,
pub const AS: rlimit_resource = .RSS;
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
// Term
pub const VEOF = 0;
pub const VEOL = 1;
pub const VEOL2 = 2;
pub const VERASE = 3;
pub const VWERASE = 4;
pub const VKILL = 5;
pub const VREPRINT = 6;
pub const VINTR = 8;
pub const VQUIT = 9;
pub const VSUSP = 10;
pub const VDSUSP = 11;
pub const VSTART = 12;
pub const VSTOP = 13;
pub const VLNEXT = 14;
pub const VDISCARD = 15;
pub const VMIN = 16;
pub const VTIME = 17;
pub const VSTATUS = 18;
pub const NCCS = 20; // 2 spares (7, 19)
pub const IGNBRK = 0x00000001; // ignore BREAK condition
pub const BRKINT = 0x00000002; // map BREAK to SIGINTR
pub const IGNPAR = 0x00000004; // ignore (discard) parity errors
pub const PARMRK = 0x00000008; // mark parity and framing errors
pub const INPCK = 0x00000010; // enable checking of parity errors
pub const ISTRIP = 0x00000020; // strip 8th bit off chars
pub const INLCR = 0x00000040; // map NL into CR
pub const IGNCR = 0x00000080; // ignore CR
pub const ICRNL = 0x00000100; // map CR to NL (ala CRMOD)
pub const IXON = 0x00000200; // enable output flow control
pub const IXOFF = 0x00000400; // enable input flow control
pub const IXANY = 0x00000800; // any char will restart after stop
pub const IMAXBEL = 0x00002000; // ring bell on input queue full
pub const IUTF8 = 0x00004000; // maintain state for UTF-8 VERASE
pub const OPOST = 0x00000001; //enable following output processing
pub const ONLCR = 0x00000002; // map NL to CR-NL (ala CRMOD)
pub const OXTABS = 0x00000004; // expand tabs to spaces
pub const ONOEOT = 0x00000008; // discard EOT's (^D) on output)
pub const OCRNL = 0x00000010; // map CR to NL on output
pub const ONOCR = 0x00000020; // no CR output at column 0
pub const ONLRET = 0x00000040; // NL performs CR function
pub const OFILL = 0x00000080; // use fill characters for delay
pub const NLDLY = 0x00000300; // \n delay
pub const TABDLY = 0x00000c04; // horizontal tab delay
pub const CRDLY = 0x00003000; // \r delay
pub const FFDLY = 0x00004000; // form feed delay
pub const BSDLY = 0x00008000; // \b delay
pub const VTDLY = 0x00010000; // vertical tab delay
pub const OFDEL = 0x00020000; // fill is DEL, else NUL
pub const NL0 = 0x00000000;
pub const NL1 = 0x00000100;
pub const NL2 = 0x00000200;
pub const NL3 = 0x00000300;
pub const TAB0 = 0x00000000;
pub const TAB1 = 0x00000400;
pub const TAB2 = 0x00000800;
pub const TAB3 = 0x00000004;
pub const CR0 = 0x00000000;
pub const CR1 = 0x00001000;
pub const CR2 = 0x00002000;
pub const CR3 = 0x00003000;
pub const FF0 = 0x00000000;
pub const FF1 = 0x00004000;
pub const BS0 = 0x00000000;
pub const BS1 = 0x00008000;
pub const VT0 = 0x00000000;
pub const VT1 = 0x00010000;
pub const CIGNORE = 0x00000001; // ignore control flags
pub const CSIZE = 0x00000300; // character size mask
pub const CS5 = 0x00000000; // 5 bits (pseudo)
pub const CS6 = 0x00000100; // 6 bits
pub const CS7 = 0x00000200; // 7 bits
pub const CS8 = 0x00000300; // 8 bits
pub const CSTOPB = 0x0000040; // send 2 stop bits
pub const CREAD = 0x00000800; // enable receiver
pub const PARENB = 0x00001000; // parity enable
pub const PARODD = 0x00002000; // odd parity, else even
pub const HUPCL = 0x00004000; // hang up on last close
pub const CLOCAL = 0x00008000; // ignore modem status lines
pub const CCTS_OFLOW = 0x00010000; // CTS flow control of output
pub const CRTSCTS = (CCTS_OFLOW | CRTS_IFLOW);
pub const CRTS_IFLOW = 0x00020000; // RTS flow control of input
pub const CDTR_IFLOW = 0x00040000; // DTR flow control of input
pub const CDSR_OFLOW = 0x00080000; // DSR flow control of output
pub const CCAR_OFLOW = 0x00100000; // DCD flow control of output
pub const MDMBUF = 0x00100000; // old name for CCAR_OFLOW
pub const ECHOKE = 0x00000001; // visual erase for line kill
pub const ECHOE = 0x00000002; // visually erase chars
pub const ECHOK = 0x00000004; // echo NL after line kill
pub const ECHO = 0x00000008; // enable echoing
pub const ECHONL = 0x00000010; // echo NL even if ECHO is off
pub const ECHOPRT = 0x00000020; // visual erase mode for hardcopy
pub const ECHOCTL = 0x00000040; // echo control chars as ^(Char)
pub const ISIG = 0x00000080; // enable signals INTR, QUIT, [D]SUSP
pub const ICANON = 0x00000100; // canonicalize input lines
pub const ALTWERASE = 0x00000200; // use alternate WERASE algorithm
pub const IEXTEN = 0x00000400; // enable DISCARD and LNEXT
pub const EXTPROC = 0x00000800; // external processing
pub const TOSTOP = 0x00400000; // stop background jobs from output
pub const FLUSHO = 0x00800000; // output being flushed (state)
pub const NOKERNINFO = 0x02000000; // no kernel output from VSTATUS
pub const PENDIN = 0x20000000; // XXX retype pending input (state)
pub const NOFLSH = 0x80000000; // don't flush after interrupt
pub const TCSANOW = 0; // make change immediate
pub const TCSADRAIN = 1; // drain output, then change
pub const TCSAFLUSH = 2; // drain output, flush input
pub const TCSASOFT = 0x10; // flag - don't alter h.w. state
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const B0 = 0;
pub const B50 = 50;
pub const B75 = 75;
pub const B110 = 110;
pub const B134 = 134;
pub const B150 = 150;
pub const B200 = 200;
pub const B300 = 300;
pub const B600 = 600;
pub const B1200 = 1200;
pub const B1800 = 1800;
pub const B2400 = 2400;
pub const B4800 = 4800;
pub const B9600 = 9600;
pub const B19200 = 19200;
pub const B38400 = 38400;
pub const B7200 = 7200;
pub const B14400 = 14400;
pub const B28800 = 28800;
pub const B57600 = 57600;
pub const B76800 = 76800;
pub const B115200 = 115200;
pub const B230400 = 230400;
pub const EXTA = 19200;
pub const EXTB = 38400;
pub const TCIFLUSH = 1;
pub const TCOFLUSH = 2;
pub const TCIOFLUSH = 3;
pub const TCOOFF = 1;
pub const TCOON = 2;
pub const TCIOFF = 3;
pub const TCION = 4;
pub const cc_t = u8;
pub const speed_t = u64;
pub const tcflag_t = u64;
pub const termios = extern struct {
iflag: tcflag_t, // input flags
oflag: tcflag_t, // output flags
cflag: tcflag_t, // control flags
lflag: tcflag_t, // local flags
cc: [NCCS]cc_t, // control chars
ispeed: speed_t align(8), // input speed
ospeed: speed_t, // output speed
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
pub const T = struct {
pub const IOCGWINSZ = ior(0x40000000, 't', 104, @sizeOf(winsize));
};
pub const IOCPARM_MASK = 0x1fff;
fn ior(inout: u32, group: usize, num: usize, len: usize) usize {
return (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num));
}
// CPU families mapping
pub const CPUFAMILY = enum(u32) {
UNKNOWN = 0,
POWERPC_G3 = 0xcee41549,
POWERPC_G4 = 0x77c184ae,
POWERPC_G5 = 0xed76d8aa,
INTEL_6_13 = 0xaa33392b,
INTEL_PENRYN = 0x78ea4fbc,
INTEL_NEHALEM = 0x6b5a4cd2,
INTEL_WESTMERE = 0x573b5eec,
INTEL_SANDYBRIDGE = 0x5490b78c,
INTEL_IVYBRIDGE = 0x1f65e835,
INTEL_HASWELL = 0x10b282dc,
INTEL_BROADWELL = 0x582ed09c,
INTEL_SKYLAKE = 0x37fc219f,
INTEL_KABYLAKE = 0x0f817246,
ARM_9 = 0xe73283ae,
ARM_11 = 0x8ff620d8,
ARM_XSCALE = 0x53b005f5,
ARM_12 = 0xbd1b0ae9,
ARM_13 = 0x0cc90e64,
ARM_14 = 0x96077ef1,
ARM_15 = 0xa8511bca,
ARM_SWIFT = 0x1e2d6381,
ARM_CYCLONE = 0x37a09642,
ARM_TYPHOON = 0x2c91a47e,
ARM_TWISTER = 0x92fb37c8,
ARM_HURRICANE = 0x67ceee93,
ARM_MONSOON_MISTRAL = 0xe81e7ef6,
ARM_VORTEX_TEMPEST = 0x07d34b9f,
ARM_LIGHTNING_THUNDER = 0x462504d2,
ARM_FIRESTORM_ICESTORM = 0x1b588bb3,
_,
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/haiku.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
extern "c" fn _errnop() *c_int;
pub const _errno = _errnop;
pub extern "c" fn find_directory(which: c_int, volume: i32, createIt: bool, path_ptr: [*]u8, length: i32) u64;
pub extern "c" fn find_thread(thread_name: ?*anyopaque) i32;
pub extern "c" fn get_system_info(system_info: *system_info) usize;
// TODO revisit if abi changes or better option becomes apparent
pub extern "c" fn _get_next_image_info(team: c_int, cookie: *i32, image_info: *image_info) usize;
pub extern "c" fn _kern_read_dir(fd: c_int, buf_ptr: [*]u8, nbytes: usize, maxcount: u32) usize;
pub extern "c" fn _kern_read_stat(fd: c_int, path_ptr: [*]u8, traverse_link: bool, st: *Stat, stat_size: i32) usize;
pub extern "c" fn _kern_get_current_team() i32;
pub const sem_t = extern struct {
_magic: u32,
_kern: extern struct {
_count: u32,
_flags: u32,
},
_padding: u32,
};
pub const pthread_attr_t = extern struct {
__detach_state: i32,
__sched_priority: i32,
__stack_size: i32,
__guard_size: i32,
__stack_address: ?*anyopaque,
};
pub const pthread_mutex_t = extern struct {
flags: u32 = 0,
lock: i32 = 0,
unused: i32 = -42,
owner: i32 = -1,
owner_count: i32 = 0,
};
pub const pthread_cond_t = extern struct {
flags: u32 = 0,
unused: i32 = -42,
mutex: ?*anyopaque = null,
waiter_count: i32 = 0,
lock: i32 = 0,
};
pub const pthread_rwlock_t = extern struct {
flags: u32 = 0,
owner: i32 = -1,
lock_sem: i32 = 0,
lock_count: i32 = 0,
reader_count: i32 = 0,
writer_count: i32 = 0,
waiters: [2]?*anyopaque = [_]?*anyopaque{ null, null },
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const uid_t = u32;
pub const gid_t = u32;
pub const mode_t = c_uint;
pub const socklen_t = u32;
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: usize,
// TODO ext
};
// Modes and flags for dlopen()
// include/dlfcn.h
pub const POLL = struct {
pub const IN = 0x0001;
pub const ERR = 0x0004;
pub const NVAL = 0x1000;
pub const HUP = 0x0080;
};
pub const RTLD = struct {
/// Bind function calls lazily.
pub const LAZY = 1;
/// Bind function calls immediately.
pub const NOW = 2;
pub const MODEMASK = 0x3;
/// Make symbols globally available.
pub const GLOBAL = 0x100;
/// Opposite of GLOBAL, and the default.
pub const LOCAL = 0;
/// Trace loaded objects and exit.
pub const TRACE = 0x200;
/// Do not remove members.
pub const NODELETE = 0x01000;
/// Do not load if not already loaded.
pub const NOLOAD = 0x02000;
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
l_sysid: i32,
__unused: [4]u8,
};
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: i32,
events: i16,
revents: i16,
};
pub const Stat = extern struct {
dev: i32,
ino: u64,
mode: u32,
nlink: i32,
uid: i32,
gid: i32,
size: i64,
rdev: i32,
blksize: i32,
atim: timespec,
mtim: timespec,
ctim: timespec,
crtim: timespec,
st_type: u32,
blocks: i64,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
pub fn crtime(self: @This()) timespec {
return self.crtim;
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const dirent = extern struct {
d_dev: i32,
d_pdev: i32,
d_ino: i64,
d_pino: i64,
d_reclen: u16,
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const image_info = extern struct {
id: u32,
type: u32,
sequence: i32,
init_order: i32,
init_routine: *anyopaque,
term_routine: *anyopaque,
device: i32,
node: i32,
name: [1024]u8,
text: *anyopaque,
data: *anyopaque,
text_size: i32,
data_size: i32,
api_version: i32,
abi: i32,
};
pub const system_info = extern struct {
boot_time: i64,
cpu_count: u32,
max_pages: u64,
used_pages: u64,
cached_pages: u64,
block_cache_pages: u64,
ignored_pages: u64,
needed_memory: u64,
free_memory: u64,
max_swap_pages: u64,
free_swap_pages: u64,
page_faults: u32,
max_sems: u32,
used_sems: u32,
max_ports: u32,
used_ports: u32,
max_threads: u32,
used_threads: u32,
max_teams: u32,
used_teams: u32,
kernel_name: [256]u8,
kernel_build_date: [32]u8,
kernel_build_time: [32]u8,
kernel_version: i64,
abi: u32,
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const sockaddr = extern struct {
/// total length
len: u8,
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
pub const un = extern struct {
len: u8 = @sizeOf(un),
family: sa_family_t = AF.UNIX,
path: [104]u8,
};
};
pub const CTL = struct {
pub const KERN = 1;
pub const DEBUG = 5;
};
pub const KERN = struct {
pub const PROC = 14; // struct: process entries
pub const PROC_PATHNAME = 12; // path to executable
};
pub const PATH_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const MONOTONIC = 0;
pub const REALTIME = -1;
pub const PROCESS_CPUTIME_ID = -2;
pub const THREAD_CPUTIME_ID = -3;
};
pub const MAP = struct {
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const FIXED = 0x0010;
pub const STACK = 0x0400;
pub const NOSYNC = 0x0800;
pub const ANON = 0x1000;
pub const ANONYMOUS = ANON;
pub const FILE = 0;
pub const GUARD = 0x00002000;
pub const EXCL = 0x00004000;
pub const NOCORE = 0x00020000;
pub const PREFAULT_READ = 0x00040000;
pub const @"32BIT" = 0x00080000;
};
pub const W = struct {
pub const NOHANG = 0x1;
pub const UNTRACED = 0x2;
pub const STOPPED = 0x10;
pub const CONTINUED = 0x4;
pub const NOWAIT = 0x20;
pub const EXITED = 0x08;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast(s & 0xff));
}
pub fn TERMSIG(s: u32) u32 {
return (s >> 8) & 0xff;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return ((s >> 16) & 0xff) != 0;
}
pub fn IFSIGNALED(s: u32) bool {
return ((s >> 8) & 0xff) != 0;
}
};
pub const SA = struct {
pub const ONSTACK = 0x20;
pub const RESTART = 0x10;
pub const RESETHAND = 0x04;
pub const NOCLDSTOP = 0x01;
pub const NODEFER = 0x08;
pub const NOCLDWAIT = 0x02;
pub const SIGINFO = 0x40;
pub const NOMASK = NODEFER;
pub const STACK = ONSTACK;
pub const ONESHOT = RESETHAND;
};
pub const SIG = struct {
pub const ERR = @as(fn (i32) callconv(.C) void, @ptrFromInt(maxInt(usize)));
pub const DFL = @as(fn (i32) callconv(.C) void, @ptrFromInt(0));
pub const IGN = @as(fn (i32) callconv(.C) void, @ptrFromInt(1));
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const CHLD = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const PIPE = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const STOP = 10;
pub const SEGV = 11;
pub const CONT = 12;
pub const TSTP = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const TTIN = 16;
pub const TTOU = 17;
pub const USR1 = 18;
pub const USR2 = 19;
pub const WINCH = 20;
pub const KILLTHR = 21;
pub const TRAP = 22;
pub const POLL = 23;
pub const PROF = 24;
pub const SYS = 25;
pub const URG = 26;
pub const VTALRM = 27;
pub const XCPU = 28;
pub const XFSZ = 29;
pub const BUS = 30;
pub const RESERVED1 = 31;
pub const RESERVED2 = 32;
// TODO: check
pub const RTMIN = 65;
pub const RTMAX = 126;
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const WORDS = 4;
pub const MAXSIG = 128;
pub inline fn IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn WORD(sig: usize) usize {
return IDX(sig) >> 5;
}
pub inline fn BIT(sig: usize) usize {
return 1 << (IDX(sig) & 31);
}
pub inline fn VALID(sig: usize) usize {
return sig <= MAXSIG and sig > 0;
}
};
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const ACCMODE = 0x0003;
pub const SHLOCK = 0x0010;
pub const EXLOCK = 0x0020;
pub const CREAT = 0x0200;
pub const EXCL = 0x0800;
pub const NOCTTY = 0x8000;
pub const TRUNC = 0x0400;
pub const APPEND = 0x0008;
pub const NONBLOCK = 0x0004;
pub const DSYNC = 0o10000;
pub const SYNC = 0x0080;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0x20000;
pub const NOFOLLOW = 0x0100;
pub const CLOEXEC = 0x00100000;
pub const ASYNC = 0x0040;
pub const DIRECT = 0x00010000;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
pub const NDELAY = NONBLOCK;
};
pub const F = struct {
pub const DUPFD = 0;
pub const GETFD = 1;
pub const SETFD = 2;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 11;
pub const SETLK = 12;
pub const SETLKW = 13;
pub const RDLCK = 1;
pub const WRLCK = 3;
pub const UNLCK = 2;
pub const SETOWN_EX = 15;
pub const GETOWN_EX = 16;
pub const GETOWNER_UIDS = 17;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
};
pub const SO = struct {
pub const DEBUG = 0x00000001;
pub const ACCEPTCONN = 0x00000002;
pub const REUSEADDR = 0x00000004;
pub const KEEPALIVE = 0x00000008;
pub const DONTROUTE = 0x00000010;
pub const BROADCAST = 0x00000020;
pub const USELOOPBACK = 0x00000040;
pub const LINGER = 0x00000080;
pub const OOBINLINE = 0x00000100;
pub const REUSEPORT = 0x00000200;
pub const TIMESTAMP = 0x00000400;
pub const NOSIGPIPE = 0x00000800;
pub const ACCEPTFILTER = 0x00001000;
pub const BINTIME = 0x00002000;
pub const NO_OFFLOAD = 0x00004000;
pub const NO_DDP = 0x00008000;
pub const REUSEPORT_LB = 0x00010000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const LABEL = 0x1009;
pub const PEERLABEL = 0x1010;
pub const LISTENQLIMIT = 0x1011;
pub const LISTENQLEN = 0x1012;
pub const LISTENINCQLEN = 0x1013;
pub const SETFIB = 0x1014;
pub const USER_COOKIE = 0x1015;
pub const PROTOCOL = 0x1016;
pub const PROTOTYPE = PROTOCOL;
pub const TS_CLOCK = 0x1017;
pub const MAX_PACING_RATE = 0x1018;
pub const DOMAIN = 0x1019;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NETBIOS = AF.NETBIOS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const XTP = AF.pseudo_XTP;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const SIP = AF.SIP;
pub const IPX = AF.IPX;
pub const RTIP = AF.pseudo_RTIP;
pub const PIP = AF.pseudo_PIP;
pub const ISDN = AF.ISDN;
pub const KEY = AF.pseudo_KEY;
pub const INET6 = AF.pseudo_INET6;
pub const NATM = AF.NATM;
pub const ATM = AF.ATM;
pub const NETGRAPH = AF.NETGRAPH;
pub const SLOW = AF.SLOW;
pub const SCLUSTER = AF.SCLUSTER;
pub const ARP = AF.ARP;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const IEEE80211 = AF.IEEE80211;
pub const INET_SDP = AF.INET_SDP;
pub const INET6_SDP = AF.INET6_SDP;
pub const MAX = AF.MAX;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const UNIX = 1;
pub const LOCAL = UNIX;
pub const FILE = LOCAL;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NETBIOS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const pseudo_XTP = 19;
pub const COIP = 20;
pub const CNT = 21;
pub const pseudo_RTIP = 22;
pub const IPX = 23;
pub const SIP = 24;
pub const pseudo_PIP = 25;
pub const ISDN = 26;
pub const E164 = ISDN;
pub const pseudo_KEY = 27;
pub const INET6 = 28;
pub const NATM = 29;
pub const ATM = 30;
pub const pseudo_HDRCMPLT = 31;
pub const NETGRAPH = 32;
pub const SLOW = 33;
pub const SCLUSTER = 34;
pub const ARP = 35;
pub const BLUETOOTH = 36;
pub const IEEE80211 = 37;
pub const INET_SDP = 40;
pub const INET6_SDP = 42;
pub const MAX = 42;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Process descriptors
pub const EVFILT_PROCDESC = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
pub const EVFILT_LIO = -10;
/// User events
pub const EVFILT_USER = -11;
/// Sendfile events
pub const EVFILT_SENDFILE = -12;
pub const EVFILT_EMPTY = -13;
pub const T = struct {
pub const CGETA = 0x8000;
pub const CSETA = 0x8001;
pub const CSETAW = 0x8004;
pub const CSETAF = 0x8003;
pub const CSBRK = 0x8005;
pub const CXONC = 0x8007;
pub const CFLSH = 0x8006;
pub const IOCSCTTY = 0x8017;
pub const IOCGPGRP = 0x8015;
pub const IOCSPGRP = 0x8016;
pub const IOCGWINSZ = 0x8012;
pub const IOCSWINSZ = 0x8013;
pub const IOCMGET = 0x8018;
pub const IOCMBIS = 0x8022;
pub const IOCMBIC = 0x8023;
pub const IOCMSET = 0x8019;
pub const FIONREAD = 0xbe000001;
pub const FIONBIO = 0xbe000000;
pub const IOCSBRK = 0x8020;
pub const IOCCBRK = 0x8021;
pub const IOCGSID = 0x8024;
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
const NSIG = 32;
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
/// signal handler
__sigaction_u: extern union {
__sa_handler: fn (i32) callconv(.C) void,
},
/// see signal options
sa_flags: u32,
/// signal mask to apply
sa_mask: sigset_t,
};
pub const sigset_t = extern struct {
__bits: [SIG.WORDS]u32,
};
pub const E = enum(i32) {
/// No error occurred.
SUCCESS = 0,
PERM = -0x7ffffff1, // Operation not permitted
NOENT = -0x7fff9ffd, // No such file or directory
SRCH = -0x7fff8ff3, // No such process
INTR = -0x7ffffff6, // Interrupted system call
IO = -0x7fffffff, // Input/output error
NXIO = -0x7fff8ff5, // Device not configured
@"2BIG" = -0x7fff8fff, // Argument list too long
NOEXEC = -0x7fffecfe, // Exec format error
CHILD = -0x7fff8ffe, // No child processes
DEADLK = -0x7fff8ffd, // Resource deadlock avoided
NOMEM = -0x80000000, // Cannot allocate memory
ACCES = -0x7ffffffe, // Permission denied
FAULT = -0x7fffecff, // Bad address
BUSY = -0x7ffffff2, // Device busy
EXIST = -0x7fff9ffe, // File exists
XDEV = -0x7fff9ff5, // Cross-device link
NODEV = -0x7fff8ff9, // Operation not supported by device
NOTDIR = -0x7fff9ffb, // Not a directory
ISDIR = -0x7fff9ff7, // Is a directory
INVAL = -0x7ffffffb, // Invalid argument
NFILE = -0x7fff8ffa, // Too many open files in system
MFILE = -0x7fff9ff6, // Too many open files
NOTTY = -0x7fff8ff6, // Inappropriate ioctl for device
TXTBSY = -0x7fff8fc5, // Text file busy
FBIG = -0x7fff8ffc, // File too large
NOSPC = -0x7fff9ff9, // No space left on device
SPIPE = -0x7fff8ff4, // Illegal seek
ROFS = -0x7fff9ff8, // Read-only filesystem
MLINK = -0x7fff8ffb, // Too many links
PIPE = -0x7fff9ff3, // Broken pipe
BADF = -0x7fffa000, // Bad file descriptor
// math software
DOM = 33, // Numerical argument out of domain
RANGE = 34, // Result too large
// non-blocking and interrupt i/o
/// Also used for `WOULDBLOCK`.
AGAIN = -0x7ffffff5,
INPROGRESS = -0x7fff8fdc,
ALREADY = -0x7fff8fdb,
// ipc/network software -- argument errors
NOTSOCK = 38, // Socket operation on non-socket
DESTADDRREQ = 39, // Destination address required
MSGSIZE = 40, // Message too long
PROTOTYPE = 41, // Protocol wrong type for socket
NOPROTOOPT = 42, // Protocol not available
PROTONOSUPPORT = 43, // Protocol not supported
SOCKTNOSUPPORT = 44, // Socket type not supported
/// Also used for `NOTSUP`.
OPNOTSUPP = 45, // Operation not supported
PFNOSUPPORT = 46, // Protocol family not supported
AFNOSUPPORT = 47, // Address family not supported by protocol family
ADDRINUSE = 48, // Address already in use
ADDRNOTAVAIL = 49, // Can't assign requested address
// ipc/network software -- operational errors
NETDOWN = 50, // Network is down
NETUNREACH = 51, // Network is unreachable
NETRESET = 52, // Network dropped connection on reset
CONNABORTED = 53, // Software caused connection abort
CONNRESET = 54, // Connection reset by peer
NOBUFS = 55, // No buffer space available
ISCONN = 56, // Socket is already connected
NOTCONN = 57, // Socket is not connected
SHUTDOWN = 58, // Can't send after socket shutdown
TOOMANYREFS = 59, // Too many references: can't splice
TIMEDOUT = 60, // Operation timed out
CONNREFUSED = 61, // Connection refused
LOOP = 62, // Too many levels of symbolic links
NAMETOOLONG = 63, // File name too long
// should be rearranged
HOSTDOWN = 64, // Host is down
HOSTUNREACH = 65, // No route to host
NOTEMPTY = 66, // Directory not empty
// quotas & mush
PROCLIM = 67, // Too many processes
USERS = 68, // Too many users
DQUOT = 69, // Disc quota exceeded
// Network File System
STALE = 70, // Stale NFS file handle
REMOTE = 71, // Too many levels of remote in path
BADRPC = 72, // RPC struct is bad
RPCMISMATCH = 73, // RPC version wrong
PROGUNAVAIL = 74, // RPC prog. not avail
PROGMISMATCH = 75, // Program version wrong
PROCUNAVAIL = 76, // Bad procedure for program
NOLCK = 77, // No locks available
NOSYS = 78, // Function not implemented
FTYPE = 79, // Inappropriate file type or format
AUTH = 80, // Authentication error
NEEDAUTH = 81, // Need authenticator
IDRM = 82, // Identifier removed
NOMSG = 83, // No message of desired type
OVERFLOW = 84, // Value too large to be stored in data type
CANCELED = 85, // Operation canceled
ILSEQ = 86, // Illegal byte sequence
NOATTR = 87, // Attribute not found
DOOFUS = 88, // Programming error
BADMSG = 89, // Bad message
MULTIHOP = 90, // Multihop attempted
NOLINK = 91, // Link has been severed
PROTO = 92, // Protocol error
NOTCAPABLE = 93, // Capabilities insufficient
CAPMODE = 94, // Not permitted in capability mode
NOTRECOVERABLE = 95, // State not recoverable
OWNERDEAD = 96, // Previous owner died
_,
};
pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {
.i386, .x86_64 => 2048,
.arm, .aarch64 => 4096,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
};
pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const HOST_NAME_MAX = 255;
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = -100;
/// Check access using effective user and group ID
pub const EACCESS = 0x0100;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x0200;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x0400;
/// Remove directory instead of file
pub const REMOVEDIR = 0x0800;
/// Fail if not under dirfd
pub const BENEATH = 0x1000;
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// control message protocol
pub const ICMP = 1;
/// tcp
pub const TCP = 6;
/// user datagram protocol
pub const UDP = 17;
/// IP6 header
pub const IPV6 = 41;
/// raw IP packet
pub const RAW = 255;
/// IP6 hop-by-hop options
pub const HOPOPTS = 0;
/// group mgmt protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IPv4 encapsulation
pub const IPV4 = 4;
/// for compatibility
pub const IPIP = IPV4;
/// Stream protocol II
pub const ST = 7;
/// exterior gateway protocol
pub const EGP = 8;
/// private interior gateway
pub const PIGP = 9;
/// BBN RCC Monitoring
pub const RCCMON = 10;
/// network voice protocol
pub const NVPII = 11;
/// pup
pub const PUP = 12;
/// Argus
pub const ARGUS = 13;
/// EMCON
pub const EMCON = 14;
/// Cross Net Debugger
pub const XNET = 15;
/// Chaos
pub const CHAOS = 16;
/// Multiplexing
pub const MUX = 18;
/// DCN Measurement Subsystems
pub const MEAS = 19;
/// Host Monitoring
pub const HMP = 20;
/// Packet Radio Measurement
pub const PRM = 21;
/// xns idp
pub const IDP = 22;
/// Trunk-1
pub const TRUNK1 = 23;
/// Trunk-2
pub const TRUNK2 = 24;
/// Leaf-1
pub const LEAF1 = 25;
/// Leaf-2
pub const LEAF2 = 26;
/// Reliable Data
pub const RDP = 27;
/// Reliable Transaction
pub const IRTP = 28;
/// tp-4 w/ class negotiation
pub const TP = 29;
/// Bulk Data Transfer
pub const BLT = 30;
/// Network Services
pub const NSP = 31;
/// Merit Internodal
pub const INP = 32;
/// Datagram Congestion Control Protocol
pub const DCCP = 33;
/// Third Party Connect
pub const @"3PC" = 34;
/// InterDomain Policy Routing
pub const IDPR = 35;
/// XTP
pub const XTP = 36;
/// Datagram Delivery
pub const DDP = 37;
/// Control Message Transport
pub const CMTP = 38;
/// TP++ Transport
pub const TPXX = 39;
/// IL transport protocol
pub const IL = 40;
/// Source Demand Routing
pub const SDRP = 42;
/// IP6 routing header
pub const ROUTING = 43;
/// IP6 fragmentation header
pub const FRAGMENT = 44;
/// InterDomain Routing
pub const IDRP = 45;
/// resource reservation
pub const RSVP = 46;
/// General Routing Encap.
pub const GRE = 47;
/// Mobile Host Routing
pub const MHRP = 48;
/// BHA
pub const BHA = 49;
/// IP6 Encap Sec. Payload
pub const ESP = 50;
/// IP6 Auth Header
pub const AH = 51;
/// Integ. Net Layer Security
pub const INLSP = 52;
/// IP with encryption
pub const SWIPE = 53;
/// Next Hop Resolution
pub const NHRP = 54;
/// IP Mobility
pub const MOBILE = 55;
/// Transport Layer Security
pub const TLSP = 56;
/// SKIP
pub const SKIP = 57;
/// ICMP6
pub const ICMPV6 = 58;
/// IP6 no next header
pub const NONE = 59;
/// IP6 destination option
pub const DSTOPTS = 60;
/// any host internal protocol
pub const AHIP = 61;
/// CFTP
pub const CFTP = 62;
/// "hello" routing protocol
pub const HELLO = 63;
/// SATNET/Backroom EXPAK
pub const SATEXPAK = 64;
/// Kryptolan
pub const KRYPTOLAN = 65;
/// Remote Virtual Disk
pub const RVD = 66;
/// Pluribus Packet Core
pub const IPPC = 67;
/// Any distributed FS
pub const ADFS = 68;
/// Satnet Monitoring
pub const SATMON = 69;
/// VISA Protocol
pub const VISA = 70;
/// Packet Core Utility
pub const IPCV = 71;
/// Comp. Prot. Net. Executive
pub const CPNX = 72;
/// Comp. Prot. HeartBeat
pub const CPHB = 73;
/// Wang Span Network
pub const WSN = 74;
/// Packet Video Protocol
pub const PVP = 75;
/// BackRoom SATNET Monitoring
pub const BRSATMON = 76;
/// Sun net disk proto (temp.)
pub const ND = 77;
/// WIDEBAND Monitoring
pub const WBMON = 78;
/// WIDEBAND EXPAK
pub const WBEXPAK = 79;
/// ISO cnlp
pub const EON = 80;
/// VMTP
pub const VMTP = 81;
/// Secure VMTP
pub const SVMTP = 82;
/// Banyon VINES
pub const VINES = 83;
/// TTP
pub const TTP = 84;
/// NSFNET-IGP
pub const IGP = 85;
/// dissimilar gateway prot.
pub const DGP = 86;
/// TCF
pub const TCF = 87;
/// Cisco/GXS IGRP
pub const IGRP = 88;
/// OSPFIGP
pub const OSPFIGP = 89;
/// Strite RPC protocol
pub const SRPC = 90;
/// Locus Address Resoloution
pub const LARP = 91;
/// Multicast Transport
pub const MTP = 92;
/// AX.25 Frames
pub const AX25 = 93;
/// IP encapsulated in IP
pub const IPEIP = 94;
/// Mobile Int.ing control
pub const MICP = 95;
/// Semaphore Comm. security
pub const SCCSP = 96;
/// Ethernet IP encapsulation
pub const ETHERIP = 97;
/// encapsulation header
pub const ENCAP = 98;
/// any private encr. scheme
pub const APES = 99;
/// GMTP
pub const GMTP = 100;
/// payload compression (IPComp)
pub const IPCOMP = 108;
/// SCTP
pub const SCTP = 132;
/// IPv6 Mobility Header
pub const MH = 135;
/// UDP-Lite
pub const UDPLITE = 136;
/// IP6 Host Identity Protocol
pub const HIP = 139;
/// IP6 Shim6 Protocol
pub const SHIM6 = 140;
/// Protocol Independent Mcast
pub const PIM = 103;
/// CARP
pub const CARP = 112;
/// PGM
pub const PGM = 113;
/// MPLS-in-IP
pub const MPLS = 137;
/// PFSYNC
pub const PFSYNC = 240;
/// Reserved
pub const RESERVED_253 = 253;
/// Reserved
pub const RESERVED_254 = 254;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
NPTS = 11,
SWAP = 12,
KQUEUES = 13,
UMTXP = 14,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
// TODO fill out if needed
pub const directory_which = enum(c_int) {
B_USER_SETTINGS_DIRECTORY = 0xbbe,
_,
};
pub const cc_t = u8;
pub const speed_t = u8;
pub const tcflag_t = u32;
pub const NCCS = 32;
pub const termios = extern struct {
c_iflag: tcflag_t,
c_oflag: tcflag_t,
c_cflag: tcflag_t,
c_lflag: tcflag_t,
c_line: cc_t,
c_ispeed: speed_t,
c_ospeed: speed_t,
cc_t: [NCCS]cc_t,
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/dragonfly.zig | const std = @import("../std.zig");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
extern "c" threadlocal var errno: c_int;
pub fn _errno() *c_int {
return &errno;
}
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn lwp_gettid() c_int;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub const pthread_mutex_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_cond_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_attr_t = extern struct { // copied from freebsd
__size: [56]u8,
__align: c_long,
};
pub const sem_t = ?*opaque {};
// See:
// - https://gitweb.dragonflybsd.org/dragonfly.git/blob/HEAD:/include/unistd.h
// - https://gitweb.dragonflybsd.org/dragonfly.git/blob/HEAD:/sys/sys/types.h
// TODO: mode_t should probably be changed to a u16, audit pid_t/off_t as well
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const off_t = c_long;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;
pub const time_t = isize;
pub const suseconds_t = c_long;
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1,
NOENT = 2,
SRCH = 3,
INTR = 4,
IO = 5,
NXIO = 6,
@"2BIG" = 7,
NOEXEC = 8,
BADF = 9,
CHILD = 10,
DEADLK = 11,
NOMEM = 12,
ACCES = 13,
FAULT = 14,
NOTBLK = 15,
BUSY = 16,
EXIST = 17,
XDEV = 18,
NODEV = 19,
NOTDIR = 20,
ISDIR = 21,
INVAL = 22,
NFILE = 23,
MFILE = 24,
NOTTY = 25,
TXTBSY = 26,
FBIG = 27,
NOSPC = 28,
SPIPE = 29,
ROFS = 30,
MLINK = 31,
PIPE = 32,
DOM = 33,
RANGE = 34,
/// This code is also used for `WOULDBLOCK`.
AGAIN = 35,
INPROGRESS = 36,
ALREADY = 37,
NOTSOCK = 38,
DESTADDRREQ = 39,
MSGSIZE = 40,
PROTOTYPE = 41,
NOPROTOOPT = 42,
PROTONOSUPPORT = 43,
SOCKTNOSUPPORT = 44,
/// This code is also used for `NOTSUP`.
OPNOTSUPP = 45,
PFNOSUPPORT = 46,
AFNOSUPPORT = 47,
ADDRINUSE = 48,
ADDRNOTAVAIL = 49,
NETDOWN = 50,
NETUNREACH = 51,
NETRESET = 52,
CONNABORTED = 53,
CONNRESET = 54,
NOBUFS = 55,
ISCONN = 56,
NOTCONN = 57,
SHUTDOWN = 58,
TOOMANYREFS = 59,
TIMEDOUT = 60,
CONNREFUSED = 61,
LOOP = 62,
NAMETOOLONG = 63,
HOSTDOWN = 64,
HOSTUNREACH = 65,
NOTEMPTY = 66,
PROCLIM = 67,
USERS = 68,
DQUOT = 69,
STALE = 70,
REMOTE = 71,
BADRPC = 72,
RPCMISMATCH = 73,
PROGUNAVAIL = 74,
PROGMISMATCH = 75,
PROCUNAVAIL = 76,
NOLCK = 77,
NOSYS = 78,
FTYPE = 79,
AUTH = 80,
NEEDAUTH = 81,
IDRM = 82,
NOMSG = 83,
OVERFLOW = 84,
CANCELED = 85,
ILSEQ = 86,
NOATTR = 87,
DOOFUS = 88,
BADMSG = 89,
MULTIHOP = 90,
NOLINK = 91,
PROTO = 92,
NOMEDIUM = 93,
ASYNC = 99,
_,
};
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const MAP = struct {
pub const FILE = 0;
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const ANONYMOUS = ANON;
pub const COPY = PRIVATE;
pub const SHARED = 1;
pub const PRIVATE = 2;
pub const FIXED = 16;
pub const RENAME = 32;
pub const NORESERVE = 64;
pub const INHERIT = 128;
pub const NOEXTEND = 256;
pub const HASSEMAPHORE = 512;
pub const STACK = 1024;
pub const NOSYNC = 2048;
pub const ANON = 4096;
pub const VPAGETABLE = 8192;
pub const TRYFIXED = 65536;
pub const NOCORE = 131072;
pub const SIZEALIGN = 262144;
};
pub const W = struct {
pub const NOHANG = 0x0001;
pub const UNTRACED = 0x0002;
pub const CONTINUED = 0x0004;
pub const STOPPED = UNTRACED;
pub const NOWAIT = 0x0008;
pub const EXITED = 0x0010;
pub const TRAPPED = 0x0020;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast((s & 0xff00) >> 8));
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return @as(u16, @truncate((((s & 0xffff) *% 0x10001) >> 8))) > 0x7f00;
}
pub fn IFSIGNALED(s: u32) bool {
return (s & 0xffff) -% 1 < 0xff;
}
};
pub const SA = struct {
pub const ONSTACK = 0x0001;
pub const RESTART = 0x0002;
pub const RESETHAND = 0x0004;
pub const NODEFER = 0x0010;
pub const NOCLDWAIT = 0x0020;
pub const SIGINFO = 0x0040;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = KERN.IOV_MAX;
pub const ino_t = c_ulong;
pub const Stat = extern struct {
ino: ino_t,
nlink: c_uint,
dev: c_uint,
mode: c_ushort,
padding1: u16,
uid: uid_t,
gid: gid_t,
rdev: c_uint,
atim: timespec,
mtim: timespec,
ctim: timespec,
size: c_ulong,
blocks: i64,
blksize: u32,
flags: u32,
gen: u32,
lspare: i32,
qspare1: i64,
qspare2: i64,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: c_long,
tv_nsec: c_long,
};
pub const timeval = extern struct {
/// seconds
tv_sec: time_t,
/// microseconds
tv_usec: suseconds_t,
};
pub const CTL = struct {
pub const UNSPEC = 0;
pub const KERN = 1;
pub const VM = 2;
pub const VFS = 3;
pub const NET = 4;
pub const DEBUG = 5;
pub const HW = 6;
pub const MACHDEP = 7;
pub const USER = 8;
pub const LWKT = 10;
pub const MAXID = 11;
pub const MAXNAME = 12;
};
pub const KERN = struct {
pub const PROC_ALL = 0;
pub const OSTYPE = 1;
pub const PROC_PID = 1;
pub const OSRELEASE = 2;
pub const PROC_PGRP = 2;
pub const OSREV = 3;
pub const PROC_SESSION = 3;
pub const VERSION = 4;
pub const PROC_TTY = 4;
pub const MAXVNODES = 5;
pub const PROC_UID = 5;
pub const MAXPROC = 6;
pub const PROC_RUID = 6;
pub const MAXFILES = 7;
pub const PROC_ARGS = 7;
pub const ARGMAX = 8;
pub const PROC_CWD = 8;
pub const PROC_PATHNAME = 9;
pub const SECURELVL = 9;
pub const PROC_SIGTRAMP = 10;
pub const HOSTNAME = 10;
pub const HOSTID = 11;
pub const CLOCKRATE = 12;
pub const VNODE = 13;
pub const PROC = 14;
pub const FILE = 15;
pub const PROC_FLAGMASK = 16;
pub const PROF = 16;
pub const PROC_FLAG_LWP = 16;
pub const POSIX1 = 17;
pub const NGROUPS = 18;
pub const JOB_CONTROL = 19;
pub const SAVED_IDS = 20;
pub const BOOTTIME = 21;
pub const NISDOMAINNAME = 22;
pub const UPDATEINTERVAL = 23;
pub const OSRELDATE = 24;
pub const NTP_PLL = 25;
pub const BOOTFILE = 26;
pub const MAXFILESPERPROC = 27;
pub const MAXPROCPERUID = 28;
pub const DUMPDEV = 29;
pub const IPC = 30;
pub const DUMMY = 31;
pub const PS_STRINGS = 32;
pub const USRSTACK = 33;
pub const LOGSIGEXIT = 34;
pub const IOV_MAX = 35;
pub const MAXPOSIXLOCKSPERUID = 36;
pub const MAXID = 37;
};
pub const HOST_NAME_MAX = 255;
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
pub const RDONLY = 0;
pub const NDELAY = NONBLOCK;
pub const WRONLY = 1;
pub const RDWR = 2;
pub const ACCMODE = 3;
pub const NONBLOCK = 4;
pub const APPEND = 8;
pub const SHLOCK = 16;
pub const EXLOCK = 32;
pub const ASYNC = 64;
pub const FSYNC = 128;
pub const SYNC = 128;
pub const NOFOLLOW = 256;
pub const CREAT = 512;
pub const TRUNC = 1024;
pub const EXCL = 2048;
pub const NOCTTY = 32768;
pub const DIRECT = 65536;
pub const CLOEXEC = 131072;
pub const FBLOCKING = 262144;
pub const FNONBLOCKING = 524288;
pub const FAPPEND = 1048576;
pub const FOFFSET = 2097152;
pub const FSYNCWRITE = 4194304;
pub const FASYNCWRITE = 8388608;
pub const DIRECTORY = 134217728;
};
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
pub const DATA = 3;
pub const HOLE = 4;
};
pub const F = struct {
pub const ULOCK = 0;
pub const LOCK = 1;
pub const TLOCK = 2;
pub const TEST = 3;
pub const DUPFD = 0;
pub const GETFD = 1;
pub const RDLCK = 1;
pub const SETFD = 2;
pub const UNLCK = 2;
pub const WRLCK = 3;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 7;
pub const SETLK = 8;
pub const SETLKW = 9;
pub const DUP2FD = 10;
pub const DUPFD_CLOEXEC = 17;
pub const DUP2FD_CLOEXEC = 18;
};
pub const FD_CLOEXEC = 1;
pub const AT = struct {
pub const FDCWD = -328243;
pub const SYMLINK_NOFOLLOW = 1;
pub const REMOVEDIR = 2;
pub const EACCESS = 4;
pub const SYMLINK_FOLLOW = 8;
};
pub const dirent = extern struct {
d_fileno: c_ulong,
d_namlen: u16,
d_type: u8,
d_unused1: u8,
d_unused2: u32,
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
return (@offsetOf(dirent, "d_name") + self.d_namlen + 1 + 7) & ~@as(u16, 7);
}
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
pub const DBF = 15;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const VIRTUAL = 1;
pub const PROF = 2;
pub const MONOTONIC = 4;
pub const UPTIME = 5;
pub const UPTIME_PRECISE = 7;
pub const UPTIME_FAST = 8;
pub const REALTIME_PRECISE = 9;
pub const REALTIME_FAST = 10;
pub const MONOTONIC_PRECISE = 11;
pub const MONOTONIC_FAST = 12;
pub const SECOND = 13;
pub const THREAD_CPUTIME_ID = 14;
pub const PROCESS_CPUTIME_ID = 15;
};
pub const sockaddr = extern struct {
len: u8,
family: u8,
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
};
pub const Kevent = extern struct {
ident: usize,
filter: c_short,
flags: c_ushort,
fflags: c_uint,
data: isize,
udata: usize,
};
pub const EVFILT_FS = -10;
pub const EVFILT_USER = -9;
pub const EVFILT_EXCEPT = -8;
pub const EVFILT_TIMER = -7;
pub const EVFILT_SIGNAL = -6;
pub const EVFILT_PROC = -5;
pub const EVFILT_VNODE = -4;
pub const EVFILT_AIO = -3;
pub const EVFILT_WRITE = -2;
pub const EVFILT_READ = -1;
pub const EVFILT_SYSCOUNT = 10;
pub const EVFILT_MARKER = 15;
pub const EV_ADD = 1;
pub const EV_DELETE = 2;
pub const EV_ENABLE = 4;
pub const EV_DISABLE = 8;
pub const EV_ONESHOT = 16;
pub const EV_CLEAR = 32;
pub const EV_RECEIPT = 64;
pub const EV_DISPATCH = 128;
pub const EV_NODATA = 4096;
pub const EV_FLAG1 = 8192;
pub const EV_ERROR = 16384;
pub const EV_EOF = 32768;
pub const EV_SYSFLAGS = 61440;
pub const NOTE_FFNOP = 0;
pub const NOTE_TRACK = 1;
pub const NOTE_DELETE = 1;
pub const NOTE_LOWAT = 1;
pub const NOTE_TRACKERR = 2;
pub const NOTE_OOB = 2;
pub const NOTE_WRITE = 2;
pub const NOTE_EXTEND = 4;
pub const NOTE_CHILD = 4;
pub const NOTE_ATTRIB = 8;
pub const NOTE_LINK = 16;
pub const NOTE_RENAME = 32;
pub const NOTE_REVOKE = 64;
pub const NOTE_PDATAMASK = 1048575;
pub const NOTE_FFLAGSMASK = 16777215;
pub const NOTE_TRIGGER = 16777216;
pub const NOTE_EXEC = 536870912;
pub const NOTE_FFAND = 1073741824;
pub const NOTE_FORK = 1073741824;
pub const NOTE_EXIT = 2147483648;
pub const NOTE_FFOR = 2147483648;
pub const NOTE_FFCTRLMASK = 3221225472;
pub const NOTE_FFCOPY = 3221225472;
pub const NOTE_PCTRLMASK = 4026531840;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IREAD = IRUSR;
pub const IEXEC = IXUSR;
pub const IWRITE = IWUSR;
pub const IXOTH = 1;
pub const IWOTH = 2;
pub const IROTH = 4;
pub const IRWXO = 7;
pub const IXGRP = 8;
pub const IWGRP = 16;
pub const IRGRP = 32;
pub const IRWXG = 56;
pub const IXUSR = 64;
pub const IWUSR = 128;
pub const IRUSR = 256;
pub const IRWXU = 448;
pub const ISTXT = 512;
pub const BLKSIZE = 512;
pub const ISVTX = 512;
pub const ISGID = 1024;
pub const ISUID = 2048;
pub const IFIFO = 4096;
pub const IFCHR = 8192;
pub const IFDIR = 16384;
pub const IFBLK = 24576;
pub const IFREG = 32768;
pub const IFDB = 36864;
pub const IFLNK = 40960;
pub const IFSOCK = 49152;
pub const IFWHT = 57344;
pub const IFMT = 61440;
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
};
pub const BADSIG = SIG.ERR;
pub const SIG = struct {
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const IOT = ABRT;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const IO = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const INFO = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const THR = 32;
pub const CKPT = 33;
pub const CKPTEXIT = 34;
};
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: c_int,
uid: uid_t,
status: c_int,
addr: ?*anyopaque,
value: sigval,
band: c_long,
__spare__: [7]c_int,
};
pub const sigval = extern union {
sival_int: c_int,
sival_ptr: ?*anyopaque,
};
pub const _SIG_WORDS = 4;
pub const sigset_t = extern struct {
__bits: [_SIG_WORDS]c_uint,
};
pub const empty_sigset = sigset_t{ .__bits = [_]c_uint{0} ** _SIG_WORDS };
pub const sig_atomic_t = c_int;
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
flags: c_uint,
mask: sigset_t,
};
pub const sig_t = [*c]fn (c_int) callconv(.C) void;
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const MAXADDRLEN = 255;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const TIMESTAMP = 0x0400;
pub const NOSIGPIPE = 0x0800;
pub const ACCEPTFILTER = 0x1000;
pub const RERROR = 0x2000;
pub const PASSCRED = 0x4000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const SNDSPACE = 0x100a;
pub const CPUHINT = 0x1030;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const INET6 = AF.INET6;
pub const IMPLINK = AF.IMPLINK;
pub const ROUTE = AF.ROUTE;
pub const ISO = AF.ISO;
pub const PIP = AF.pseudo_PIP;
pub const CHAOS = AF.CHAOS;
pub const DATAKIT = AF.DATAKIT;
pub const INET = AF.INET;
pub const APPLETALK = AF.APPLETALK;
pub const SIP = AF.SIP;
pub const OSI = AF.ISO;
pub const CNT = AF.CNT;
pub const LINK = AF.LINK;
pub const HYLINK = AF.HYLINK;
pub const MAX = AF.MAX;
pub const KEY = AF.pseudo_KEY;
pub const PUP = AF.PUP;
pub const COIP = AF.COIP;
pub const SNA = AF.SNA;
pub const LOCAL = AF.LOCAL;
pub const NETBIOS = AF.NETBIOS;
pub const NATM = AF.NATM;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const UNSPEC = AF.UNSPEC;
pub const NETGRAPH = AF.NETGRAPH;
pub const ECMA = AF.ECMA;
pub const IPX = AF.IPX;
pub const DLI = AF.DLI;
pub const ATM = AF.ATM;
pub const CCITT = AF.CCITT;
pub const ISDN = AF.ISDN;
pub const RTIP = AF.pseudo_RTIP;
pub const LAT = AF.LAT;
pub const UNIX = PF.LOCAL;
pub const XTP = AF.pseudo_XTP;
pub const DECnet = AF.DECnet;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const OSI = ISO;
pub const UNIX = LOCAL;
pub const LOCAL = 1;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NETBIOS = 6;
pub const ISO = 7;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const COIP = 20;
pub const CNT = 21;
pub const IPX = 23;
pub const SIP = 24;
pub const ISDN = 26;
pub const INET6 = 28;
pub const NATM = 29;
pub const ATM = 30;
pub const NETGRAPH = 32;
pub const BLUETOOTH = 33;
pub const MPLS = 34;
pub const MAX = 36;
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const EAI = enum(c_int) {
ADDRFAMILY = 1,
AGAIN = 2,
BADFLAGS = 3,
FAIL = 4,
FAMILY = 5,
MEMORY = 6,
NODATA = 7,
NONAME = 8,
SERVICE = 9,
SOCKTYPE = 10,
SYSTEM = 11,
BADHINTS = 12,
PROTOCOL = 13,
OVERFLOW = 14,
_,
};
pub const AI = struct {
pub const PASSIVE = 0x00000001;
pub const CANONNAME = 0x00000002;
pub const NUMERICHOST = 0x00000004;
pub const NUMERICSERV = 0x00000008;
pub const MASK = PASSIVE | CANONNAME | NUMERICHOST | NUMERICSERV | ADDRCONFIG;
pub const ALL = 0x00000100;
pub const V4MAPPED_CFG = 0x00000200;
pub const ADDRCONFIG = 0x00000400;
pub const V4MAPPED = 0x00000800;
pub const DEFAULT = V4MAPPED_CFG | ADDRCONFIG;
};
pub const RTLD = struct {
pub const LAZY = 1;
pub const NOW = 2;
pub const MODEMASK = 0x3;
pub const GLOBAL = 0x100;
pub const LOCAL = 0;
pub const TRACE = 0x200;
pub const NODELETE = 0x01000;
pub const NOLOAD = 0x02000;
pub const NEXT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -1)))));
pub const DEFAULT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -2)))));
pub const SELF = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -3)))));
pub const ALL = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -4)))));
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const cmsghdr = extern struct {
cmsg_len: socklen_t,
cmsg_level: c_int,
cmsg_type: c_int,
};
pub const msghdr = extern struct {
msg_name: ?*anyopaque,
msg_namelen: socklen_t,
msg_iov: [*c]iovec,
msg_iovlen: c_int,
msg_control: ?*anyopaque,
msg_controllen: socklen_t,
msg_flags: c_int,
};
pub const cmsgcred = extern struct {
cmcred_pid: pid_t,
cmcred_uid: uid_t,
cmcred_euid: uid_t,
cmcred_gid: gid_t,
cmcred_ngroups: c_short,
cmcred_groups: [16]gid_t,
};
pub const sf_hdtr = extern struct {
headers: [*c]iovec,
hdr_cnt: c_int,
trailers: [*c]iovec,
trl_cnt: c_int,
};
pub const MS_SYNC = 0;
pub const MS_ASYNC = 1;
pub const MS_INVALIDATE = 2;
pub const POSIX_MADV_SEQUENTIAL = 2;
pub const POSIX_MADV_RANDOM = 1;
pub const POSIX_MADV_DONTNEED = 4;
pub const POSIX_MADV_NORMAL = 0;
pub const POSIX_MADV_WILLNEED = 3;
pub const MADV = struct {
pub const SEQUENTIAL = 2;
pub const CONTROL_END = SETMAP;
pub const DONTNEED = 4;
pub const RANDOM = 1;
pub const WILLNEED = 3;
pub const NORMAL = 0;
pub const CONTROL_START = INVAL;
pub const FREE = 5;
pub const NOSYNC = 6;
pub const AUTOSYNC = 7;
pub const NOCORE = 8;
pub const CORE = 9;
pub const INVAL = 10;
pub const SETMAP = 11;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: c_short,
l_whence: c_short,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const IPPROTO = struct {
pub const IP = 0;
pub const ICMP = 1;
pub const TCP = 6;
pub const UDP = 17;
pub const IPV6 = 41;
pub const RAW = 255;
pub const HOPOPTS = 0;
pub const IGMP = 2;
pub const GGP = 3;
pub const IPV4 = 4;
pub const IPIP = IPV4;
pub const ST = 7;
pub const EGP = 8;
pub const PIGP = 9;
pub const RCCMON = 10;
pub const NVPII = 11;
pub const PUP = 12;
pub const ARGUS = 13;
pub const EMCON = 14;
pub const XNET = 15;
pub const CHAOS = 16;
pub const MUX = 18;
pub const MEAS = 19;
pub const HMP = 20;
pub const PRM = 21;
pub const IDP = 22;
pub const TRUNK1 = 23;
pub const TRUNK2 = 24;
pub const LEAF1 = 25;
pub const LEAF2 = 26;
pub const RDP = 27;
pub const IRTP = 28;
pub const TP = 29;
pub const BLT = 30;
pub const NSP = 31;
pub const INP = 32;
pub const SEP = 33;
pub const @"3PC" = 34;
pub const IDPR = 35;
pub const XTP = 36;
pub const DDP = 37;
pub const CMTP = 38;
pub const TPXX = 39;
pub const IL = 40;
pub const SDRP = 42;
pub const ROUTING = 43;
pub const FRAGMENT = 44;
pub const IDRP = 45;
pub const RSVP = 46;
pub const GRE = 47;
pub const MHRP = 48;
pub const BHA = 49;
pub const ESP = 50;
pub const AH = 51;
pub const INLSP = 52;
pub const SWIPE = 53;
pub const NHRP = 54;
pub const MOBILE = 55;
pub const TLSP = 56;
pub const SKIP = 57;
pub const ICMPV6 = 58;
pub const NONE = 59;
pub const DSTOPTS = 60;
pub const AHIP = 61;
pub const CFTP = 62;
pub const HELLO = 63;
pub const SATEXPAK = 64;
pub const KRYPTOLAN = 65;
pub const RVD = 66;
pub const IPPC = 67;
pub const ADFS = 68;
pub const SATMON = 69;
pub const VISA = 70;
pub const IPCV = 71;
pub const CPNX = 72;
pub const CPHB = 73;
pub const WSN = 74;
pub const PVP = 75;
pub const BRSATMON = 76;
pub const ND = 77;
pub const WBMON = 78;
pub const WBEXPAK = 79;
pub const EON = 80;
pub const VMTP = 81;
pub const SVMTP = 82;
pub const VINES = 83;
pub const TTP = 84;
pub const IGP = 85;
pub const DGP = 86;
pub const TCF = 87;
pub const IGRP = 88;
pub const OSPFIGP = 89;
pub const SRPC = 90;
pub const LARP = 91;
pub const MTP = 92;
pub const AX25 = 93;
pub const IPEIP = 94;
pub const MICP = 95;
pub const SCCSP = 96;
pub const ETHERIP = 97;
pub const ENCAP = 98;
pub const APES = 99;
pub const GMTP = 100;
pub const IPCOMP = 108;
pub const PIM = 103;
pub const CARP = 112;
pub const PGM = 113;
pub const PFSYNC = 240;
pub const DIVERT = 254;
pub const MAX = 256;
pub const DONE = 257;
pub const UNKNOWN = 258;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
POSIXLOCKS = 11,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
/// Requestable events.
pub const IN = 0x0001;
pub const PRI = 0x0002;
pub const OUT = 0x0004;
pub const RDNORM = 0x0040;
pub const WRNORM = OUT;
pub const RDBAND = 0x0080;
pub const WRBAND = 0x0100;
/// These events are set if they occur regardless of whether they were requested.
pub const ERR = 0x0008;
pub const HUP = 0x0010;
pub const NVAL = 0x0020;
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/minix.zig | const builtin = @import("builtin");
pub const pthread_mutex_t = extern struct {
size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
};
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = switch (builtin.abi) {
.musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.cpu.arch) {
.aarch64 => 48,
.x86_64 => if (builtin.abi == .gnux32) 40 else 32,
.mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
else => if (@sizeOf(usize) == 8) 40 else 24,
},
else => unreachable,
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/linux.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const native_abi = builtin.abi;
const native_arch = builtin.cpu.arch;
const linux = std.os.linux;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
const FILE = std.c.FILE;
pub const AF = linux.AF;
pub const ARCH = linux.ARCH;
pub const AT = linux.AT;
pub const CLOCK = linux.CLOCK;
pub const CPU_COUNT = linux.CPU_COUNT;
pub const E = linux.E;
pub const Elf_Symndx = linux.Elf_Symndx;
pub const F = linux.F;
pub const FD_CLOEXEC = linux.FD_CLOEXEC;
pub const F_OK = linux.F_OK;
pub const Flock = linux.Flock;
pub const HOST_NAME_MAX = linux.HOST_NAME_MAX;
pub const IFNAMESIZE = linux.IFNAMESIZE;
pub const IOV_MAX = linux.IOV_MAX;
pub const IPPROTO = linux.IPPROTO;
pub const LOCK = linux.LOCK;
pub const MADV = linux.MADV;
pub const MAP = struct {
pub usingnamespace linux.MAP;
/// Only used by libc to communicate failure.
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
};
pub const MMAP2_UNIT = linux.MMAP2_UNIT;
pub const MSG = linux.MSG;
pub const NAME_MAX = linux.NAME_MAX;
pub const O = linux.O;
pub const PATH_MAX = linux.PATH_MAX;
pub const POLL = linux.POLL;
pub const PROT = linux.PROT;
pub const REG = linux.REG;
pub const RLIM = linux.RLIM;
pub const R_OK = linux.R_OK;
pub const S = linux.S;
pub const SA = linux.SA;
pub const SC = linux.SC;
pub const SEEK = linux.SEEK;
pub const SHUT = linux.SHUT;
pub const SIG = linux.SIG;
pub const SIOCGIFINDEX = linux.SIOCGIFINDEX;
pub const SO = linux.SO;
pub const SOCK = linux.SOCK;
pub const SOL = linux.SOL;
pub const STDERR_FILENO = linux.STDERR_FILENO;
pub const STDIN_FILENO = linux.STDIN_FILENO;
pub const STDOUT_FILENO = linux.STDOUT_FILENO;
pub const SYS = linux.SYS;
pub const Sigaction = linux.Sigaction;
pub const TCP = linux.TCP;
pub const VDSO = linux.VDSO;
pub const W = linux.W;
pub const W_OK = linux.W_OK;
pub const X_OK = linux.X_OK;
pub const addrinfo = linux.addrinfo;
pub const blkcnt_t = linux.blkcnt_t;
pub const blksize_t = linux.blksize_t;
pub const clock_t = linux.clock_t;
pub const cpu_set_t = linux.cpu_set_t;
pub const dev_t = linux.dev_t;
pub const dl_phdr_info = linux.dl_phdr_info;
pub const empty_sigset = linux.empty_sigset;
pub const epoll_event = linux.epoll_event;
pub const fd_t = linux.fd_t;
pub const gid_t = linux.gid_t;
pub const ifreq = linux.ifreq;
pub const ino_t = linux.ino_t;
pub const mcontext_t = linux.mcontext_t;
pub const mode_t = linux.mode_t;
pub const msghdr = linux.msghdr;
pub const msghdr_const = linux.msghdr_const;
pub const nfds_t = linux.nfds_t;
pub const nlink_t = linux.nlink_t;
pub const off_t = linux.off_t;
pub const pid_t = linux.pid_t;
pub const pollfd = linux.pollfd;
pub const rlim_t = linux.rlim_t;
pub const rlimit = linux.rlimit;
pub const rlimit_resource = linux.rlimit_resource;
pub const siginfo_t = linux.siginfo_t;
pub const sigset_t = linux.sigset_t;
pub const sockaddr = linux.sockaddr;
pub const socklen_t = linux.socklen_t;
pub const stack_t = linux.stack_t;
pub const termios = linux.termios;
pub const time_t = linux.time_t;
pub const timespec = linux.timespec;
pub const timeval = linux.timeval;
pub const timezone = linux.timezone;
pub const ucontext_t = linux.ucontext_t;
pub const uid_t = linux.uid_t;
pub const user_desc = linux.user_desc;
pub const utsname = linux.utsname;
pub const PR = linux.PR;
pub const _errno = switch (native_abi) {
.android => struct {
extern "c" var __errno: c_int;
fn getErrno() *c_int {
return &__errno;
}
}.getErrno,
else => struct {
extern "c" fn __errno_location() *c_int;
}.__errno_location,
};
pub const Stat = switch (native_arch) {
.sparcv9 => extern struct {
dev: u64,
ino: ino_t,
mode: u32,
nlink: usize,
uid: u32,
gid: u32,
rdev: u64,
__pad0: u32,
size: off_t,
blksize: isize,
blocks: i64,
atim: timespec,
mtim: timespec,
ctim: timespec,
__unused: [2]isize,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
},
.mips, .mipsel => extern struct {
dev: dev_t,
__pad0: [2]u32,
ino: ino_t,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
__pad1: [2]u32,
size: off_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
blksize: blksize_t,
__pad3: u32,
blocks: blkcnt_t,
__pad4: [14]u32,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
},
else => std.os.linux.Stat, // libc stat is the same as kernel stat.
};
pub const AI = struct {
pub const PASSIVE = 0x01;
pub const CANONNAME = 0x02;
pub const NUMERICHOST = 0x04;
pub const V4MAPPED = 0x08;
pub const ALL = 0x10;
pub const ADDRCONFIG = 0x20;
pub const NUMERICSERV = 0x400;
};
pub const NI = struct {
pub const NUMERICHOST = 0x01;
pub const NUMERICSERV = 0x02;
pub const NOFQDN = 0x04;
pub const NAMEREQD = 0x08;
pub const DGRAM = 0x10;
pub const NUMERICSCOPE = 0x100;
};
pub const EAI = enum(c_int) {
BADFLAGS = -1,
NONAME = -2,
AGAIN = -3,
FAIL = -4,
FAMILY = -6,
SOCKTYPE = -7,
SERVICE = -8,
MEMORY = -10,
SYSTEM = -11,
OVERFLOW = -12,
NODATA = -5,
ADDRFAMILY = -9,
INPROGRESS = -100,
CANCELED = -101,
NOTCANCELED = -102,
ALLDONE = -103,
INTR = -104,
IDN_ENCODE = -105,
_,
};
pub extern "c" fn fallocate64(fd: fd_t, mode: c_int, offset: off_t, len: off_t) c_int;
pub extern "c" fn fopen64(noalias filename: [*:0]const u8, noalias modes: [*:0]const u8) ?*FILE;
pub extern "c" fn fstat64(fd: fd_t, buf: *Stat) c_int;
pub extern "c" fn fstatat64(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
pub extern "c" fn ftruncate64(fd: c_int, length: off_t) c_int;
pub extern "c" fn getrlimit64(resource: rlimit_resource, rlim: *rlimit) c_int;
pub extern "c" fn lseek64(fd: fd_t, offset: i64, whence: c_int) i64;
pub extern "c" fn mmap64(addr: ?*align(std.mem.page_size) anyopaque, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: i64) *anyopaque;
pub extern "c" fn open64(path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn openat64(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn pread64(fd: fd_t, buf: [*]u8, nbyte: usize, offset: i64) isize;
pub extern "c" fn preadv64(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: i64) isize;
pub extern "c" fn pwrite64(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: i64) isize;
pub extern "c" fn pwritev64(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: i64) isize;
pub extern "c" fn sendfile64(out_fd: fd_t, in_fd: fd_t, offset: ?*i64, count: usize) isize;
pub extern "c" fn setrlimit64(resource: rlimit_resource, rlim: *const rlimit) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn sched_getaffinity(pid: c_int, size: usize, set: *cpu_set_t) c_int;
pub extern "c" fn eventfd(initval: c_uint, flags: c_uint) c_int;
pub extern "c" fn epoll_ctl(epfd: fd_t, op: c_uint, fd: fd_t, event: ?*epoll_event) c_int;
pub extern "c" fn epoll_create1(flags: c_uint) c_int;
pub extern "c" fn epoll_wait(epfd: fd_t, events: [*]epoll_event, maxevents: c_uint, timeout: c_int) c_int;
pub extern "c" fn epoll_pwait(
epfd: fd_t,
events: [*]epoll_event,
maxevents: c_int,
timeout: c_int,
sigmask: *const sigset_t,
) c_int;
pub extern "c" fn inotify_init1(flags: c_uint) c_int;
pub extern "c" fn inotify_add_watch(fd: fd_t, pathname: [*:0]const u8, mask: u32) c_int;
pub extern "c" fn inotify_rm_watch(fd: fd_t, wd: c_int) c_int;
/// See std.elf for constants for this
pub extern "c" fn getauxval(__type: c_ulong) c_ulong;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn fallocate(fd: fd_t, mode: c_int, offset: off_t, len: off_t) c_int;
pub extern "c" fn sendfile(
out_fd: fd_t,
in_fd: fd_t,
offset: ?*off_t,
count: usize,
) isize;
pub extern "c" fn copy_file_range(fd_in: fd_t, off_in: ?*i64, fd_out: fd_t, off_out: ?*i64, len: usize, flags: c_uint) isize;
pub extern "c" fn signalfd(fd: fd_t, mask: *const sigset_t, flags: c_uint) c_int;
pub extern "c" fn prlimit(pid: pid_t, resource: rlimit_resource, new_limit: *const rlimit, old_limit: *rlimit) c_int;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub extern "c" fn malloc_usable_size(?*const anyopaque) usize;
pub extern "c" fn madvise(
addr: *align(std.mem.page_size) anyopaque,
length: usize,
advice: c_uint,
) c_int;
pub const pthread_attr_t = extern struct {
__size: [56]u8,
__align: c_long,
};
pub const pthread_mutex_t = extern struct {
size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
};
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
pub const pthread_rwlock_t = switch (native_abi) {
.android => switch (@sizeOf(usize)) {
4 => extern struct {
lock: std.c.pthread_mutex_t = std.c.PTHREAD_MUTEX_INITIALIZER,
cond: std.c.pthread_cond_t = std.c.PTHREAD_COND_INITIALIZER,
numLocks: c_int = 0,
writerThreadId: c_int = 0,
pendingReaders: c_int = 0,
pendingWriters: c_int = 0,
attr: i32 = 0,
__reserved: [12]u8 = [_]u8{0} ** 2,
},
8 => extern struct {
numLocks: c_int = 0,
writerThreadId: c_int = 0,
pendingReaders: c_int = 0,
pendingWriters: c_int = 0,
attr: i32 = 0,
__reserved: [36]u8 = [_]u8{0} ** 36,
},
else => @compileError("impossible pointer size"),
},
else => extern struct {
size: [56]u8 align(@alignOf(usize)) = [_]u8{0} ** 56,
},
};
pub const sem_t = extern struct {
__size: [__SIZEOF_SEM_T]u8 align(@alignOf(usize)),
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = switch (native_abi) {
.musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (native_arch) {
.aarch64 => 48,
.x86_64 => if (native_abi == .gnux32) 40 else 32,
.mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
else => if (@sizeOf(usize) == 8) 40 else 24,
},
.android => if (@sizeOf(usize) == 8) 40 else 4,
else => @compileError("unsupported ABI"),
};
const __SIZEOF_SEM_T = 4 * @sizeOf(usize);
pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub const RTLD = struct {
pub const LAZY = 1;
pub const NOW = 2;
pub const NOLOAD = 4;
pub const NODELETE = 4096;
pub const GLOBAL = 256;
pub const LOCAL = 0;
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/emscripten.zig | pub const pthread_mutex_t = extern struct {
size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(4) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
};
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
pub const pthread_rwlock_t = extern struct {
size: [32]u8 align(4) = [_]u8{0} ** 32,
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = 28;
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/tokenizer.zig | const std = @import("std");
const mem = std.mem;
pub const Token = struct {
id: Id,
start: usize,
end: usize,
pub const Id = union(enum) {
Invalid,
Eof,
Nl,
Identifier,
/// special case for #include <...>
MacroString,
StringLiteral: StrKind,
CharLiteral: StrKind,
IntegerLiteral: NumSuffix,
FloatLiteral: NumSuffix,
Bang,
BangEqual,
Pipe,
PipePipe,
PipeEqual,
Equal,
EqualEqual,
LParen,
RParen,
LBrace,
RBrace,
LBracket,
RBracket,
Period,
Ellipsis,
Caret,
CaretEqual,
Plus,
PlusPlus,
PlusEqual,
Minus,
MinusMinus,
MinusEqual,
Asterisk,
AsteriskEqual,
Percent,
PercentEqual,
Arrow,
Colon,
Semicolon,
Slash,
SlashEqual,
Comma,
Ampersand,
AmpersandAmpersand,
AmpersandEqual,
QuestionMark,
AngleBracketLeft,
AngleBracketLeftEqual,
AngleBracketAngleBracketLeft,
AngleBracketAngleBracketLeftEqual,
AngleBracketRight,
AngleBracketRightEqual,
AngleBracketAngleBracketRight,
AngleBracketAngleBracketRightEqual,
Tilde,
LineComment,
MultiLineComment,
Hash,
HashHash,
Keyword_auto,
Keyword_break,
Keyword_case,
Keyword_char,
Keyword_const,
Keyword_continue,
Keyword_default,
Keyword_do,
Keyword_double,
Keyword_else,
Keyword_enum,
Keyword_extern,
Keyword_float,
Keyword_for,
Keyword_goto,
Keyword_if,
Keyword_int,
Keyword_long,
Keyword_register,
Keyword_return,
Keyword_short,
Keyword_signed,
Keyword_sizeof,
Keyword_static,
Keyword_struct,
Keyword_switch,
Keyword_typedef,
Keyword_union,
Keyword_unsigned,
Keyword_void,
Keyword_volatile,
Keyword_while,
// ISO C99
Keyword_bool,
Keyword_complex,
Keyword_imaginary,
Keyword_inline,
Keyword_restrict,
// ISO C11
Keyword_alignas,
Keyword_alignof,
Keyword_atomic,
Keyword_generic,
Keyword_noreturn,
Keyword_static_assert,
Keyword_thread_local,
// Preprocessor directives
Keyword_include,
Keyword_define,
Keyword_ifdef,
Keyword_ifndef,
Keyword_error,
Keyword_pragma,
pub fn symbol(id: std.meta.TagType(Id)) []const u8 {
return switch (id) {
.Invalid => "Invalid",
.Eof => "Eof",
.Nl => "NewLine",
.Identifier => "Identifier",
.MacroString => "MacroString",
.StringLiteral => "StringLiteral",
.CharLiteral => "CharLiteral",
.IntegerLiteral => "IntegerLiteral",
.FloatLiteral => "FloatLiteral",
.LineComment => "LineComment",
.MultiLineComment => "MultiLineComment",
.Bang => "!",
.BangEqual => "!=",
.Pipe => "|",
.PipePipe => "||",
.PipeEqual => "|=",
.Equal => "=",
.EqualEqual => "==",
.LParen => "(",
.RParen => ")",
.LBrace => "{",
.RBrace => "}",
.LBracket => "[",
.RBracket => "]",
.Period => ".",
.Ellipsis => "...",
.Caret => "^",
.CaretEqual => "^=",
.Plus => "+",
.PlusPlus => "++",
.PlusEqual => "+=",
.Minus => "-",
.MinusMinus => "--",
.MinusEqual => "-=",
.Asterisk => "*",
.AsteriskEqual => "*=",
.Percent => "%",
.PercentEqual => "%=",
.Arrow => "->",
.Colon => ":",
.Semicolon => ";",
.Slash => "/",
.SlashEqual => "/=",
.Comma => ",",
.Ampersand => "&",
.AmpersandAmpersand => "&&",
.AmpersandEqual => "&=",
.QuestionMark => "?",
.AngleBracketLeft => "<",
.AngleBracketLeftEqual => "<=",
.AngleBracketAngleBracketLeft => "<<",
.AngleBracketAngleBracketLeftEqual => "<<=",
.AngleBracketRight => ">",
.AngleBracketRightEqual => ">=",
.AngleBracketAngleBracketRight => ">>",
.AngleBracketAngleBracketRightEqual => ">>=",
.Tilde => "~",
.Hash => "#",
.HashHash => "##",
.Keyword_auto => "auto",
.Keyword_break => "break",
.Keyword_case => "case",
.Keyword_char => "char",
.Keyword_const => "const",
.Keyword_continue => "continue",
.Keyword_default => "default",
.Keyword_do => "do",
.Keyword_double => "double",
.Keyword_else => "else",
.Keyword_enum => "enum",
.Keyword_extern => "extern",
.Keyword_float => "float",
.Keyword_for => "for",
.Keyword_goto => "goto",
.Keyword_if => "if",
.Keyword_int => "int",
.Keyword_long => "long",
.Keyword_register => "register",
.Keyword_return => "return",
.Keyword_short => "short",
.Keyword_signed => "signed",
.Keyword_sizeof => "sizeof",
.Keyword_static => "static",
.Keyword_struct => "struct",
.Keyword_switch => "switch",
.Keyword_typedef => "typedef",
.Keyword_union => "union",
.Keyword_unsigned => "unsigned",
.Keyword_void => "void",
.Keyword_volatile => "volatile",
.Keyword_while => "while",
.Keyword_bool => "_Bool",
.Keyword_complex => "_Complex",
.Keyword_imaginary => "_Imaginary",
.Keyword_inline => "inline",
.Keyword_restrict => "restrict",
.Keyword_alignas => "_Alignas",
.Keyword_alignof => "_Alignof",
.Keyword_atomic => "_Atomic",
.Keyword_generic => "_Generic",
.Keyword_noreturn => "_Noreturn",
.Keyword_static_assert => "_Static_assert",
.Keyword_thread_local => "_Thread_local",
.Keyword_include => "include",
.Keyword_define => "define",
.Keyword_ifdef => "ifdef",
.Keyword_ifndef => "ifndef",
.Keyword_error => "error",
.Keyword_pragma => "pragma",
};
}
};
// TODO extensions
pub const keywords = std.ComptimeStringMap(Id, .{
.{ "auto", .Keyword_auto },
.{ "break", .Keyword_break },
.{ "case", .Keyword_case },
.{ "char", .Keyword_char },
.{ "const", .Keyword_const },
.{ "continue", .Keyword_continue },
.{ "default", .Keyword_default },
.{ "do", .Keyword_do },
.{ "double", .Keyword_double },
.{ "else", .Keyword_else },
.{ "enum", .Keyword_enum },
.{ "extern", .Keyword_extern },
.{ "float", .Keyword_float },
.{ "for", .Keyword_for },
.{ "goto", .Keyword_goto },
.{ "if", .Keyword_if },
.{ "int", .Keyword_int },
.{ "long", .Keyword_long },
.{ "register", .Keyword_register },
.{ "return", .Keyword_return },
.{ "short", .Keyword_short },
.{ "signed", .Keyword_signed },
.{ "sizeof", .Keyword_sizeof },
.{ "static", .Keyword_static },
.{ "struct", .Keyword_struct },
.{ "switch", .Keyword_switch },
.{ "typedef", .Keyword_typedef },
.{ "union", .Keyword_union },
.{ "unsigned", .Keyword_unsigned },
.{ "void", .Keyword_void },
.{ "volatile", .Keyword_volatile },
.{ "while", .Keyword_while },
// ISO C99
.{ "_Bool", .Keyword_bool },
.{ "_Complex", .Keyword_complex },
.{ "_Imaginary", .Keyword_imaginary },
.{ "inline", .Keyword_inline },
.{ "restrict", .Keyword_restrict },
// ISO C11
.{ "_Alignas", .Keyword_alignas },
.{ "_Alignof", .Keyword_alignof },
.{ "_Atomic", .Keyword_atomic },
.{ "_Generic", .Keyword_generic },
.{ "_Noreturn", .Keyword_noreturn },
.{ "_Static_assert", .Keyword_static_assert },
.{ "_Thread_local", .Keyword_thread_local },
// Preprocessor directives
.{ "include", .Keyword_include },
.{ "define", .Keyword_define },
.{ "ifdef", .Keyword_ifdef },
.{ "ifndef", .Keyword_ifndef },
.{ "error", .Keyword_error },
.{ "pragma", .Keyword_pragma },
});
// TODO do this in the preprocessor
pub fn getKeyword(bytes: []const u8, pp_directive: bool) ?Id {
if (keywords.get(bytes)) |id| {
switch (id) {
.Keyword_include,
.Keyword_define,
.Keyword_ifdef,
.Keyword_ifndef,
.Keyword_error,
.Keyword_pragma,
=> if (!pp_directive) return null,
else => {},
}
return id;
}
return null;
}
pub const NumSuffix = enum {
none,
f,
l,
u,
lu,
ll,
llu,
};
pub const StrKind = enum {
none,
wide,
utf_8,
utf_16,
utf_32,
};
};
pub const Tokenizer = struct {
buffer: []const u8,
index: usize = 0,
prev_tok_id: std.meta.TagType(Token.Id) = .Invalid,
pp_directive: bool = false,
pub fn next(self: *Tokenizer) Token {
var result = Token{
.id = .Eof,
.start = self.index,
.end = undefined,
};
var state: enum {
Start,
Cr,
BackSlash,
BackSlashCr,
u,
u8,
U,
L,
StringLiteral,
CharLiteralStart,
CharLiteral,
EscapeSequence,
CrEscape,
OctalEscape,
HexEscape,
UnicodeEscape,
Identifier,
Equal,
Bang,
Pipe,
Percent,
Asterisk,
Plus,
/// special case for #include <...>
MacroString,
AngleBracketLeft,
AngleBracketAngleBracketLeft,
AngleBracketRight,
AngleBracketAngleBracketRight,
Caret,
Period,
Period2,
Minus,
Slash,
Ampersand,
Hash,
LineComment,
MultiLineComment,
MultiLineCommentAsterisk,
Zero,
IntegerLiteralOct,
IntegerLiteralBinary,
IntegerLiteralBinaryFirst,
IntegerLiteralHex,
IntegerLiteralHexFirst,
IntegerLiteral,
IntegerSuffix,
IntegerSuffixU,
IntegerSuffixL,
IntegerSuffixLL,
IntegerSuffixUL,
FloatFraction,
FloatFractionHex,
FloatExponent,
FloatExponentDigits,
FloatSuffix,
} = .Start;
var string = false;
var counter: u32 = 0;
while (self.index < self.buffer.len) : (self.index += 1) {
const c = self.buffer[self.index];
switch (state) {
.Start => switch (c) {
'\n' => {
self.pp_directive = false;
result.id = .Nl;
self.index += 1;
break;
},
'\r' => {
state = .Cr;
},
'"' => {
result.id = .{ .StringLiteral = .none };
state = .StringLiteral;
},
'\'' => {
result.id = .{ .CharLiteral = .none };
state = .CharLiteralStart;
},
'u' => {
state = .u;
},
'U' => {
state = .U;
},
'L' => {
state = .L;
},
'a'...'t', 'v'...'z', 'A'...'K', 'M'...'T', 'V'...'Z', '_', '$' => {
state = .Identifier;
},
'=' => {
state = .Equal;
},
'!' => {
state = .Bang;
},
'|' => {
state = .Pipe;
},
'(' => {
result.id = .LParen;
self.index += 1;
break;
},
')' => {
result.id = .RParen;
self.index += 1;
break;
},
'[' => {
result.id = .LBracket;
self.index += 1;
break;
},
']' => {
result.id = .RBracket;
self.index += 1;
break;
},
';' => {
result.id = .Semicolon;
self.index += 1;
break;
},
',' => {
result.id = .Comma;
self.index += 1;
break;
},
'?' => {
result.id = .QuestionMark;
self.index += 1;
break;
},
':' => {
result.id = .Colon;
self.index += 1;
break;
},
'%' => {
state = .Percent;
},
'*' => {
state = .Asterisk;
},
'+' => {
state = .Plus;
},
'<' => {
if (self.prev_tok_id == .Keyword_include)
state = .MacroString
else
state = .AngleBracketLeft;
},
'>' => {
state = .AngleBracketRight;
},
'^' => {
state = .Caret;
},
'{' => {
result.id = .LBrace;
self.index += 1;
break;
},
'}' => {
result.id = .RBrace;
self.index += 1;
break;
},
'~' => {
result.id = .Tilde;
self.index += 1;
break;
},
'.' => {
state = .Period;
},
'-' => {
state = .Minus;
},
'/' => {
state = .Slash;
},
'&' => {
state = .Ampersand;
},
'#' => {
state = .Hash;
},
'0' => {
state = .Zero;
},
'1'...'9' => {
state = .IntegerLiteral;
},
'\\' => {
state = .BackSlash;
},
'\t', '\x0B', '\x0C', ' ' => {
result.start = self.index + 1;
},
else => {
// TODO handle invalid bytes better
result.id = .Invalid;
self.index += 1;
break;
},
},
.Cr => switch (c) {
'\n' => {
self.pp_directive = false;
result.id = .Nl;
self.index += 1;
break;
},
else => {
result.id = .Invalid;
break;
},
},
.BackSlash => switch (c) {
'\n' => {
result.start = self.index + 1;
state = .Start;
},
'\r' => {
state = .BackSlashCr;
},
'\t', '\x0B', '\x0C', ' ' => {
// TODO warn
},
else => {
result.id = .Invalid;
break;
},
},
.BackSlashCr => switch (c) {
'\n' => {
result.start = self.index + 1;
state = .Start;
},
else => {
result.id = .Invalid;
break;
},
},
.u => switch (c) {
'8' => {
state = .u8;
},
'\'' => {
result.id = .{ .CharLiteral = .utf_16 };
state = .CharLiteralStart;
},
'\"' => {
result.id = .{ .StringLiteral = .utf_16 };
state = .StringLiteral;
},
else => {
self.index -= 1;
state = .Identifier;
},
},
.u8 => switch (c) {
'\"' => {
result.id = .{ .StringLiteral = .utf_8 };
state = .StringLiteral;
},
else => {
self.index -= 1;
state = .Identifier;
},
},
.U => switch (c) {
'\'' => {
result.id = .{ .CharLiteral = .utf_32 };
state = .CharLiteralStart;
},
'\"' => {
result.id = .{ .StringLiteral = .utf_32 };
state = .StringLiteral;
},
else => {
self.index -= 1;
state = .Identifier;
},
},
.L => switch (c) {
'\'' => {
result.id = .{ .CharLiteral = .wide };
state = .CharLiteralStart;
},
'\"' => {
result.id = .{ .StringLiteral = .wide };
state = .StringLiteral;
},
else => {
self.index -= 1;
state = .Identifier;
},
},
.StringLiteral => switch (c) {
'\\' => {
string = true;
state = .EscapeSequence;
},
'"' => {
self.index += 1;
break;
},
'\n', '\r' => {
result.id = .Invalid;
break;
},
else => {},
},
.CharLiteralStart => switch (c) {
'\\' => {
string = false;
state = .EscapeSequence;
},
'\'', '\n' => {
result.id = .Invalid;
break;
},
else => {
state = .CharLiteral;
},
},
.CharLiteral => switch (c) {
'\\' => {
string = false;
state = .EscapeSequence;
},
'\'' => {
self.index += 1;
break;
},
'\n' => {
result.id = .Invalid;
break;
},
else => {},
},
.EscapeSequence => switch (c) {
'\'', '"', '?', '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v', '\n' => {
state = if (string) .StringLiteral else .CharLiteral;
},
'\r' => {
state = .CrEscape;
},
'0'...'7' => {
counter = 1;
state = .OctalEscape;
},
'x' => {
state = .HexEscape;
},
'u' => {
counter = 4;
state = .OctalEscape;
},
'U' => {
counter = 8;
state = .OctalEscape;
},
else => {
result.id = .Invalid;
break;
},
},
.CrEscape => switch (c) {
'\n' => {
state = if (string) .StringLiteral else .CharLiteral;
},
else => {
result.id = .Invalid;
break;
},
},
.OctalEscape => switch (c) {
'0'...'7' => {
counter += 1;
if (counter == 3) {
state = if (string) .StringLiteral else .CharLiteral;
}
},
else => {
self.index -= 1;
state = if (string) .StringLiteral else .CharLiteral;
},
},
.HexEscape => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => {
self.index -= 1;
state = if (string) .StringLiteral else .CharLiteral;
},
},
.UnicodeEscape => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {
counter -= 1;
if (counter == 0) {
state = if (string) .StringLiteral else .CharLiteral;
}
},
else => {
if (counter != 0) {
result.id = .Invalid;
break;
}
self.index -= 1;
state = if (string) .StringLiteral else .CharLiteral;
},
},
.Identifier => switch (c) {
'a'...'z', 'A'...'Z', '_', '0'...'9', '$' => {},
else => {
result.id = Token.getKeyword(self.buffer[result.start..self.index], self.prev_tok_id == .Hash and !self.pp_directive) orelse .Identifier;
if (self.prev_tok_id == .Hash)
self.pp_directive = true;
break;
},
},
.Equal => switch (c) {
'=' => {
result.id = .EqualEqual;
self.index += 1;
break;
},
else => {
result.id = .Equal;
break;
},
},
.Bang => switch (c) {
'=' => {
result.id = .BangEqual;
self.index += 1;
break;
},
else => {
result.id = .Bang;
break;
},
},
.Pipe => switch (c) {
'=' => {
result.id = .PipeEqual;
self.index += 1;
break;
},
'|' => {
result.id = .PipePipe;
self.index += 1;
break;
},
else => {
result.id = .Pipe;
break;
},
},
.Percent => switch (c) {
'=' => {
result.id = .PercentEqual;
self.index += 1;
break;
},
else => {
result.id = .Percent;
break;
},
},
.Asterisk => switch (c) {
'=' => {
result.id = .AsteriskEqual;
self.index += 1;
break;
},
else => {
result.id = .Asterisk;
break;
},
},
.Plus => switch (c) {
'=' => {
result.id = .PlusEqual;
self.index += 1;
break;
},
'+' => {
result.id = .PlusPlus;
self.index += 1;
break;
},
else => {
result.id = .Plus;
break;
},
},
.MacroString => switch (c) {
'>' => {
result.id = .MacroString;
self.index += 1;
break;
},
else => {},
},
.AngleBracketLeft => switch (c) {
'<' => {
state = .AngleBracketAngleBracketLeft;
},
'=' => {
result.id = .AngleBracketLeftEqual;
self.index += 1;
break;
},
else => {
result.id = .AngleBracketLeft;
break;
},
},
.AngleBracketAngleBracketLeft => switch (c) {
'=' => {
result.id = .AngleBracketAngleBracketLeftEqual;
self.index += 1;
break;
},
else => {
result.id = .AngleBracketAngleBracketLeft;
break;
},
},
.AngleBracketRight => switch (c) {
'>' => {
state = .AngleBracketAngleBracketRight;
},
'=' => {
result.id = .AngleBracketRightEqual;
self.index += 1;
break;
},
else => {
result.id = .AngleBracketRight;
break;
},
},
.AngleBracketAngleBracketRight => switch (c) {
'=' => {
result.id = .AngleBracketAngleBracketRightEqual;
self.index += 1;
break;
},
else => {
result.id = .AngleBracketAngleBracketRight;
break;
},
},
.Caret => switch (c) {
'=' => {
result.id = .CaretEqual;
self.index += 1;
break;
},
else => {
result.id = .Caret;
break;
},
},
.Period => switch (c) {
'.' => {
state = .Period2;
},
'0'...'9' => {
state = .FloatFraction;
},
else => {
result.id = .Period;
break;
},
},
.Period2 => switch (c) {
'.' => {
result.id = .Ellipsis;
self.index += 1;
break;
},
else => {
result.id = .Period;
self.index -= 1;
break;
},
},
.Minus => switch (c) {
'>' => {
result.id = .Arrow;
self.index += 1;
break;
},
'=' => {
result.id = .MinusEqual;
self.index += 1;
break;
},
'-' => {
result.id = .MinusMinus;
self.index += 1;
break;
},
else => {
result.id = .Minus;
break;
},
},
.Slash => switch (c) {
'/' => {
state = .LineComment;
},
'*' => {
state = .MultiLineComment;
},
'=' => {
result.id = .SlashEqual;
self.index += 1;
break;
},
else => {
result.id = .Slash;
break;
},
},
.Ampersand => switch (c) {
'&' => {
result.id = .AmpersandAmpersand;
self.index += 1;
break;
},
'=' => {
result.id = .AmpersandEqual;
self.index += 1;
break;
},
else => {
result.id = .Ampersand;
break;
},
},
.Hash => switch (c) {
'#' => {
result.id = .HashHash;
self.index += 1;
break;
},
else => {
result.id = .Hash;
break;
},
},
.LineComment => switch (c) {
'\n' => {
result.id = .LineComment;
break;
},
else => {},
},
.MultiLineComment => switch (c) {
'*' => {
state = .MultiLineCommentAsterisk;
},
else => {},
},
.MultiLineCommentAsterisk => switch (c) {
'/' => {
result.id = .MultiLineComment;
self.index += 1;
break;
},
else => {
state = .MultiLineComment;
},
},
.Zero => switch (c) {
'0'...'9' => {
state = .IntegerLiteralOct;
},
'b', 'B' => {
state = .IntegerLiteralBinaryFirst;
},
'x', 'X' => {
state = .IntegerLiteralHexFirst;
},
'.' => {
state = .FloatFraction;
},
else => {
state = .IntegerSuffix;
self.index -= 1;
},
},
.IntegerLiteralOct => switch (c) {
'0'...'7' => {},
else => {
state = .IntegerSuffix;
self.index -= 1;
},
},
.IntegerLiteralBinaryFirst => switch (c) {
'0'...'7' => state = .IntegerLiteralBinary,
else => {
result.id = .Invalid;
break;
},
},
.IntegerLiteralBinary => switch (c) {
'0', '1' => {},
else => {
state = .IntegerSuffix;
self.index -= 1;
},
},
.IntegerLiteralHexFirst => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => state = .IntegerLiteralHex,
'.' => {
state = .FloatFractionHex;
},
'p', 'P' => {
state = .FloatExponent;
},
else => {
result.id = .Invalid;
break;
},
},
.IntegerLiteralHex => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
'.' => {
state = .FloatFractionHex;
},
'p', 'P' => {
state = .FloatExponent;
},
else => {
state = .IntegerSuffix;
self.index -= 1;
},
},
.IntegerLiteral => switch (c) {
'0'...'9' => {},
'.' => {
state = .FloatFraction;
},
'e', 'E' => {
state = .FloatExponent;
},
else => {
state = .IntegerSuffix;
self.index -= 1;
},
},
.IntegerSuffix => switch (c) {
'u', 'U' => {
state = .IntegerSuffixU;
},
'l', 'L' => {
state = .IntegerSuffixL;
},
else => {
result.id = .{ .IntegerLiteral = .none };
break;
},
},
.IntegerSuffixU => switch (c) {
'l', 'L' => {
state = .IntegerSuffixUL;
},
else => {
result.id = .{ .IntegerLiteral = .u };
break;
},
},
.IntegerSuffixL => switch (c) {
'l', 'L' => {
state = .IntegerSuffixLL;
},
'u', 'U' => {
result.id = .{ .IntegerLiteral = .lu };
self.index += 1;
break;
},
else => {
result.id = .{ .IntegerLiteral = .l };
break;
},
},
.IntegerSuffixLL => switch (c) {
'u', 'U' => {
result.id = .{ .IntegerLiteral = .llu };
self.index += 1;
break;
},
else => {
result.id = .{ .IntegerLiteral = .ll };
break;
},
},
.IntegerSuffixUL => switch (c) {
'l', 'L' => {
result.id = .{ .IntegerLiteral = .llu };
self.index += 1;
break;
},
else => {
result.id = .{ .IntegerLiteral = .lu };
break;
},
},
.FloatFraction => switch (c) {
'0'...'9' => {},
'e', 'E' => {
state = .FloatExponent;
},
else => {
self.index -= 1;
state = .FloatSuffix;
},
},
.FloatFractionHex => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
'p', 'P' => {
state = .FloatExponent;
},
else => {
result.id = .Invalid;
break;
},
},
.FloatExponent => switch (c) {
'+', '-' => {
state = .FloatExponentDigits;
},
else => {
self.index -= 1;
state = .FloatExponentDigits;
},
},
.FloatExponentDigits => switch (c) {
'0'...'9' => {
counter += 1;
},
else => {
if (counter == 0) {
result.id = .Invalid;
break;
}
self.index -= 1;
state = .FloatSuffix;
},
},
.FloatSuffix => switch (c) {
'l', 'L' => {
result.id = .{ .FloatLiteral = .l };
self.index += 1;
break;
},
'f', 'F' => {
result.id = .{ .FloatLiteral = .f };
self.index += 1;
break;
},
else => {
result.id = .{ .FloatLiteral = .none };
break;
},
},
}
} else if (self.index == self.buffer.len) {
switch (state) {
.Start => {},
.u, .u8, .U, .L, .Identifier => {
result.id = Token.getKeyword(self.buffer[result.start..self.index], self.prev_tok_id == .Hash and !self.pp_directive) orelse .Identifier;
},
.Cr,
.BackSlash,
.BackSlashCr,
.Period2,
.StringLiteral,
.CharLiteralStart,
.CharLiteral,
.EscapeSequence,
.CrEscape,
.OctalEscape,
.HexEscape,
.UnicodeEscape,
.MultiLineComment,
.MultiLineCommentAsterisk,
.FloatExponent,
.MacroString,
.IntegerLiteralBinaryFirst,
.IntegerLiteralHexFirst,
=> result.id = .Invalid,
.FloatExponentDigits => result.id = if (counter == 0) .Invalid else .{ .FloatLiteral = .none },
.FloatFraction,
.FloatFractionHex,
=> result.id = .{ .FloatLiteral = .none },
.IntegerLiteralOct,
.IntegerLiteralBinary,
.IntegerLiteralHex,
.IntegerLiteral,
.IntegerSuffix,
.Zero,
=> result.id = .{ .IntegerLiteral = .none },
.IntegerSuffixU => result.id = .{ .IntegerLiteral = .u },
.IntegerSuffixL => result.id = .{ .IntegerLiteral = .l },
.IntegerSuffixLL => result.id = .{ .IntegerLiteral = .ll },
.IntegerSuffixUL => result.id = .{ .IntegerLiteral = .lu },
.FloatSuffix => result.id = .{ .FloatLiteral = .none },
.Equal => result.id = .Equal,
.Bang => result.id = .Bang,
.Minus => result.id = .Minus,
.Slash => result.id = .Slash,
.Ampersand => result.id = .Ampersand,
.Hash => result.id = .Hash,
.Period => result.id = .Period,
.Pipe => result.id = .Pipe,
.AngleBracketAngleBracketRight => result.id = .AngleBracketAngleBracketRight,
.AngleBracketRight => result.id = .AngleBracketRight,
.AngleBracketAngleBracketLeft => result.id = .AngleBracketAngleBracketLeft,
.AngleBracketLeft => result.id = .AngleBracketLeft,
.Plus => result.id = .Plus,
.Percent => result.id = .Percent,
.Caret => result.id = .Caret,
.Asterisk => result.id = .Asterisk,
.LineComment => result.id = .LineComment,
}
}
self.prev_tok_id = result.id;
result.end = self.index;
return result;
}
};
test "operators" {
try expectTokens(
\\ ! != | || |= = ==
\\ ( ) { } [ ] . .. ...
\\ ^ ^= + ++ += - -- -=
\\ * *= % %= -> : ; / /=
\\ , & && &= ? < <= <<
\\ <<= > >= >> >>= ~ # ##
\\
, &[_]Token.Id{
.Bang,
.BangEqual,
.Pipe,
.PipePipe,
.PipeEqual,
.Equal,
.EqualEqual,
.Nl,
.LParen,
.RParen,
.LBrace,
.RBrace,
.LBracket,
.RBracket,
.Period,
.Period,
.Period,
.Ellipsis,
.Nl,
.Caret,
.CaretEqual,
.Plus,
.PlusPlus,
.PlusEqual,
.Minus,
.MinusMinus,
.MinusEqual,
.Nl,
.Asterisk,
.AsteriskEqual,
.Percent,
.PercentEqual,
.Arrow,
.Colon,
.Semicolon,
.Slash,
.SlashEqual,
.Nl,
.Comma,
.Ampersand,
.AmpersandAmpersand,
.AmpersandEqual,
.QuestionMark,
.AngleBracketLeft,
.AngleBracketLeftEqual,
.AngleBracketAngleBracketLeft,
.Nl,
.AngleBracketAngleBracketLeftEqual,
.AngleBracketRight,
.AngleBracketRightEqual,
.AngleBracketAngleBracketRight,
.AngleBracketAngleBracketRightEqual,
.Tilde,
.Hash,
.HashHash,
.Nl,
});
}
test "keywords" {
try expectTokens(
\\auto break case char const continue default do
\\double else enum extern float for goto if int
\\long register return short signed sizeof static
\\struct switch typedef union unsigned void volatile
\\while _Bool _Complex _Imaginary inline restrict _Alignas
\\_Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local
\\
, &[_]Token.Id{
.Keyword_auto,
.Keyword_break,
.Keyword_case,
.Keyword_char,
.Keyword_const,
.Keyword_continue,
.Keyword_default,
.Keyword_do,
.Nl,
.Keyword_double,
.Keyword_else,
.Keyword_enum,
.Keyword_extern,
.Keyword_float,
.Keyword_for,
.Keyword_goto,
.Keyword_if,
.Keyword_int,
.Nl,
.Keyword_long,
.Keyword_register,
.Keyword_return,
.Keyword_short,
.Keyword_signed,
.Keyword_sizeof,
.Keyword_static,
.Nl,
.Keyword_struct,
.Keyword_switch,
.Keyword_typedef,
.Keyword_union,
.Keyword_unsigned,
.Keyword_void,
.Keyword_volatile,
.Nl,
.Keyword_while,
.Keyword_bool,
.Keyword_complex,
.Keyword_imaginary,
.Keyword_inline,
.Keyword_restrict,
.Keyword_alignas,
.Nl,
.Keyword_alignof,
.Keyword_atomic,
.Keyword_generic,
.Keyword_noreturn,
.Keyword_static_assert,
.Keyword_thread_local,
.Nl,
});
}
test "preprocessor keywords" {
try expectTokens(
\\#include <test>
\\#define #include <1
\\#ifdef
\\#ifndef
\\#error
\\#pragma
\\
, &[_]Token.Id{
.Hash,
.Keyword_include,
.MacroString,
.Nl,
.Hash,
.Keyword_define,
.Hash,
.Identifier,
.AngleBracketLeft,
.{ .IntegerLiteral = .none },
.Nl,
.Hash,
.Keyword_ifdef,
.Nl,
.Hash,
.Keyword_ifndef,
.Nl,
.Hash,
.Keyword_error,
.Nl,
.Hash,
.Keyword_pragma,
.Nl,
});
}
test "line continuation" {
try expectTokens(
\\#define foo \
\\ bar
\\"foo\
\\ bar"
\\#define "foo"
\\ "bar"
\\#define "foo" \
\\ "bar"
, &[_]Token.Id{
.Hash,
.Keyword_define,
.Identifier,
.Identifier,
.Nl,
.{ .StringLiteral = .none },
.Nl,
.Hash,
.Keyword_define,
.{ .StringLiteral = .none },
.Nl,
.{ .StringLiteral = .none },
.Nl,
.Hash,
.Keyword_define,
.{ .StringLiteral = .none },
.{ .StringLiteral = .none },
});
}
test "string prefix" {
try expectTokens(
\\"foo"
\\u"foo"
\\u8"foo"
\\U"foo"
\\L"foo"
\\'foo'
\\u'foo'
\\U'foo'
\\L'foo'
\\
, &[_]Token.Id{
.{ .StringLiteral = .none },
.Nl,
.{ .StringLiteral = .utf_16 },
.Nl,
.{ .StringLiteral = .utf_8 },
.Nl,
.{ .StringLiteral = .utf_32 },
.Nl,
.{ .StringLiteral = .wide },
.Nl,
.{ .CharLiteral = .none },
.Nl,
.{ .CharLiteral = .utf_16 },
.Nl,
.{ .CharLiteral = .utf_32 },
.Nl,
.{ .CharLiteral = .wide },
.Nl,
});
}
test "num suffixes" {
try expectTokens(
\\ 1.0f 1.0L 1.0 .0 1.
\\ 0l 0lu 0ll 0llu 0
\\ 1u 1ul 1ull 1
\\ 0x 0b
\\
, &[_]Token.Id{
.{ .FloatLiteral = .f },
.{ .FloatLiteral = .l },
.{ .FloatLiteral = .none },
.{ .FloatLiteral = .none },
.{ .FloatLiteral = .none },
.Nl,
.{ .IntegerLiteral = .l },
.{ .IntegerLiteral = .lu },
.{ .IntegerLiteral = .ll },
.{ .IntegerLiteral = .llu },
.{ .IntegerLiteral = .none },
.Nl,
.{ .IntegerLiteral = .u },
.{ .IntegerLiteral = .lu },
.{ .IntegerLiteral = .llu },
.{ .IntegerLiteral = .none },
.Nl,
.Invalid,
.Invalid,
.Nl,
});
}
fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) !void {
var tokenizer = Tokenizer{
.buffer = source,
};
for (expected_tokens) |expected_token_id| {
const token = tokenizer.next();
if (!std.meta.eql(token.id, expected_token_id)) {
std.debug.panic("expected {s}, found {s}\n", .{ @tagName(expected_token_id), @tagName(token.id) });
}
}
const last_token = tokenizer.next();
try std.testing.expect(last_token.id == .Eof);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/solaris.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
const timezone = std.c.timezone;
extern "c" fn ___errno() *c_int;
pub const _errno = ___errno;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub extern "c" fn sysconf(sc: c_int) i64;
pub extern "c" fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) c_int;
pub extern "c" fn madvise(address: [*]u8, len: usize, advise: u32) c_int;
pub const pthread_mutex_t = extern struct {
flag1: u16 = 0,
flag2: u8 = 0,
ceiling: u8 = 0,
type: u16 = 0,
magic: u16 = 0x4d58,
lock: u64 = 0,
data: u64 = 0,
};
pub const pthread_cond_t = extern struct {
flag: [4]u8 = [_]u8{0} ** 4,
type: u16 = 0,
magic: u16 = 0x4356,
data: u64 = 0,
};
pub const pthread_rwlock_t = extern struct {
readers: i32 = 0,
type: u16 = 0,
magic: u16 = 0x5257,
mutex: pthread_mutex_t = .{},
readercv: pthread_cond_t = .{},
writercv: pthread_cond_t = .{},
};
pub const pthread_attr_t = extern struct {
mutexattr: ?*anyopaque = null,
};
pub const pthread_key_t = c_int;
pub const sem_t = extern struct {
count: u32 = 0,
type: u16 = 0,
magic: u16 = 0x534d,
__pad1: [3]u64 = [_]u64{0} ** 3,
__pad2: [2]u64 = [_]u64{0} ** 2,
};
pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*anyopaque) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub const blkcnt_t = i64;
pub const blksize_t = i32;
pub const clock_t = i64;
pub const dev_t = i32;
pub const fd_t = c_int;
pub const gid_t = u32;
pub const ino_t = u64;
pub const mode_t = u32;
pub const nlink_t = u32;
pub const off_t = i64;
pub const pid_t = i32;
pub const socklen_t = u32;
pub const time_t = i64;
pub const suseconds_t = i64;
pub const uid_t = u32;
pub const major_t = u32;
pub const minor_t = u32;
pub const port_t = c_int;
pub const nfds_t = usize;
pub const id_t = i32;
pub const taskid_t = id_t;
pub const projid_t = id_t;
pub const poolid_t = id_t;
pub const zoneid_t = id_t;
pub const ctid_t = id_t;
pub const dl_phdr_info = extern struct {
dlpi_addr: std.elf.Addr,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: std.elf.Half,
/// Incremented when a new object is mapped into the process.
dlpi_adds: u64,
/// Incremented when an object is unmapped from the process.
dlpi_subs: u64,
};
pub const RTLD = struct {
pub const LAZY = 0x00001;
pub const NOW = 0x00002;
pub const NOLOAD = 0x00004;
pub const GLOBAL = 0x00100;
pub const LOCAL = 0x00000;
pub const PARENT = 0x00200;
pub const GROUP = 0x00400;
pub const WORLD = 0x00800;
pub const NODELETE = 0x01000;
pub const FIRST = 0x02000;
pub const CONFGEN = 0x10000;
pub const NEXT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -1)))));
pub const DEFAULT = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -2)))));
pub const SELF = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -3)))));
pub const PROBE = @as(*anyopaque, @ptrFromInt(@as(usize, @bitCast(@as(isize, -4)))));
};
pub const Flock = extern struct {
l_type: c_short,
l_whence: c_short,
l_start: off_t,
// len == 0 means until end of file.
l_len: off_t,
l_sysid: c_int,
l_pid: pid_t,
__pad: [4]c_long,
};
pub const utsname = extern struct {
sysname: [256:0]u8,
nodename: [256:0]u8,
release: [256:0]u8,
version: [256:0]u8,
machine: [256:0]u8,
domainname: [256:0]u8,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// argument buffer overflow
OVERFLOW = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
_,
};
pub const EAI_MAX = 14;
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*anyopaque,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const cmsghdr = extern struct {
cmsg_len: socklen_t,
cmsg_level: i32,
cmsg_type: i32,
};
/// The stat structure used by libc.
pub const Stat = extern struct {
dev: dev_t,
ino: ino_t,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
size: off_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
blksize: blksize_t,
blocks: blkcnt_t,
fstype: [16]u8,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: i64,
tv_nsec: isize,
};
pub const timeval = extern struct {
/// seconds
tv_sec: time_t,
/// microseconds
tv_usec: suseconds_t,
};
pub const MAXNAMLEN = 511;
pub const dirent = extern struct {
/// Inode number of entry.
d_ino: ino_t,
/// Offset of this entry on disk.
d_off: off_t,
/// Length of this record.
d_reclen: u16,
/// File name.
d_name: [MAXNAMLEN:0]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const SOCK = struct {
/// Datagram.
pub const DGRAM = 1;
/// STREAM.
pub const STREAM = 2;
/// Raw-protocol interface.
pub const RAW = 4;
/// Reliably-delivered message.
pub const RDM = 5;
/// Sequenced packed stream.
pub const SEQPACKET = 6;
pub const NONBLOCK = 0x100000;
pub const NDELAY = 0x200000;
pub const CLOEXEC = 0x080000;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const DGRAM_ERRIND = 0x0200;
pub const RECVUCRED = 0x0400;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const PROTOTYPE = 0x1009;
pub const ANON_MLP = 0x100a;
pub const MAC_EXEMPT = 0x100b;
pub const DOMAIN = 0x100c;
pub const RCVPSH = 0x100d;
pub const SECATTR = 0x1011;
pub const TIMESTAMP = 0x1013;
pub const ALLZONES = 0x1014;
pub const EXCLBIND = 0x1015;
pub const MAC_IMPLICIT = 0x1016;
pub const VRRP = 0x1017;
};
pub const SOMAXCONN = 128;
pub const SCM = struct {
pub const UCRED = 0x1012;
pub const RIGHTS = 0x1010;
pub const TIMESTAMP = SO.TIMESTAMP;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const UNIX = 1;
pub const LOCAL = UNIX;
pub const FILE = UNIX;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NS = 6;
pub const NBS = 7;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const NIT = 17;
pub const @"802" = 18;
pub const OSI = 19;
pub const X25 = 20;
pub const OSINET = 21;
pub const GOSIP = 22;
pub const IPX = 23;
pub const ROUTE = 24;
pub const LINK = 25;
pub const INET6 = 26;
pub const KEY = 27;
pub const NCA = 28;
pub const POLICY = 29;
pub const INET_OFFLOAD = 30;
pub const TRILL = 31;
pub const PACKET = 32;
pub const LX_NETLINK = 33;
pub const MAX = 33;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
pub const ROUTE = 0xfffe;
pub const PACKET = 0xfffd;
pub const FILTER = 0xfffc;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const UNIX = AF.UNIX;
pub const LOCAL = UNIX;
pub const FILE = UNIX;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NS = AF.NS;
pub const NBS = AF.NBS;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const SNA = AF.SNA;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const NIT = AF.NIT;
pub const @"802" = AF.@"802";
pub const OSI = AF.OSI;
pub const X25 = AF.X25;
pub const OSINET = AF.OSINET;
pub const GOSIP = AF.GOSIP;
pub const IPX = AF.IPX;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const INET6 = AF.INET6;
pub const KEY = AF.KEY;
pub const NCA = AF.NCA;
pub const POLICY = AF.POLICY;
pub const TRILL = AF.TRILL;
pub const PACKET = AF.PACKET;
pub const LX_NETLINK = AF.LX_NETLINK;
pub const MAX = AF.MAX;
};
pub const in_port_t = u16;
pub const sa_family_t = u16;
pub const sockaddr = extern struct {
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 256;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
__src_id: u32 = 0,
};
/// Definitions for UNIX IPC domain.
pub const un = extern struct {
family: sa_family_t = AF.UNIX,
path: [108]u8,
};
};
pub const AI = struct {
/// IPv4-mapped IPv6 address
pub const V4MAPPED = 0x0001;
pub const ALL = 0x0002;
/// only if any address is assigned
pub const ADDRCONFIG = 0x0004;
/// get address to use bind()
pub const PASSIVE = 0x0008;
/// fill ai_canonname
pub const CANONNAME = 0x0010;
/// prevent host name resolution
pub const NUMERICHOST = 0x0020;
/// prevent service name resolution
pub const NUMERICSERV = 0x0040;
};
pub const NI = struct {
pub const NOFQDN = 0x0001;
pub const NUMERICHOST = 0x0002;
pub const NAMEREQD = 0x0004;
pub const NUMERICSERV = 0x0008;
pub const DGRAM = 0x0010;
pub const WITHSCOPEID = 0x0020;
pub const NUMERICSCOPE = 0x0040;
pub const MAXHOST = 1025;
pub const MAXSERV = 32;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const VIRTUAL = 1;
pub const THREAD_CPUTIME_ID = 2;
pub const REALTIME = 3;
pub const MONOTONIC = 4;
pub const PROCESS_CPUTIME_ID = 5;
pub const HIGHRES = MONOTONIC;
pub const PROF = THREAD_CPUTIME_ID;
};
pub const MAP = struct {
pub const FAILED = @as(*anyopaque, @ptrFromInt(maxInt(usize)));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const TYPE = 0x000f;
pub const FILE = 0x0000;
pub const FIXED = 0x0010;
// Unimplemented
pub const RENAME = 0x0020;
pub const NORESERVE = 0x0040;
/// Force mapping in lower 4G address space
pub const @"32BIT" = 0x0080;
pub const ANON = 0x0100;
pub const ANONYMOUS = ANON;
pub const ALIGN = 0x0200;
pub const TEXT = 0x0400;
pub const INITDATA = 0x0800;
};
pub const MADV = struct {
/// no further special treatment
pub const NORMAL = 0;
/// expect random page references
pub const RANDOM = 1;
/// expect sequential page references
pub const SEQUENTIAL = 2;
/// will need these pages
pub const WILLNEED = 3;
/// don't need these pages
pub const DONTNEED = 4;
/// contents can be freed
pub const FREE = 5;
/// default access
pub const ACCESS_DEFAULT = 6;
/// next LWP to access heavily
pub const ACCESS_LWP = 7;
/// many processes to access heavily
pub const ACCESS_MANY = 8;
/// contents will be purged
pub const PURGE = 9;
};
pub const W = struct {
pub const EXITED = 0o001;
pub const TRAPPED = 0o002;
pub const UNTRACED = 0o004;
pub const STOPPED = UNTRACED;
pub const CONTINUED = 0o010;
pub const NOHANG = 0o100;
pub const NOWAIT = 0o200;
pub fn EXITSTATUS(s: u32) u8 {
return @as(u8, @intCast((s >> 8) & 0xff));
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFCONTINUED(s: u32) bool {
return ((s & 0o177777) == 0o177777);
}
pub fn IFSTOPPED(s: u32) bool {
return (s & 0x00ff != 0o177) and !(s & 0xff00 != 0);
}
pub fn IFSIGNALED(s: u32) bool {
return s & 0x00ff > 0 and s & 0xff00 == 0;
}
};
pub const SA = struct {
pub const ONSTACK = 0x00000001;
pub const RESETHAND = 0x00000002;
pub const RESTART = 0x00000004;
pub const SIGINFO = 0x00000008;
pub const NODEFER = 0x00000010;
pub const NOCLDWAIT = 0x00010000;
};
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const F = struct {
/// Unlock a previously locked region
pub const ULOCK = 0;
/// Lock a region for exclusive use
pub const LOCK = 1;
/// Test and lock a region for exclusive use
pub const TLOCK = 2;
/// Test a region for other processes locks
pub const TEST = 3;
/// Duplicate fildes
pub const DUPFD = 0;
/// Get fildes flags
pub const GETFD = 1;
/// Set fildes flags
pub const SETFD = 2;
/// Get file flags
pub const GETFL = 3;
/// Get file flags including open-only flags
pub const GETXFL = 45;
/// Set file flags
pub const SETFL = 4;
/// Unused
pub const CHKFL = 8;
/// Duplicate fildes at third arg
pub const DUP2FD = 9;
/// Like DUP2FD with O_CLOEXEC set EINVAL is fildes matches arg1
pub const DUP2FD_CLOEXEC = 36;
/// Like DUPFD with O_CLOEXEC set
pub const DUPFD_CLOEXEC = 37;
/// Is the file desc. a stream ?
pub const ISSTREAM = 13;
/// Turn on private access to file
pub const PRIV = 15;
/// Turn off private access to file
pub const NPRIV = 16;
/// UFS quota call
pub const QUOTACTL = 17;
/// Get number of BLKSIZE blocks allocated
pub const BLOCKS = 18;
/// Get optimal I/O block size
pub const BLKSIZE = 19;
/// Get owner (socket emulation)
pub const GETOWN = 23;
/// Set owner (socket emulation)
pub const SETOWN = 24;
/// Object reuse revoke access to file desc.
pub const REVOKE = 25;
/// Does vp have NFS locks private to lock manager
pub const HASREMOTELOCKS = 26;
/// Set file lock
pub const SETLK = 6;
/// Set file lock and wait
pub const SETLKW = 7;
/// Allocate file space
pub const ALLOCSP = 10;
/// Free file space
pub const FREESP = 11;
/// Get file lock
pub const GETLK = 14;
/// Get file lock owned by file
pub const OFD_GETLK = 47;
/// Set file lock owned by file
pub const OFD_SETLK = 48;
/// Set file lock owned by file and wait
pub const OFD_SETLKW = 49;
/// Set a file share reservation
pub const SHARE = 40;
/// Remove a file share reservation
pub const UNSHARE = 41;
/// Create Poison FD
pub const BADFD = 46;
/// Read lock
pub const RDLCK = 1;
/// Write lock
pub const WRLCK = 2;
/// Remove lock(s)
pub const UNLCK = 3;
/// remove remote locks for a given system
pub const UNLKSYS = 4;
// f_access values
/// Read-only share access
pub const RDACC = 0x1;
/// Write-only share access
pub const WRACC = 0x2;
/// Read-Write share access
pub const RWACC = 0x3;
// f_deny values
/// Don't deny others access
pub const NODNY = 0x0;
/// Deny others read share access
pub const RDDNY = 0x1;
/// Deny others write share access
pub const WRDNY = 0x2;
/// Deny others read or write share access
pub const RWDNY = 0x3;
/// private flag: Deny delete share access
pub const RMDNY = 0x4;
};
pub const O = struct {
pub const RDONLY = 0;
pub const WRONLY = 1;
pub const RDWR = 2;
pub const SEARCH = 0x200000;
pub const EXEC = 0x400000;
pub const NDELAY = 0x04;
pub const APPEND = 0x08;
pub const SYNC = 0x10;
pub const DSYNC = 0x40;
pub const RSYNC = 0x8000;
pub const NONBLOCK = 0x80;
pub const LARGEFILE = 0x2000;
pub const CREAT = 0x100;
pub const TRUNC = 0x200;
pub const EXCL = 0x400;
pub const NOCTTY = 0x800;
pub const XATTR = 0x4000;
pub const NOFOLLOW = 0x20000;
pub const NOLINKS = 0x40000;
pub const CLOEXEC = 0x800000;
pub const DIRECTORY = 0x1000000;
pub const DIRECT = 0x2000000;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const NB = 4;
pub const UN = 8;
};
pub const FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
pub const DATA = 3;
pub const HOLE = 4;
};
pub const tcflag_t = c_uint;
pub const cc_t = u8;
pub const speed_t = c_uint;
pub const NCCS = 19;
pub const termios = extern struct {
c_iflag: tcflag_t,
c_oflag: tcflag_t,
c_cflag: tcflag_t,
c_lflag: tcflag_t,
c_cc: [NCCS]cc_t,
};
fn tioc(t: u16, num: u8) u16 {
return (t << 8) | num;
}
pub const T = struct {
pub const CGETA = tioc('T', 1);
pub const CSETA = tioc('T', 2);
pub const CSETAW = tioc('T', 3);
pub const CSETAF = tioc('T', 4);
pub const CSBRK = tioc('T', 5);
pub const CXONC = tioc('T', 6);
pub const CFLSH = tioc('T', 7);
pub const IOCGWINSZ = tioc('T', 104);
pub const IOCSWINSZ = tioc('T', 103);
// Softcarrier ioctls
pub const IOCGSOFTCAR = tioc('T', 105);
pub const IOCSSOFTCAR = tioc('T', 106);
// termios ioctls
pub const CGETS = tioc('T', 13);
pub const CSETS = tioc('T', 14);
pub const CSANOW = tioc('T', 14);
pub const CSETSW = tioc('T', 15);
pub const CSADRAIN = tioc('T', 15);
pub const CSETSF = tioc('T', 16);
pub const IOCSETLD = tioc('T', 123);
pub const IOCGETLD = tioc('T', 124);
// NTP PPS ioctls
pub const IOCGPPS = tioc('T', 125);
pub const IOCSPPS = tioc('T', 126);
pub const IOCGPPSEV = tioc('T', 127);
pub const IOCGETD = tioc('t', 0);
pub const IOCSETD = tioc('t', 1);
pub const IOCHPCL = tioc('t', 2);
pub const IOCGETP = tioc('t', 8);
pub const IOCSETP = tioc('t', 9);
pub const IOCSETN = tioc('t', 10);
pub const IOCEXCL = tioc('t', 13);
pub const IOCNXCL = tioc('t', 14);
pub const IOCFLUSH = tioc('t', 16);
pub const IOCSETC = tioc('t', 17);
pub const IOCGETC = tioc('t', 18);
/// bis local mode bits
pub const IOCLBIS = tioc('t', 127);
/// bic local mode bits
pub const IOCLBIC = tioc('t', 126);
/// set entire local mode word
pub const IOCLSET = tioc('t', 125);
/// get local modes
pub const IOCLGET = tioc('t', 124);
/// set break bit
pub const IOCSBRK = tioc('t', 123);
/// clear break bit
pub const IOCCBRK = tioc('t', 122);
/// set data terminal ready
pub const IOCSDTR = tioc('t', 121);
/// clear data terminal ready
pub const IOCCDTR = tioc('t', 120);
/// set local special chars
pub const IOCSLTC = tioc('t', 117);
/// get local special chars
pub const IOCGLTC = tioc('t', 116);
/// driver output queue size
pub const IOCOUTQ = tioc('t', 115);
/// void tty association
pub const IOCNOTTY = tioc('t', 113);
/// get a ctty
pub const IOCSCTTY = tioc('t', 132);
/// stop output, like ^S
pub const IOCSTOP = tioc('t', 111);
/// start output, like ^Q
pub const IOCSTART = tioc('t', 110);
/// get pgrp of tty
pub const IOCGPGRP = tioc('t', 20);
/// set pgrp of tty
pub const IOCSPGRP = tioc('t', 21);
/// get session id on ctty
pub const IOCGSID = tioc('t', 22);
/// simulate terminal input
pub const IOCSTI = tioc('t', 23);
/// set all modem bits
pub const IOCMSET = tioc('t', 26);
/// bis modem bits
pub const IOCMBIS = tioc('t', 27);
/// bic modem bits
pub const IOCMBIC = tioc('t', 28);
/// get all modem bits
pub const IOCMGET = tioc('t', 29);
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
const NSIG = 75;
pub const SIG = struct {
pub const DFL = @as(?Sigaction.sigaction_fn, @ptrFromInt(0));
pub const ERR = @as(?Sigaction.sigaction_fn, @ptrFromInt(maxInt(usize)));
pub const IGN = @as(?Sigaction.sigaction_fn, @ptrFromInt(1));
pub const HOLD = @as(?Sigaction.sigaction_fn, @ptrFromInt(2));
pub const WORDS = 4;
pub const MAXSIG = 75;
pub const SIG_BLOCK = 1;
pub const SIG_UNBLOCK = 2;
pub const SIG_SETMASK = 3;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const IOT = 6;
pub const ABRT = 6;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const USR1 = 16;
pub const USR2 = 17;
pub const CLD = 18;
pub const CHLD = 18;
pub const PWR = 19;
pub const WINCH = 20;
pub const URG = 21;
pub const POLL = 22;
pub const IO = .POLL;
pub const STOP = 23;
pub const TSTP = 24;
pub const CONT = 25;
pub const TTIN = 26;
pub const TTOU = 27;
pub const VTALRM = 28;
pub const PROF = 29;
pub const XCPU = 30;
pub const XFSZ = 31;
pub const WAITING = 32;
pub const LWP = 33;
pub const FREEZE = 34;
pub const THAW = 35;
pub const CANCEL = 36;
pub const LOST = 37;
pub const XRES = 38;
pub const JVM1 = 39;
pub const JVM2 = 40;
pub const INFO = 41;
pub const RTMIN = 42;
pub const RTMAX = 74;
pub inline fn IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn WORD(sig: usize) usize {
return IDX(sig) >> 5;
}
pub inline fn BIT(sig: usize) usize {
return 1 << (IDX(sig) & 31);
}
pub inline fn VALID(sig: usize) usize {
return sig <= MAXSIG and sig > 0;
}
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal options
flags: c_uint,
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
/// signal mask to apply
mask: sigset_t,
};
pub const sigval_t = extern union {
int: c_int,
ptr: ?*anyopaque,
};
pub const siginfo_t = extern struct {
signo: c_int,
code: c_int,
errno: c_int,
// 64bit architectures insert 4bytes of padding here, this is done by
// correctly aligning the reason field
reason: extern union {
proc: extern struct {
pid: pid_t,
pdata: extern union {
kill: extern struct {
uid: uid_t,
value: sigval_t,
},
cld: extern struct {
utime: clock_t,
status: c_int,
stime: clock_t,
},
},
contract: ctid_t,
zone: zoneid_t,
},
fault: extern struct {
addr: ?*anyopaque,
trapno: c_int,
pc: ?*anyopaque,
},
file: extern struct {
// fd not currently available for SIGPOLL.
fd: c_int,
band: c_long,
},
prof: extern struct {
addr: ?*anyopaque,
timestamp: timespec,
syscall: c_short,
sysarg: u8,
fault: u8,
args: [8]c_long,
state: [10]c_int,
},
rctl: extern struct {
entity: i32,
},
__pad: [256 - 4 * @sizeOf(c_int)]u8,
} align(@sizeOf(usize)),
};
comptime {
std.debug.assert(@sizeOf(siginfo_t) == 256);
std.debug.assert(@alignOf(siginfo_t) == @sizeOf(usize));
}
pub const sigset_t = extern struct {
__bits: [SIG.WORDS]u32,
};
pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** SIG.WORDS };
pub const fpregset_t = extern union {
regs: [130]u32,
chip_state: extern struct {
cw: u16,
sw: u16,
fctw: u8,
__fx_rsvd: u8,
fop: u16,
rip: u64,
rdp: u64,
mxcsr: u32,
mxcsr_mask: u32,
st: [8]extern union {
fpr_16: [5]u16,
__fpr_pad: u128,
},
xmm: [16]u128,
__fx_ign2: [6]u128,
status: u32,
xstatus: u32,
},
};
pub const mcontext_t = extern struct {
gregs: [28]u64,
fpregs: fpregset_t,
};
pub const REG = struct {
pub const RBP = 10;
pub const RIP = 17;
pub const RSP = 20;
};
pub const ucontext_t = extern struct {
flags: u64,
link: ?*ucontext_t,
sigmask: sigset_t,
stack: stack_t,
mcontext: mcontext_t,
brand_data: [3]?*anyopaque,
filler: [2]i64,
};
pub const GETCONTEXT = 0;
pub const SETCONTEXT = 1;
pub const GETUSTACK = 2;
pub const SETUSTACK = 3;
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
/// Not super-user
PERM = 1,
/// No such file or directory
NOENT = 2,
/// No such process
SRCH = 3,
/// interrupted system call
INTR = 4,
/// I/O error
IO = 5,
/// No such device or address
NXIO = 6,
/// Arg list too long
@"2BIG" = 7,
/// Exec format error
NOEXEC = 8,
/// Bad file number
BADF = 9,
/// No children
CHILD = 10,
/// Resource temporarily unavailable.
/// also: WOULDBLOCK: Operation would block.
AGAIN = 11,
/// Not enough core
NOMEM = 12,
/// Permission denied
ACCES = 13,
/// Bad address
FAULT = 14,
/// Block device required
NOTBLK = 15,
/// Mount device busy
BUSY = 16,
/// File exists
EXIST = 17,
/// Cross-device link
XDEV = 18,
/// No such device
NODEV = 19,
/// Not a directory
NOTDIR = 20,
/// Is a directory
ISDIR = 21,
/// Invalid argument
INVAL = 22,
/// File table overflow
NFILE = 23,
/// Too many open files
MFILE = 24,
/// Inappropriate ioctl for device
NOTTY = 25,
/// Text file busy
TXTBSY = 26,
/// File too large
FBIG = 27,
/// No space left on device
NOSPC = 28,
/// Illegal seek
SPIPE = 29,
/// Read only file system
ROFS = 30,
/// Too many links
MLINK = 31,
/// Broken pipe
PIPE = 32,
/// Math arg out of domain of func
DOM = 33,
/// Math result not representable
RANGE = 34,
/// No message of desired type
NOMSG = 35,
/// Identifier removed
IDRM = 36,
/// Channel number out of range
CHRNG = 37,
/// Level 2 not synchronized
L2NSYNC = 38,
/// Level 3 halted
L3HLT = 39,
/// Level 3 reset
L3RST = 40,
/// Link number out of range
LNRNG = 41,
/// Protocol driver not attached
UNATCH = 42,
/// No CSI structure available
NOCSI = 43,
/// Level 2 halted
L2HLT = 44,
/// Deadlock condition.
DEADLK = 45,
/// No record locks available.
NOLCK = 46,
/// Operation canceled
CANCELED = 47,
/// Operation not supported
NOTSUP = 48,
// Filesystem Quotas
/// Disc quota exceeded
DQUOT = 49,
// Convergent Error Returns
/// invalid exchange
BADE = 50,
/// invalid request descriptor
BADR = 51,
/// exchange full
XFULL = 52,
/// no anode
NOANO = 53,
/// invalid request code
BADRQC = 54,
/// invalid slot
BADSLT = 55,
/// file locking deadlock error
DEADLOCK = 56,
/// bad font file fmt
BFONT = 57,
// Interprocess Robust Locks
/// process died with the lock
OWNERDEAD = 58,
/// lock is not recoverable
NOTRECOVERABLE = 59,
/// locked lock was unmapped
LOCKUNMAPPED = 72,
/// Facility is not active
NOTACTIVE = 73,
/// multihop attempted
MULTIHOP = 74,
/// trying to read unreadable message
BADMSG = 77,
/// path name is too long
NAMETOOLONG = 78,
/// value too large to be stored in data type
OVERFLOW = 79,
/// given log. name not unique
NOTUNIQ = 80,
/// f.d. invalid for this operation
BADFD = 81,
/// Remote address changed
REMCHG = 82,
// Stream Problems
/// Device not a stream
NOSTR = 60,
/// no data (for no delay io)
NODATA = 61,
/// timer expired
TIME = 62,
/// out of streams resources
NOSR = 63,
/// Machine is not on the network
NONET = 64,
/// Package not installed
NOPKG = 65,
/// The object is remote
REMOTE = 66,
/// the link has been severed
NOLINK = 67,
/// advertise error
ADV = 68,
/// srmount error
SRMNT = 69,
/// Communication error on send
COMM = 70,
/// Protocol error
PROTO = 71,
// Shared Library Problems
/// Can't access a needed shared lib.
LIBACC = 83,
/// Accessing a corrupted shared lib.
LIBBAD = 84,
/// .lib section in a.out corrupted.
LIBSCN = 85,
/// Attempting to link in too many libs.
LIBMAX = 86,
/// Attempting to exec a shared library.
LIBEXEC = 87,
/// Illegal byte sequence.
ILSEQ = 88,
/// Unsupported file system operation
NOSYS = 89,
/// Symbolic link loop
LOOP = 90,
/// Restartable system call
RESTART = 91,
/// if pipe/FIFO, don't sleep in stream head
STRPIPE = 92,
/// directory not empty
NOTEMPTY = 93,
/// Too many users (for UFS)
USERS = 94,
// BSD Networking Software
// Argument Errors
/// Socket operation on non-socket
NOTSOCK = 95,
/// Destination address required
DESTADDRREQ = 96,
/// Message too long
MSGSIZE = 97,
/// Protocol wrong type for socket
PROTOTYPE = 98,
/// Protocol not available
NOPROTOOPT = 99,
/// Protocol not supported
PROTONOSUPPORT = 120,
/// Socket type not supported
SOCKTNOSUPPORT = 121,
/// Operation not supported on socket
OPNOTSUPP = 122,
/// Protocol family not supported
PFNOSUPPORT = 123,
/// Address family not supported by
AFNOSUPPORT = 124,
/// Address already in use
ADDRINUSE = 125,
/// Can't assign requested address
ADDRNOTAVAIL = 126,
// Operational Errors
/// Network is down
NETDOWN = 127,
/// Network is unreachable
NETUNREACH = 128,
/// Network dropped connection because
NETRESET = 129,
/// Software caused connection abort
CONNABORTED = 130,
/// Connection reset by peer
CONNRESET = 131,
/// No buffer space available
NOBUFS = 132,
/// Socket is already connected
ISCONN = 133,
/// Socket is not connected
NOTCONN = 134,
/// Can't send after socket shutdown
SHUTDOWN = 143,
/// Too many references: can't splice
TOOMANYREFS = 144,
/// Connection timed out
TIMEDOUT = 145,
/// Connection refused
CONNREFUSED = 146,
/// Host is down
HOSTDOWN = 147,
/// No route to host
HOSTUNREACH = 148,
/// operation already in progress
ALREADY = 149,
/// operation now in progress
INPROGRESS = 150,
// SUN Network File System
/// Stale NFS file handle
STALE = 151,
_,
};
pub const MINSIGSTKSZ = 2048;
pub const SIGSTKSZ = 8192;
pub const SS_ONSTACK = 0x1;
pub const SS_DISABLE = 0x2;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
/// SunOS 2.6 Door
pub const IFDOOR = 0o150000;
/// Solaris 10 Event Port
pub const IFPORT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn ISDOOR(m: u32) bool {
return m & IFMT == IFDOOR;
}
pub fn ISPORT(m: u32) bool {
return m & IFMT == IFPORT;
}
};
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = @as(fd_t, @bitCast(@as(u32, 0xffd19553)));
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x1000;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x2000;
/// Remove directory instead of file
pub const REMOVEDIR = 0x1;
pub const TRIGGER = 0x2;
/// Check access using effective user and group ID
pub const EACCESS = 0x4;
};
pub const POSIX_FADV = struct {
pub const NORMAL = 0;
pub const RANDOM = 1;
pub const SEQUENTIAL = 2;
pub const WILLNEED = 3;
pub const DONTNEED = 4;
pub const NOREUSE = 5;
};
pub const HOST_NAME_MAX = 255;
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// Hop by hop header for IPv6
pub const HOPOPTS = 0;
/// control message protocol
pub const ICMP = 1;
/// group control protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IP in IP encapsulation
pub const ENCAP = 4;
/// tcp
pub const TCP = 6;
/// exterior gateway protocol
pub const EGP = 8;
/// pup
pub const PUP = 12;
/// user datagram protocol
pub const UDP = 17;
/// xns idp
pub const IDP = 22;
/// IPv6 encapsulated in IP
pub const IPV6 = 41;
/// Routing header for IPv6
pub const ROUTING = 43;
/// Fragment header for IPv6
pub const FRAGMENT = 44;
/// rsvp
pub const RSVP = 46;
/// IPsec Encap. Sec. Payload
pub const ESP = 50;
/// IPsec Authentication Hdr.
pub const AH = 51;
/// ICMP for IPv6
pub const ICMPV6 = 58;
/// No next header for IPv6
pub const NONE = 59;
/// Destination options
pub const DSTOPTS = 60;
/// "hello" routing protocol
pub const HELLO = 63;
/// UNOFFICIAL net disk proto
pub const ND = 77;
/// ISO clnp
pub const EON = 80;
/// OSPF
pub const OSPF = 89;
/// PIM routing protocol
pub const PIM = 103;
/// Stream Control
pub const SCTP = 132;
/// raw IP packet
pub const RAW = 255;
/// Sockets Direct Protocol
pub const PROTO_SDP = 257;
};
pub const priority = enum(c_int) {
PROCESS = 0,
PGRP = 1,
USER = 2,
GROUP = 3,
SESSION = 4,
LWP = 5,
TASK = 6,
PROJECT = 7,
ZONE = 8,
CONTRACT = 9,
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
NOFILE = 5,
VMEM = 6,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 3;
pub const SAVED_MAX: rlim_t = (1 << 63) - 2;
pub const SAVED_CUR: rlim_t = (1 << 63) - 1;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const RUSAGE_SELF = 0;
pub const RUSAGE_CHILDREN = -1;
pub const RUSAGE_THREAD = 1;
pub const rusage = extern struct {
utime: timeval,
stime: timeval,
maxrss: isize,
ixrss: isize,
idrss: isize,
isrss: isize,
minflt: isize,
majflt: isize,
nswap: isize,
inblock: isize,
oublock: isize,
msgsnd: isize,
msgrcv: isize,
nsignals: isize,
nvcsw: isize,
nivcsw: isize,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
/// Testable events (may be specified in ::pollfd::events).
pub const POLL = struct {
pub const IN = 0x0001;
pub const PRI = 0x0002;
pub const OUT = 0x0004;
pub const RDNORM = 0x0040;
pub const WRNORM = .OUT;
pub const RDBAND = 0x0080;
pub const WRBAND = 0x0100;
/// Read-side hangup.
pub const RDHUP = 0x4000;
/// Non-testable events (may not be specified in events).
pub const ERR = 0x0008;
pub const HUP = 0x0010;
pub const NVAL = 0x0020;
/// Events to control `/dev/poll` (not specified in revents)
pub const REMOVE = 0x0800;
pub const ONESHOT = 0x1000;
pub const ET = 0x2000;
};
/// Extensions to the ELF auxiliary vector.
pub const AT_SUN = struct {
/// effective user id
pub const UID = 2000;
/// real user id
pub const RUID = 2001;
/// effective group id
pub const GID = 2002;
/// real group id
pub const RGID = 2003;
/// dynamic linker's ELF header
pub const LDELF = 2004;
/// dynamic linker's section headers
pub const LDSHDR = 2005;
/// name of dynamic linker
pub const LDNAME = 2006;
/// large pagesize
pub const LPAGESZ = 2007;
/// platform name
pub const PLATFORM = 2008;
/// hints about hardware capabilities.
pub const HWCAP = 2009;
pub const HWCAP2 = 2023;
/// flush icache?
pub const IFLUSH = 2010;
/// cpu name
pub const CPU = 2011;
/// exec() path name in the auxv, null terminated.
pub const EXECNAME = 2014;
/// mmu module name
pub const MMU = 2015;
/// dynamic linkers data segment
pub const LDDATA = 2016;
/// AF_SUN_ flags passed from the kernel
pub const AUXFLAGS = 2017;
/// name of the emulation binary for the linker
pub const EMULATOR = 2018;
/// name of the brand library for the linker
pub const BRANDNAME = 2019;
/// vectors for brand modules.
pub const BRAND_AUX1 = 2020;
pub const BRAND_AUX2 = 2021;
pub const BRAND_AUX3 = 2022;
pub const BRAND_AUX4 = 2025;
pub const BRAND_NROOT = 2024;
/// vector for comm page.
pub const COMMPAGE = 2026;
/// information about the x86 FPU.
pub const FPTYPE = 2027;
pub const FPSIZE = 2028;
};
/// ELF auxiliary vector flags.
pub const AF_SUN = struct {
/// tell ld.so.1 to run "secure" and ignore the environment.
pub const SETUGID = 0x00000001;
/// hardware capabilities can be verified against AT_SUN_HWCAP
pub const HWCAPVERIFY = 0x00000002;
pub const NOPLM = 0x00000004;
};
// TODO: Add sysconf numbers when the other OSs do.
pub const _SC = struct {
pub const NPROCESSORS_ONLN = 15;
};
pub const procfs = struct {
pub const misc_header = extern struct {
size: u32,
type: enum(u32) {
Pathname,
Socketname,
Peersockname,
SockoptsBoolOpts,
SockoptLinger,
SockoptSndbuf,
SockoptRcvbuf,
SockoptIpNexthop,
SockoptIpv6Nexthop,
SockoptType,
SockoptTcpCongestion,
SockfiltersPriv = 14,
},
};
pub const fdinfo = extern struct {
fd: fd_t,
mode: mode_t,
ino: ino_t,
size: off_t,
offset: off_t,
uid: uid_t,
gid: gid_t,
dev_major: major_t,
dev_minor: minor_t,
special_major: major_t,
special_minor: minor_t,
fileflags: i32,
fdflags: i32,
locktype: i16,
lockpid: pid_t,
locksysid: i32,
peerpid: pid_t,
__filler: [25]c_int,
peername: [15:0]u8,
misc: [1]u8,
};
};
pub const SFD = struct {
pub const CLOEXEC = 0o2000000;
pub const NONBLOCK = 0o4000;
};
pub const signalfd_siginfo = extern struct {
signo: u32,
errno: i32,
code: i32,
pid: u32,
uid: uid_t,
fd: i32,
tid: u32, // unused
band: u32,
overrun: u32, // unused
trapno: u32,
status: i32,
int: i32, // unused
ptr: u64, // unused
utime: u64,
stime: u64,
addr: u64,
__pad: [48]u8,
};
pub const PORT_SOURCE = struct {
pub const AIO = 1;
pub const TIMER = 2;
pub const USER = 3;
pub const FD = 4;
pub const ALERT = 5;
pub const MQ = 6;
pub const FILE = 7;
};
pub const PORT_ALERT = struct {
pub const SET = 0x01;
pub const UPDATE = 0x02;
};
/// User watchable file events.
pub const FILE_EVENT = struct {
pub const ACCESS = 0x00000001;
pub const MODIFIED = 0x00000002;
pub const ATTRIB = 0x00000004;
pub const DELETE = 0x00000010;
pub const RENAME_TO = 0x00000020;
pub const RENAME_FROM = 0x00000040;
pub const TRUNC = 0x00100000;
pub const NOFOLLOW = 0x10000000;
/// The filesystem holding the watched file was unmounted.
pub const UNMOUNTED = 0x20000000;
/// Some other file/filesystem got mounted over the watched file/directory.
pub const MOUNTEDOVER = 0x40000000;
pub fn isException(event: u32) bool {
return event & (UNMOUNTED | DELETE | RENAME_TO | RENAME_FROM | MOUNTEDOVER) > 0;
}
};
pub const port_event = extern struct {
events: u32,
/// Event source.
source: u16,
__pad: u16,
/// Source-specific object.
object: ?*anyopaque,
/// User cookie.
cookie: ?*anyopaque,
};
pub const port_notify = extern struct {
/// Bind request(s) to port.
port: u32,
/// User defined variable.
user: ?*void,
};
pub const file_obj = extern struct {
/// Access time.
atim: timespec,
/// Modification time
mtim: timespec,
/// Change time
ctim: timespec,
__pad: [3]usize,
name: [*:0]u8,
};
// struct ifreq is marked obsolete, with struct lifreq prefered for interface requests.
// Here we alias lifreq to ifreq to avoid chainging existing code in os and x.os.IPv6.
pub const SIOCGLIFINDEX = IOWR('i', 133, lifreq);
pub const SIOCGIFINDEX = SIOCGLIFINDEX;
pub const MAX_HDW_LEN = 64;
pub const IFNAMESIZE = 32;
pub const lif_nd_req = extern struct {
addr: sockaddr.storage,
state_create: u8,
state_same_lla: u8,
state_diff_lla: u8,
hdw_len: i32,
flags: i32,
__pad: i32,
hdw_addr: [MAX_HDW_LEN]u8,
};
pub const lif_ifinfo_req = extern struct {
maxhops: u8,
reachtime: u32,
reachretrans: u32,
maxmtu: u32,
};
/// IP interface request. See if_tcp(7p) for more info.
pub const lifreq = extern struct {
// Not actually in a union, but the stdlib expects one for ifreq
ifrn: extern union {
/// Interface name, e.g. "lo0", "en0".
name: [IFNAMESIZE]u8,
},
ru1: extern union {
/// For subnet/token etc.
addrlen: i32,
/// Driver's PPA (physical point of attachment).
ppa: u32,
},
/// One of the IFT types, e.g. IFT_ETHER.
type: u32,
ifru: extern union {
/// Address.
addr: sockaddr.storage,
/// Other end of a peer-to-peer link.
dstaddr: sockaddr.storage,
/// Broadcast address.
broadaddr: sockaddr.storage,
/// Address token.
token: sockaddr.storage,
/// Subnet prefix.
subnet: sockaddr.storage,
/// Interface index.
ivalue: i32,
/// Flags for SIOC?LIFFLAGS.
flags: u64,
/// Hop count metric
metric: i32,
/// Maximum transmission unit
mtu: u32,
// Technically [2]i32
muxid: packed struct { ip: i32, arp: i32 },
/// Neighbor reachability determination entries
nd_req: lif_nd_req,
/// Link info
ifinfo_req: lif_ifinfo_req,
/// Name of the multipath interface group
groupname: [IFNAMESIZE]u8,
binding: [IFNAMESIZE]u8,
/// Zone id associated with this interface.
zoneid: zoneid_t,
/// Duplicate address detection state. Either in progress or completed.
dadstate: u32,
},
};
pub const ifreq = lifreq;
const IoCtlCommand = enum(u32) {
none = 0x20000000, // no parameters
write = 0x40000000, // copy out parameters
read = 0x80000000, // copy in parameters
read_write = 0xc0000000,
};
fn ioImpl(cmd: IoCtlCommand, io_type: u8, nr: u8, comptime IOT: type) i32 {
const size = @as(u32, @intCast(@as(u8, @truncate(@sizeOf(IOT))))) << 16;
const t = @as(u32, @intCast(io_type)) << 8;
return @as(i32, @bitCast(@intFromEnum(cmd) | size | t | nr));
}
pub fn IO(io_type: u8, nr: u8) i32 {
return ioImpl(.none, io_type, nr, void);
}
pub fn IOR(io_type: u8, nr: u8, comptime IOT: type) i32 {
return ioImpl(.write, io_type, nr, IOT);
}
pub fn IOW(io_type: u8, nr: u8, comptime IOT: type) i32 {
return ioImpl(.read, io_type, nr, IOT);
}
pub fn IOWR(io_type: u8, nr: u8, comptime IOT: type) i32 {
return ioImpl(.read_write, io_type, nr, IOT);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/windows.zig | //! The reference for these types and values is Microsoft Windows's ucrt (Universal C RunTime).
const std = @import("../std.zig");
const ws2_32 = std.os.windows.ws2_32;
const windows = std.os.windows;
pub extern "c" fn _errno() *c_int;
pub extern "c" fn _msize(memblock: ?*anyopaque) usize;
// TODO: copied the else case and removed the socket function (because its in ws2_32)
// need to verify which of these is actually supported on windows
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
pub extern "c" fn sigfillset(set: ?*sigset_t) void;
pub extern "c" fn alarm(seconds: c_uint) c_uint;
pub extern "c" fn sigwait(set: ?*sigset_t, sig: ?*c_int) c_int;
pub const fd_t = windows.HANDLE;
pub const ino_t = windows.LARGE_INTEGER;
pub const pid_t = windows.HANDLE;
pub const mode_t = u0;
pub const PATH_MAX = 260;
pub const time_t = c_longlong;
pub const timespec = extern struct {
tv_sec: time_t,
tv_nsec: c_long,
};
pub const timeval = extern struct {
tv_sec: c_long,
tv_usec: c_long,
};
pub const Stat = @compileError("TODO windows Stat definition");
pub const sig_atomic_t = c_int;
pub const sigset_t = @compileError("TODO windows sigset_t definition");
pub const Sigaction = @compileError("TODO windows Sigaction definition");
pub const timezone = @compileError("TODO windows timezone definition");
pub const rusage = @compileError("TODO windows rusage definition");
/// maximum signal number + 1
pub const NSIG = 23;
/// Signal types
pub const SIG = struct {
/// interrupt
pub const INT = 2;
/// illegal instruction - invalid function image
pub const ILL = 4;
/// floating point exception
pub const FPE = 8;
/// segment violation
pub const SEGV = 11;
/// Software termination signal from kill
pub const TERM = 15;
/// Ctrl-Break sequence
pub const BREAK = 21;
/// abnormal termination triggered by abort call
pub const ABRT = 22;
/// SIGABRT compatible with other platforms, same as SIGABRT
pub const ABRT_COMPAT = 6;
// Signal action codes
/// default signal action
pub const DFL = 0;
/// ignore signal
pub const IGN = 1;
/// return current value
pub const GET = 2;
/// signal gets error
pub const SGE = 3;
/// acknowledge
pub const ACK = 4;
/// Signal error value (returned by signal call on error)
pub const ERR = -1;
};
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1,
NOENT = 2,
SRCH = 3,
INTR = 4,
IO = 5,
NXIO = 6,
@"2BIG" = 7,
NOEXEC = 8,
BADF = 9,
CHILD = 10,
AGAIN = 11,
NOMEM = 12,
ACCES = 13,
FAULT = 14,
BUSY = 16,
EXIST = 17,
XDEV = 18,
NODEV = 19,
NOTDIR = 20,
ISDIR = 21,
NFILE = 23,
MFILE = 24,
NOTTY = 25,
FBIG = 27,
NOSPC = 28,
SPIPE = 29,
ROFS = 30,
MLINK = 31,
PIPE = 32,
DOM = 33,
/// Also means `DEADLOCK`.
DEADLK = 36,
NAMETOOLONG = 38,
NOLCK = 39,
NOSYS = 40,
NOTEMPTY = 41,
INVAL = 22,
RANGE = 34,
ILSEQ = 42,
// POSIX Supplement
ADDRINUSE = 100,
ADDRNOTAVAIL = 101,
AFNOSUPPORT = 102,
ALREADY = 103,
BADMSG = 104,
CANCELED = 105,
CONNABORTED = 106,
CONNREFUSED = 107,
CONNRESET = 108,
DESTADDRREQ = 109,
HOSTUNREACH = 110,
IDRM = 111,
INPROGRESS = 112,
ISCONN = 113,
LOOP = 114,
MSGSIZE = 115,
NETDOWN = 116,
NETRESET = 117,
NETUNREACH = 118,
NOBUFS = 119,
NODATA = 120,
NOLINK = 121,
NOMSG = 122,
NOPROTOOPT = 123,
NOSR = 124,
NOSTR = 125,
NOTCONN = 126,
NOTRECOVERABLE = 127,
NOTSOCK = 128,
NOTSUP = 129,
OPNOTSUPP = 130,
OTHER = 131,
OVERFLOW = 132,
OWNERDEAD = 133,
PROTO = 134,
PROTONOSUPPORT = 135,
PROTOTYPE = 136,
TIME = 137,
TIMEDOUT = 138,
TXTBSY = 139,
WOULDBLOCK = 140,
DQUOT = 10069,
_,
};
pub const STRUNCATE = 80;
pub const F_OK = 0;
/// Remove directory instead of unlinking file
pub const AT = struct {
pub const REMOVEDIR = 0x200;
};
pub const in_port_t = u16;
pub const sa_family_t = ws2_32.ADDRESS_FAMILY;
pub const socklen_t = ws2_32.socklen_t;
pub const sockaddr = ws2_32.sockaddr;
pub const in6_addr = [16]u8;
pub const in_addr = u32;
pub const addrinfo = ws2_32.addrinfo;
pub const AF = ws2_32.AF;
pub const MSG = ws2_32.MSG;
pub const SOCK = ws2_32.SOCK;
pub const TCP = ws2_32.TCP;
pub const IPPROTO = ws2_32.IPPROTO;
pub const BTHPROTO_RFCOMM = ws2_32.BTHPROTO_RFCOMM;
pub const nfds_t = c_ulong;
pub const pollfd = ws2_32.pollfd;
pub const POLL = ws2_32.POLL;
pub const SOL = ws2_32.SOL;
pub const SO = ws2_32.SO;
pub const PVD_CONFIG = ws2_32.PVD_CONFIG;
pub const O = struct {
pub const RDONLY = 0o0;
pub const WRONLY = 0o1;
pub const RDWR = 0o2;
pub const CREAT = 0o100;
pub const EXCL = 0o200;
pub const NOCTTY = 0o400;
pub const TRUNC = 0o1000;
pub const APPEND = 0o2000;
pub const NONBLOCK = 0o4000;
pub const DSYNC = 0o10000;
pub const SYNC = 0o4010000;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0o200000;
pub const NOFOLLOW = 0o400000;
pub const CLOEXEC = 0o2000000;
pub const ASYNC = 0o20000;
pub const DIRECT = 0o40000;
pub const LARGEFILE = 0;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
pub const NDELAY = NONBLOCK;
};
pub const IFNAMESIZE = 30;
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/c/fuchsia.zig | pub const pthread_mutex_t = extern struct {
size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
};
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
pub const pthread_rwlock_t = extern struct {
size: [56]u8 align(@alignOf(usize)) = [_]u8{0} ** 56,
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = 40;
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/json/write_stream.zig | const std = @import("../std.zig");
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
const State = enum {
Complete,
Value,
ArrayStart,
Array,
ObjectStart,
Object,
};
/// Writes JSON ([RFC8259](https://tools.ietf.org/html/rfc8259)) formatted data
/// to a stream. `max_depth` is a comptime-known upper bound on the nesting depth.
/// TODO A future iteration of this API will allow passing `null` for this value,
/// and disable safety checks in release builds.
pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
return struct {
const Self = @This();
pub const Stream = OutStream;
whitespace: std.json.StringifyOptions.Whitespace = std.json.StringifyOptions.Whitespace{
.indent_level = 0,
.indent = .{ .Space = 1 },
},
stream: OutStream,
state_index: usize,
state: [max_depth]State,
pub fn init(stream: OutStream) Self {
var self = Self{
.stream = stream,
.state_index = 1,
.state = undefined,
};
self.state[0] = .Complete;
self.state[1] = .Value;
return self;
}
pub fn beginArray(self: *Self) !void {
assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField
try self.stream.writeByte('[');
self.state[self.state_index] = State.ArrayStart;
self.whitespace.indent_level += 1;
}
pub fn beginObject(self: *Self) !void {
assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField
try self.stream.writeByte('{');
self.state[self.state_index] = State.ObjectStart;
self.whitespace.indent_level += 1;
}
pub fn arrayElem(self: *Self) !void {
const state = self.state[self.state_index];
switch (state) {
.Complete => unreachable,
.Value => unreachable,
.ObjectStart => unreachable,
.Object => unreachable,
.Array, .ArrayStart => {
if (state == .Array) {
try self.stream.writeByte(',');
}
self.state[self.state_index] = .Array;
self.pushState(.Value);
try self.indent();
},
}
}
pub fn objectField(self: *Self, name: []const u8) !void {
const state = self.state[self.state_index];
switch (state) {
.Complete => unreachable,
.Value => unreachable,
.ArrayStart => unreachable,
.Array => unreachable,
.Object, .ObjectStart => {
if (state == .Object) {
try self.stream.writeByte(',');
}
self.state[self.state_index] = .Object;
self.pushState(.Value);
try self.indent();
try self.writeEscapedString(name);
try self.stream.writeByte(':');
if (self.whitespace.separator) {
try self.stream.writeByte(' ');
}
},
}
}
pub fn endArray(self: *Self) !void {
switch (self.state[self.state_index]) {
.Complete => unreachable,
.Value => unreachable,
.ObjectStart => unreachable,
.Object => unreachable,
.ArrayStart => {
self.whitespace.indent_level -= 1;
try self.stream.writeByte(']');
self.popState();
},
.Array => {
self.whitespace.indent_level -= 1;
try self.indent();
self.popState();
try self.stream.writeByte(']');
},
}
}
pub fn endObject(self: *Self) !void {
switch (self.state[self.state_index]) {
.Complete => unreachable,
.Value => unreachable,
.ArrayStart => unreachable,
.Array => unreachable,
.ObjectStart => {
self.whitespace.indent_level -= 1;
try self.stream.writeByte('}');
self.popState();
},
.Object => {
self.whitespace.indent_level -= 1;
try self.indent();
self.popState();
try self.stream.writeByte('}');
},
}
}
pub fn emitNull(self: *Self) !void {
assert(self.state[self.state_index] == State.Value);
try self.stringify(null);
self.popState();
}
pub fn emitBool(self: *Self, value: bool) !void {
assert(self.state[self.state_index] == State.Value);
try self.stringify(value);
self.popState();
}
pub fn emitNumber(
self: *Self,
/// An integer, float, or `std.math.BigInt`. Emitted as a bare number if it fits losslessly
/// in a IEEE 754 double float, otherwise emitted as a string to the full precision.
value: anytype,
) !void {
assert(self.state[self.state_index] == State.Value);
switch (@typeInfo(@TypeOf(value))) {
.Int => |info| {
if (info.bits < 53) {
try self.stream.print("{}", .{value});
self.popState();
return;
}
if (value < 4503599627370496 and (info.signedness == .unsigned or value > -4503599627370496)) {
try self.stream.print("{}", .{value});
self.popState();
return;
}
},
.ComptimeInt => {
return self.emitNumber(@as(std.math.IntFittingRange(value, value), value));
},
.Float, .ComptimeFloat => if (@as(f64, @floatCast(value)) == value) {
try self.stream.print("{}", .{@as(f64, @floatCast(value))});
self.popState();
return;
},
else => {},
}
try self.stream.print("\"{}\"", .{value});
self.popState();
}
pub fn emitString(self: *Self, string: []const u8) !void {
assert(self.state[self.state_index] == State.Value);
try self.writeEscapedString(string);
self.popState();
}
fn writeEscapedString(self: *Self, string: []const u8) !void {
assert(std.unicode.utf8ValidateSlice(string));
try self.stringify(string);
}
/// Writes the complete json into the output stream
pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void {
assert(self.state[self.state_index] == State.Value);
try self.stringify(json);
self.popState();
}
fn indent(self: *Self) !void {
assert(self.state_index >= 1);
try self.stream.writeByte('\n');
try self.whitespace.outputIndent(self.stream);
}
fn pushState(self: *Self, state: State) void {
self.state_index += 1;
self.state[self.state_index] = state;
}
fn popState(self: *Self) void {
self.state_index -= 1;
}
fn stringify(self: *Self, value: anytype) !void {
try std.json.stringify(value, std.json.StringifyOptions{
.whitespace = self.whitespace,
}, self.stream);
}
};
}
pub fn writeStream(
out_stream: anytype,
comptime max_depth: usize,
) WriteStream(@TypeOf(out_stream), max_depth) {
return WriteStream(@TypeOf(out_stream), max_depth).init(out_stream);
}
test "json write stream" {
var out_buf: [1024]u8 = undefined;
var slice_stream = std.io.fixedBufferStream(&out_buf);
const out = slice_stream.writer();
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
var w = std.json.writeStream(out, 10);
try w.beginObject();
try w.objectField("object");
try w.emitJson(try getJsonObject(&arena_allocator.allocator));
try w.objectField("string");
try w.emitString("This is a string");
try w.objectField("array");
try w.beginArray();
try w.arrayElem();
try w.emitString("Another string");
try w.arrayElem();
try w.emitNumber(@as(i32, 1));
try w.arrayElem();
try w.emitNumber(@as(f32, 3.5));
try w.endArray();
try w.objectField("int");
try w.emitNumber(@as(i32, 10));
try w.objectField("float");
try w.emitNumber(@as(f32, 3.5));
try w.endObject();
const result = slice_stream.getWritten();
const expected =
\\{
\\ "object": {
\\ "one": 1,
\\ "two": 2.0e+00
\\ },
\\ "string": "This is a string",
\\ "array": [
\\ "Another string",
\\ 1,
\\ 3.5e+00
\\ ],
\\ "int": 10,
\\ "float": 3.5e+00
\\}
;
try std.testing.expect(std.mem.eql(u8, expected, result));
}
fn getJsonObject(allocator: *std.mem.Allocator) !std.json.Value {
var value = std.json.Value{ .Object = std.json.ObjectMap.init(allocator) };
try value.Object.put("one", std.json.Value{ .Integer = @as(i64, @intCast(1)) });
try value.Object.put("two", std.json.Value{ .Float = 2.0 });
return value;
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/json/test.zig | // RFC 8529 conformance tests.
//
// Tests are taken from https://github.com/nst/JSONTestSuite
// Read also http://seriot.ch/parsing_json.php for a good overview.
const std = @import("../std.zig");
const json = std.json;
const testing = std.testing;
fn testNonStreaming(s: []const u8) !void {
var p = json.Parser.init(testing.allocator, false);
defer p.deinit();
var tree = try p.parse(s);
defer tree.deinit();
}
fn ok(s: []const u8) !void {
try testing.expect(json.validate(s));
try testNonStreaming(s);
}
fn err(s: []const u8) !void {
try testing.expect(!json.validate(s));
try testing.expect(std.meta.isError(testNonStreaming(s)));
}
fn utf8Error(s: []const u8) !void {
try testing.expect(!json.validate(s));
try testing.expectError(error.InvalidUtf8Byte, testNonStreaming(s));
}
fn any(s: []const u8) !void {
_ = json.validate(s);
testNonStreaming(s) catch {};
}
fn anyStreamingErrNonStreaming(s: []const u8) !void {
_ = json.validate(s);
try testing.expect(std.meta.isError(testNonStreaming(s)));
}
fn roundTrip(s: []const u8) !void {
try testing.expect(json.validate(s));
var p = json.Parser.init(testing.allocator, false);
defer p.deinit();
var tree = try p.parse(s);
defer tree.deinit();
var buf: [256]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try tree.root.jsonStringify(.{}, fbs.writer());
try testing.expectEqualStrings(s, fbs.getWritten());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Additional tests not part of test JSONTestSuite.
test "y_trailing_comma_after_empty" {
try roundTrip(
\\{"1":[],"2":{},"3":"4"}
);
}
test "n_object_closed_missing_value" {
try err(
\\{"a":}
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "y_array_arraysWithSpaces" {
try ok(
\\[[] ]
);
}
test "y_array_empty" {
try roundTrip(
\\[]
);
}
test "y_array_empty-string" {
try roundTrip(
\\[""]
);
}
test "y_array_ending_with_newline" {
try roundTrip(
\\["a"]
);
}
test "y_array_false" {
try roundTrip(
\\[false]
);
}
test "y_array_heterogeneous" {
try ok(
\\[null, 1, "1", {}]
);
}
test "y_array_null" {
try roundTrip(
\\[null]
);
}
test "y_array_with_1_and_newline" {
try ok(
\\[1
\\]
);
}
test "y_array_with_leading_space" {
try ok(
\\ [1]
);
}
test "y_array_with_several_null" {
try roundTrip(
\\[1,null,null,null,2]
);
}
test "y_array_with_trailing_space" {
try ok("[2] ");
}
test "y_number_0e+1" {
try ok(
\\[0e+1]
);
}
test "y_number_0e1" {
try ok(
\\[0e1]
);
}
test "y_number_after_space" {
try ok(
\\[ 4]
);
}
test "y_number_double_close_to_zero" {
try ok(
\\[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]
);
}
test "y_number_int_with_exp" {
try ok(
\\[20e1]
);
}
test "y_number" {
try ok(
\\[123e65]
);
}
test "y_number_minus_zero" {
try ok(
\\[-0]
);
}
test "y_number_negative_int" {
try roundTrip(
\\[-123]
);
}
test "y_number_negative_one" {
try roundTrip(
\\[-1]
);
}
test "y_number_negative_zero" {
try ok(
\\[-0]
);
}
test "y_number_real_capital_e" {
try ok(
\\[1E22]
);
}
test "y_number_real_capital_e_neg_exp" {
try ok(
\\[1E-2]
);
}
test "y_number_real_capital_e_pos_exp" {
try ok(
\\[1E+2]
);
}
test "y_number_real_exponent" {
try ok(
\\[123e45]
);
}
test "y_number_real_fraction_exponent" {
try ok(
\\[123.456e78]
);
}
test "y_number_real_neg_exp" {
try ok(
\\[1e-2]
);
}
test "y_number_real_pos_exponent" {
try ok(
\\[1e+2]
);
}
test "y_number_simple_int" {
try roundTrip(
\\[123]
);
}
test "y_number_simple_real" {
try ok(
\\[123.456789]
);
}
test "y_object_basic" {
try roundTrip(
\\{"asd":"sdf"}
);
}
test "y_object_duplicated_key_and_value" {
try ok(
\\{"a":"b","a":"b"}
);
}
test "y_object_duplicated_key" {
try ok(
\\{"a":"b","a":"c"}
);
}
test "y_object_empty" {
try roundTrip(
\\{}
);
}
test "y_object_empty_key" {
try roundTrip(
\\{"":0}
);
}
test "y_object_escaped_null_in_key" {
try ok(
\\{"foo\u0000bar": 42}
);
}
test "y_object_extreme_numbers" {
try ok(
\\{ "min": -1.0e+28, "max": 1.0e+28 }
);
}
test "y_object" {
try ok(
\\{"asd":"sdf", "dfg":"fgh"}
);
}
test "y_object_long_strings" {
try ok(
\\{"x":[{"id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}], "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
);
}
test "y_object_simple" {
try roundTrip(
\\{"a":[]}
);
}
test "y_object_string_unicode" {
try ok(
\\{"title":"\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" }
);
}
test "y_object_with_newlines" {
try ok(
\\{
\\"a": "b"
\\}
);
}
test "y_string_1_2_3_bytes_UTF-8_sequences" {
try ok(
\\["\u0060\u012a\u12AB"]
);
}
test "y_string_accepted_surrogate_pair" {
try ok(
\\["\uD801\udc37"]
);
}
test "y_string_accepted_surrogate_pairs" {
try ok(
\\["\ud83d\ude39\ud83d\udc8d"]
);
}
test "y_string_allowed_escapes" {
try ok(
\\["\"\\\/\b\f\n\r\t"]
);
}
test "y_string_backslash_and_u_escaped_zero" {
try ok(
\\["\\u0000"]
);
}
test "y_string_backslash_doublequotes" {
try roundTrip(
\\["\""]
);
}
test "y_string_comments" {
try ok(
\\["a/*b*/c/*d//e"]
);
}
test "y_string_double_escape_a" {
try ok(
\\["\\a"]
);
}
test "y_string_double_escape_n" {
try roundTrip(
\\["\\n"]
);
}
test "y_string_escaped_control_character" {
try ok(
\\["\u0012"]
);
}
test "y_string_escaped_noncharacter" {
try ok(
\\["\uFFFF"]
);
}
test "y_string_in_array" {
try ok(
\\["asd"]
);
}
test "y_string_in_array_with_leading_space" {
try ok(
\\[ "asd"]
);
}
test "y_string_last_surrogates_1_and_2" {
try ok(
\\["\uDBFF\uDFFF"]
);
}
test "y_string_nbsp_uescaped" {
try ok(
\\["new\u00A0line"]
);
}
test "y_string_nonCharacterInUTF-8_U+10FFFF" {
try ok(
\\[""]
);
}
test "y_string_nonCharacterInUTF-8_U+FFFF" {
try ok(
\\[""]
);
}
test "y_string_null_escape" {
try ok(
\\["\u0000"]
);
}
test "y_string_one-byte-utf-8" {
try ok(
\\["\u002c"]
);
}
test "y_string_pi" {
try ok(
\\["π"]
);
}
test "y_string_reservedCharacterInUTF-8_U+1BFFF" {
try ok(
\\[""]
);
}
test "y_string_simple_ascii" {
try ok(
\\["asd "]
);
}
test "y_string_space" {
try roundTrip(
\\" "
);
}
test "y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF" {
try ok(
\\["\uD834\uDd1e"]
);
}
test "y_string_three-byte-utf-8" {
try ok(
\\["\u0821"]
);
}
test "y_string_two-byte-utf-8" {
try ok(
\\["\u0123"]
);
}
test "y_string_u+2028_line_sep" {
try ok("[\"\xe2\x80\xa8\"]");
}
test "y_string_u+2029_par_sep" {
try ok("[\"\xe2\x80\xa9\"]");
}
test "y_string_uescaped_newline" {
try ok(
\\["new\u000Aline"]
);
}
test "y_string_uEscape" {
try ok(
\\["\u0061\u30af\u30EA\u30b9"]
);
}
test "y_string_unescaped_char_delete" {
try ok("[\"\x7f\"]");
}
test "y_string_unicode_2" {
try ok(
\\["⍂㈴⍂"]
);
}
test "y_string_unicodeEscapedBackslash" {
try ok(
\\["\u005C"]
);
}
test "y_string_unicode_escaped_double_quote" {
try ok(
\\["\u0022"]
);
}
test "y_string_unicode" {
try ok(
\\["\uA66D"]
);
}
test "y_string_unicode_U+10FFFE_nonchar" {
try ok(
\\["\uDBFF\uDFFE"]
);
}
test "y_string_unicode_U+1FFFE_nonchar" {
try ok(
\\["\uD83F\uDFFE"]
);
}
test "y_string_unicode_U+200B_ZERO_WIDTH_SPACE" {
try ok(
\\["\u200B"]
);
}
test "y_string_unicode_U+2064_invisible_plus" {
try ok(
\\["\u2064"]
);
}
test "y_string_unicode_U+FDD0_nonchar" {
try ok(
\\["\uFDD0"]
);
}
test "y_string_unicode_U+FFFE_nonchar" {
try ok(
\\["\uFFFE"]
);
}
test "y_string_utf8" {
try ok(
\\["€𝄞"]
);
}
test "y_string_with_del_character" {
try ok("[\"a\x7fa\"]");
}
test "y_structure_lonely_false" {
try roundTrip(
\\false
);
}
test "y_structure_lonely_int" {
try roundTrip(
\\42
);
}
test "y_structure_lonely_negative_real" {
try ok(
\\-0.1
);
}
test "y_structure_lonely_null" {
try roundTrip(
\\null
);
}
test "y_structure_lonely_string" {
try roundTrip(
\\"asd"
);
}
test "y_structure_lonely_true" {
try roundTrip(
\\true
);
}
test "y_structure_string_empty" {
try roundTrip(
\\""
);
}
test "y_structure_trailing_newline" {
try roundTrip(
\\["a"]
);
}
test "y_structure_true_in_array" {
try roundTrip(
\\[true]
);
}
test "y_structure_whitespace_array" {
try ok(" [] ");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "n_array_1_true_without_comma" {
try err(
\\[1 true]
);
}
test "n_array_a_invalid_utf8" {
try err(
\\[aå]
);
}
test "n_array_colon_instead_of_comma" {
try err(
\\["": 1]
);
}
test "n_array_comma_after_close" {
try err(
\\[""],
);
}
test "n_array_comma_and_number" {
try err(
\\[,1]
);
}
test "n_array_double_comma" {
try err(
\\[1,,2]
);
}
test "n_array_double_extra_comma" {
try err(
\\["x",,]
);
}
test "n_array_extra_close" {
try err(
\\["x"]]
);
}
test "n_array_extra_comma" {
try err(
\\["",]
);
}
test "n_array_incomplete_invalid_value" {
try err(
\\[x
);
}
test "n_array_incomplete" {
try err(
\\["x"
);
}
test "n_array_inner_array_no_comma" {
try err(
\\[3[4]]
);
}
test "n_array_invalid_utf8" {
try err(
\\[ÿ]
);
}
test "n_array_items_separated_by_semicolon" {
try err(
\\[1:2]
);
}
test "n_array_just_comma" {
try err(
\\[,]
);
}
test "n_array_just_minus" {
try err(
\\[-]
);
}
test "n_array_missing_value" {
try err(
\\[ , ""]
);
}
test "n_array_newlines_unclosed" {
try err(
\\["a",
\\4
\\,1,
);
}
test "n_array_number_and_comma" {
try err(
\\[1,]
);
}
test "n_array_number_and_several_commas" {
try err(
\\[1,,]
);
}
test "n_array_spaces_vertical_tab_formfeed" {
try err("[\"\x0aa\"\\f]");
}
test "n_array_star_inside" {
try err(
\\[*]
);
}
test "n_array_unclosed" {
try err(
\\[""
);
}
test "n_array_unclosed_trailing_comma" {
try err(
\\[1,
);
}
test "n_array_unclosed_with_new_lines" {
try err(
\\[1,
\\1
\\,1
);
}
test "n_array_unclosed_with_object_inside" {
try err(
\\[{}
);
}
test "n_incomplete_false" {
try err(
\\[fals]
);
}
test "n_incomplete_null" {
try err(
\\[nul]
);
}
test "n_incomplete_true" {
try err(
\\[tru]
);
}
test "n_multidigit_number_then_00" {
try err("123\x00");
}
test "n_number_0.1.2" {
try err(
\\[0.1.2]
);
}
test "n_number_-01" {
try err(
\\[-01]
);
}
test "n_number_0.3e" {
try err(
\\[0.3e]
);
}
test "n_number_0.3e+" {
try err(
\\[0.3e+]
);
}
test "n_number_0_capital_E" {
try err(
\\[0E]
);
}
test "n_number_0_capital_E+" {
try err(
\\[0E+]
);
}
test "n_number_0.e1" {
try err(
\\[0.e1]
);
}
test "n_number_0e" {
try err(
\\[0e]
);
}
test "n_number_0e+" {
try err(
\\[0e+]
);
}
test "n_number_1_000" {
try err(
\\[1 000.0]
);
}
test "n_number_1.0e-" {
try err(
\\[1.0e-]
);
}
test "n_number_1.0e" {
try err(
\\[1.0e]
);
}
test "n_number_1.0e+" {
try err(
\\[1.0e+]
);
}
test "n_number_-1.0." {
try err(
\\[-1.0.]
);
}
test "n_number_1eE2" {
try err(
\\[1eE2]
);
}
test "n_number_.-1" {
try err(
\\[.-1]
);
}
test "n_number_+1" {
try err(
\\[+1]
);
}
test "n_number_.2e-3" {
try err(
\\[.2e-3]
);
}
test "n_number_2.e-3" {
try err(
\\[2.e-3]
);
}
test "n_number_2.e+3" {
try err(
\\[2.e+3]
);
}
test "n_number_2.e3" {
try err(
\\[2.e3]
);
}
test "n_number_-2." {
try err(
\\[-2.]
);
}
test "n_number_9.e+" {
try err(
\\[9.e+]
);
}
test "n_number_expression" {
try err(
\\[1+2]
);
}
test "n_number_hex_1_digit" {
try err(
\\[0x1]
);
}
test "n_number_hex_2_digits" {
try err(
\\[0x42]
);
}
test "n_number_infinity" {
try err(
\\[Infinity]
);
}
test "n_number_+Inf" {
try err(
\\[+Inf]
);
}
test "n_number_Inf" {
try err(
\\[Inf]
);
}
test "n_number_invalid+-" {
try err(
\\[0e+-1]
);
}
test "n_number_invalid-negative-real" {
try err(
\\[-123.123foo]
);
}
test "n_number_invalid-utf-8-in-bigger-int" {
try err(
\\[123å]
);
}
test "n_number_invalid-utf-8-in-exponent" {
try err(
\\[1e1å]
);
}
test "n_number_invalid-utf-8-in-int" {
try err(
\\[0å]
);
}
test "n_number_++" {
try err(
\\[++1234]
);
}
test "n_number_minus_infinity" {
try err(
\\[-Infinity]
);
}
test "n_number_minus_sign_with_trailing_garbage" {
try err(
\\[-foo]
);
}
test "n_number_minus_space_1" {
try err(
\\[- 1]
);
}
test "n_number_-NaN" {
try err(
\\[-NaN]
);
}
test "n_number_NaN" {
try err(
\\[NaN]
);
}
test "n_number_neg_int_starting_with_zero" {
try err(
\\[-012]
);
}
test "n_number_neg_real_without_int_part" {
try err(
\\[-.123]
);
}
test "n_number_neg_with_garbage_at_end" {
try err(
\\[-1x]
);
}
test "n_number_real_garbage_after_e" {
try err(
\\[1ea]
);
}
test "n_number_real_with_invalid_utf8_after_e" {
try err(
\\[1eå]
);
}
test "n_number_real_without_fractional_part" {
try err(
\\[1.]
);
}
test "n_number_starting_with_dot" {
try err(
\\[.123]
);
}
test "n_number_U+FF11_fullwidth_digit_one" {
try err(
\\[ï¼]
);
}
test "n_number_with_alpha_char" {
try err(
\\[1.8011670033376514H-308]
);
}
test "n_number_with_alpha" {
try err(
\\[1.2a-3]
);
}
test "n_number_with_leading_zero" {
try err(
\\[012]
);
}
test "n_object_bad_value" {
try err(
\\["x", truth]
);
}
test "n_object_bracket_key" {
try err(
\\{[: "x"}
);
}
test "n_object_comma_instead_of_colon" {
try err(
\\{"x", null}
);
}
test "n_object_double_colon" {
try err(
\\{"x"::"b"}
);
}
test "n_object_emoji" {
try err(
\\{ð¨ð}
);
}
test "n_object_garbage_at_end" {
try err(
\\{"a":"a" 123}
);
}
test "n_object_key_with_single_quotes" {
try err(
\\{key: 'value'}
);
}
test "n_object_lone_continuation_byte_in_key_and_trailing_comma" {
try err(
\\{"¹":"0",}
);
}
test "n_object_missing_colon" {
try err(
\\{"a" b}
);
}
test "n_object_missing_key" {
try err(
\\{:"b"}
);
}
test "n_object_missing_semicolon" {
try err(
\\{"a" "b"}
);
}
test "n_object_missing_value" {
try err(
\\{"a":
);
}
test "n_object_no-colon" {
try err(
\\{"a"
);
}
test "n_object_non_string_key_but_huge_number_instead" {
try err(
\\{9999E9999:1}
);
}
test "n_object_non_string_key" {
try err(
\\{1:1}
);
}
test "n_object_repeated_null_null" {
try err(
\\{null:null,null:null}
);
}
test "n_object_several_trailing_commas" {
try err(
\\{"id":0,,,,,}
);
}
test "n_object_single_quote" {
try err(
\\{'a':0}
);
}
test "n_object_trailing_comma" {
try err(
\\{"id":0,}
);
}
test "n_object_trailing_comment" {
try err(
\\{"a":"b"}/**/
);
}
test "n_object_trailing_comment_open" {
try err(
\\{"a":"b"}/**//
);
}
test "n_object_trailing_comment_slash_open_incomplete" {
try err(
\\{"a":"b"}/
);
}
test "n_object_trailing_comment_slash_open" {
try err(
\\{"a":"b"}//
);
}
test "n_object_two_commas_in_a_row" {
try err(
\\{"a":"b",,"c":"d"}
);
}
test "n_object_unquoted_key" {
try err(
\\{a: "b"}
);
}
test "n_object_unterminated-value" {
try err(
\\{"a":"a
);
}
test "n_object_with_single_string" {
try err(
\\{ "foo" : "bar", "a" }
);
}
test "n_object_with_trailing_garbage" {
try err(
\\{"a":"b"}#
);
}
test "n_single_space" {
try err(" ");
}
test "n_string_1_surrogate_then_escape" {
try err(
\\["\uD800\"]
);
}
test "n_string_1_surrogate_then_escape_u1" {
try err(
\\["\uD800\u1"]
);
}
test "n_string_1_surrogate_then_escape_u1x" {
try err(
\\["\uD800\u1x"]
);
}
test "n_string_1_surrogate_then_escape_u" {
try err(
\\["\uD800\u"]
);
}
test "n_string_accentuated_char_no_quotes" {
try err(
\\[é]
);
}
test "n_string_backslash_00" {
try err("[\"\x00\"]");
}
test "n_string_escaped_backslash_bad" {
try err(
\\["\\\"]
);
}
test "n_string_escaped_ctrl_char_tab" {
try err("\x5b\x22\x5c\x09\x22\x5d");
}
test "n_string_escaped_emoji" {
try err("[\"\x5c\xc3\xb0\xc2\x9f\xc2\x8c\xc2\x80\"]");
}
test "n_string_escape_x" {
try err(
\\["\x00"]
);
}
test "n_string_incomplete_escaped_character" {
try err(
\\["\u00A"]
);
}
test "n_string_incomplete_escape" {
try err(
\\["\"]
);
}
test "n_string_incomplete_surrogate_escape_invalid" {
try err(
\\["\uD800\uD800\x"]
);
}
test "n_string_incomplete_surrogate" {
try err(
\\["\uD834\uDd"]
);
}
test "n_string_invalid_backslash_esc" {
try err(
\\["\a"]
);
}
test "n_string_invalid_unicode_escape" {
try err(
\\["\uqqqq"]
);
}
test "n_string_invalid_utf8_after_escape" {
try err("[\"\\\x75\xc3\xa5\"]");
}
test "n_string_invalid-utf-8-in-escape" {
try err(
\\["\uå"]
);
}
test "n_string_leading_uescaped_thinspace" {
try err(
\\[\u0020"asd"]
);
}
test "n_string_no_quotes_with_bad_escape" {
try err(
\\[\n]
);
}
test "n_string_single_doublequote" {
try err(
\\"
);
}
test "n_string_single_quote" {
try err(
\\['single quote']
);
}
test "n_string_single_string_no_double_quotes" {
try err(
\\abc
);
}
test "n_string_start_escape_unclosed" {
try err(
\\["\
);
}
test "n_string_unescaped_crtl_char" {
try err("[\"a\x00a\"]");
}
test "n_string_unescaped_newline" {
try err(
\\["new
\\line"]
);
}
test "n_string_unescaped_tab" {
try err("[\"\t\"]");
}
test "n_string_unicode_CapitalU" {
try err(
\\"\UA66D"
);
}
test "n_string_with_trailing_garbage" {
try err(
\\""x
);
}
test "n_structure_100000_opening_arrays" {
try err("[" ** 100000);
}
test "n_structure_angle_bracket_." {
try err(
\\<.>
);
}
test "n_structure_angle_bracket_null" {
try err(
\\[<null>]
);
}
test "n_structure_array_trailing_garbage" {
try err(
\\[1]x
);
}
test "n_structure_array_with_extra_array_close" {
try err(
\\[1]]
);
}
test "n_structure_array_with_unclosed_string" {
try err(
\\["asd]
);
}
test "n_structure_ascii-unicode-identifier" {
try err(
\\aå
);
}
test "n_structure_capitalized_True" {
try err(
\\[True]
);
}
test "n_structure_close_unopened_array" {
try err(
\\1]
);
}
test "n_structure_comma_instead_of_closing_brace" {
try err(
\\{"x": true,
);
}
test "n_structure_double_array" {
try err(
\\[][]
);
}
test "n_structure_end_array" {
try err(
\\]
);
}
test "n_structure_incomplete_UTF8_BOM" {
try err(
\\ï»{}
);
}
test "n_structure_lone-invalid-utf-8" {
try err(
\\å
);
}
test "n_structure_lone-open-bracket" {
try err(
\\[
);
}
test "n_structure_no_data" {
try err(
\\
);
}
test "n_structure_null-byte-outside-string" {
try err("[\x00]");
}
test "n_structure_number_with_trailing_garbage" {
try err(
\\2@
);
}
test "n_structure_object_followed_by_closing_object" {
try err(
\\{}}
);
}
test "n_structure_object_unclosed_no_value" {
try err(
\\{"":
);
}
test "n_structure_object_with_comment" {
try err(
\\{"a":/*comment*/"b"}
);
}
test "n_structure_object_with_trailing_garbage" {
try err(
\\{"a": true} "x"
);
}
test "n_structure_open_array_apostrophe" {
try err(
\\['
);
}
test "n_structure_open_array_comma" {
try err(
\\[,
);
}
test "n_structure_open_array_object" {
try err("[{\"\":" ** 50000);
}
test "n_structure_open_array_open_object" {
try err(
\\[{
);
}
test "n_structure_open_array_open_string" {
try err(
\\["a
);
}
test "n_structure_open_array_string" {
try err(
\\["a"
);
}
test "n_structure_open_object_close_array" {
try err(
\\{]
);
}
test "n_structure_open_object_comma" {
try err(
\\{,
);
}
test "n_structure_open_object" {
try err(
\\{
);
}
test "n_structure_open_object_open_array" {
try err(
\\{[
);
}
test "n_structure_open_object_open_string" {
try err(
\\{"a
);
}
test "n_structure_open_object_string_with_apostrophes" {
try err(
\\{'a'
);
}
test "n_structure_open_open" {
try err(
\\["\{["\{["\{["\{
);
}
test "n_structure_single_eacute" {
try err(
\\é
);
}
test "n_structure_single_star" {
try err(
\\*
);
}
test "n_structure_trailing_#" {
try err(
\\{"a":"b"}#{}
);
}
test "n_structure_U+2060_word_joined" {
try err(
\\[â ]
);
}
test "n_structure_uescaped_LF_before_string" {
try err(
\\[\u000A""]
);
}
test "n_structure_unclosed_array" {
try err(
\\[1
);
}
test "n_structure_unclosed_array_partial_null" {
try err(
\\[ false, nul
);
}
test "n_structure_unclosed_array_unfinished_false" {
try err(
\\[ true, fals
);
}
test "n_structure_unclosed_array_unfinished_true" {
try err(
\\[ false, tru
);
}
test "n_structure_unclosed_object" {
try err(
\\{"asd":"asd"
);
}
test "n_structure_unicode-identifier" {
try err(
\\Ã¥
);
}
test "n_structure_UTF8_BOM_no_data" {
try err(
\\
);
}
test "n_structure_whitespace_formfeed" {
try err("[\x0c]");
}
test "n_structure_whitespace_U+2060_word_joiner" {
try err(
\\[â ]
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "i_number_double_huge_neg_exp" {
try any(
\\[123.456e-789]
);
}
test "i_number_huge_exp" {
try any(
\\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
);
}
test "i_number_neg_int_huge_exp" {
try any(
\\[-1e+9999]
);
}
test "i_number_pos_double_huge_exp" {
try any(
\\[1.5e+9999]
);
}
test "i_number_real_neg_overflow" {
try any(
\\[-123123e100000]
);
}
test "i_number_real_pos_overflow" {
try any(
\\[123123e100000]
);
}
test "i_number_real_underflow" {
try any(
\\[123e-10000000]
);
}
test "i_number_too_big_neg_int" {
try any(
\\[-123123123123123123123123123123]
);
}
test "i_number_too_big_pos_int" {
try any(
\\[100000000000000000000]
);
}
test "i_number_very_big_negative_int" {
try any(
\\[-237462374673276894279832749832423479823246327846]
);
}
test "i_object_key_lone_2nd_surrogate" {
try anyStreamingErrNonStreaming(
\\{"\uDFAA":0}
);
}
test "i_string_1st_surrogate_but_2nd_missing" {
try anyStreamingErrNonStreaming(
\\["\uDADA"]
);
}
test "i_string_1st_valid_surrogate_2nd_invalid" {
try anyStreamingErrNonStreaming(
\\["\uD888\u1234"]
);
}
test "i_string_incomplete_surrogate_and_escape_valid" {
try anyStreamingErrNonStreaming(
\\["\uD800\n"]
);
}
test "i_string_incomplete_surrogate_pair" {
try anyStreamingErrNonStreaming(
\\["\uDd1ea"]
);
}
test "i_string_incomplete_surrogates_escape_valid" {
try anyStreamingErrNonStreaming(
\\["\uD800\uD800\n"]
);
}
test "i_string_invalid_lonely_surrogate" {
try anyStreamingErrNonStreaming(
\\["\ud800"]
);
}
test "i_string_invalid_surrogate" {
try anyStreamingErrNonStreaming(
\\["\ud800abc"]
);
}
test "i_string_invalid_utf-8" {
try any(
\\["ÿ"]
);
}
test "i_string_inverted_surrogates_U+1D11E" {
try anyStreamingErrNonStreaming(
\\["\uDd1e\uD834"]
);
}
test "i_string_iso_latin_1" {
try any(
\\["é"]
);
}
test "i_string_lone_second_surrogate" {
try anyStreamingErrNonStreaming(
\\["\uDFAA"]
);
}
test "i_string_lone_utf8_continuation_byte" {
try any(
\\[""]
);
}
test "i_string_not_in_unicode_range" {
try any(
\\["ô¿¿¿"]
);
}
test "i_string_overlong_sequence_2_bytes" {
try any(
\\["À¯"]
);
}
test "i_string_overlong_sequence_6_bytes" {
try any(
\\["ü¿¿¿¿"]
);
}
test "i_string_overlong_sequence_6_bytes_null" {
try any(
\\["ü"]
);
}
test "i_string_truncated-utf-8" {
try any(
\\["àÿ"]
);
}
test "i_string_utf16BE_no_BOM" {
try any("\x00\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d");
}
test "i_string_utf16LE_no_BOM" {
try any("\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
}
test "i_string_UTF-16LE_with_BOM" {
try any("\xc3\xbf\xc3\xbe\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
}
test "i_string_UTF-8_invalid_sequence" {
try any(
\\["æ¥Ñú"]
);
}
test "i_string_UTF8_surrogate_U+D800" {
try any(
\\["í "]
);
}
test "i_structure_500_nested_arrays" {
try any(("[" ** 500) ++ ("]" ** 500));
}
test "i_structure_UTF-8_BOM_empty_object" {
try any(
\\{}
);
}
test "truncated UTF-8 sequence" {
try utf8Error("\"\xc2\"");
try utf8Error("\"\xdf\"");
try utf8Error("\"\xed\xa0\"");
try utf8Error("\"\xf0\x80\"");
try utf8Error("\"\xf0\x80\x80\"");
}
test "invalid continuation byte" {
try utf8Error("\"\xc2\x00\"");
try utf8Error("\"\xc2\x7f\"");
try utf8Error("\"\xc2\xc0\"");
try utf8Error("\"\xc3\xc1\"");
try utf8Error("\"\xc4\xf5\"");
try utf8Error("\"\xc5\xff\"");
try utf8Error("\"\xe4\x80\x00\"");
try utf8Error("\"\xe5\x80\x10\"");
try utf8Error("\"\xe6\x80\xc0\"");
try utf8Error("\"\xe7\x80\xf5\"");
try utf8Error("\"\xe8\x00\x80\"");
try utf8Error("\"\xf2\x00\x80\x80\"");
try utf8Error("\"\xf0\x80\x00\x80\"");
try utf8Error("\"\xf1\x80\xc0\x80\"");
try utf8Error("\"\xf2\x80\x80\x00\"");
try utf8Error("\"\xf3\x80\x80\xc0\"");
try utf8Error("\"\xf4\x80\x80\xf5\"");
}
test "disallowed overlong form" {
try utf8Error("\"\xc0\x80\"");
try utf8Error("\"\xc0\x90\"");
try utf8Error("\"\xc1\x80\"");
try utf8Error("\"\xc1\x90\"");
try utf8Error("\"\xe0\x80\x80\"");
try utf8Error("\"\xf0\x80\x80\x80\"");
}
test "out of UTF-16 range" {
try utf8Error("\"\xf4\x90\x80\x80\"");
try utf8Error("\"\xf5\x80\x80\x80\"");
try utf8Error("\"\xf6\x80\x80\x80\"");
try utf8Error("\"\xf7\x80\x80\x80\"");
try utf8Error("\"\xf8\x80\x80\x80\"");
try utf8Error("\"\xf9\x80\x80\x80\"");
try utf8Error("\"\xfa\x80\x80\x80\"");
try utf8Error("\"\xfb\x80\x80\x80\"");
try utf8Error("\"\xfc\x80\x80\x80\"");
try utf8Error("\"\xfd\x80\x80\x80\"");
try utf8Error("\"\xfe\x80\x80\x80\"");
try utf8Error("\"\xff\x80\x80\x80\"");
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/hkdf.zig | const std = @import("../std.zig");
const assert = std.debug.assert;
const hmac = std.crypto.auth.hmac;
const mem = std.mem;
/// HKDF-SHA256
pub const HkdfSha256 = Hkdf(hmac.sha2.HmacSha256);
/// HKDF-SHA512
pub const HkdfSha512 = Hkdf(hmac.sha2.HmacSha512);
/// The Hkdf construction takes some source of initial keying material and
/// derives one or more uniform keys from it.
pub fn Hkdf(comptime Hmac: type) type {
return struct {
/// Return a master key from a salt and initial keying material.
pub fn extract(salt: []const u8, ikm: []const u8) [Hmac.mac_length]u8 {
var prk: [Hmac.mac_length]u8 = undefined;
Hmac.create(&prk, ikm, salt);
return prk;
}
/// Derive a subkey from a master key `prk` and a subkey description `ctx`.
pub fn expand(out: []u8, ctx: []const u8, prk: [Hmac.mac_length]u8) void {
assert(out.len < Hmac.mac_length * 255); // output size is too large for the Hkdf construction
var i: usize = 0;
var counter = [1]u8{1};
while (i + Hmac.mac_length <= out.len) : (i += Hmac.mac_length) {
var st = Hmac.init(&prk);
if (i != 0) {
st.update(out[i - Hmac.mac_length ..][0..Hmac.mac_length]);
}
st.update(ctx);
st.update(&counter);
st.final(out[i..][0..Hmac.mac_length]);
counter[0] += 1;
}
const left = out.len % Hmac.mac_length;
if (left > 0) {
var st = Hmac.init(&prk);
if (i != 0) {
st.update(out[i - Hmac.mac_length ..][0..Hmac.mac_length]);
}
st.update(ctx);
st.update(&counter);
var tmp: [Hmac.mac_length]u8 = undefined;
st.final(tmp[0..Hmac.mac_length]);
mem.copy(u8, out[i..][0..left], tmp[0..left]);
}
}
};
}
const htest = @import("test.zig");
test "Hkdf" {
const ikm = [_]u8{0x0b} ** 22;
const salt = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c };
const context = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
const kdf = HkdfSha256;
const prk = kdf.extract(&salt, &ikm);
try htest.assertEqual("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", &prk);
var out: [42]u8 = undefined;
kdf.expand(&out, &context, prk);
try htest.assertEqual("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", &out);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes.zig | const std = @import("../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const has_aesni = std.Target.x86.featureSetHas(builtin.cpu.features, .aes);
const has_avx = std.Target.x86.featureSetHas(builtin.cpu.features, .avx);
const has_armaes = std.Target.aarch64.featureSetHas(builtin.cpu.features, .aes);
const impl = if (builtin.cpu.arch == .x86_64 and has_aesni and has_avx) impl: {
break :impl @import("aes/aesni.zig");
} else if (builtin.cpu.arch == .aarch64 and has_armaes)
impl: {
break :impl @import("aes/armcrypto.zig");
} else impl: {
break :impl @import("aes/soft.zig");
};
pub const Block = impl.Block;
pub const AesEncryptCtx = impl.AesEncryptCtx;
pub const AesDecryptCtx = impl.AesDecryptCtx;
pub const Aes128 = impl.Aes128;
pub const Aes256 = impl.Aes256;
test "ctr" {
// NIST SP 800-38A pp 55-58
const ctr = @import("modes.zig").ctr;
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const iv = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
const in = [_]u8{
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10,
};
const exp_out = [_]u8{
0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee,
};
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initEnc(key);
ctr(AesEncryptCtx(Aes128), ctx, out[0..], in[0..], iv, std.builtin.Endian.Big);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
test "encrypt" {
// Appendix B
{
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const in = [_]u8{ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 };
const exp_out = [_]u8{ 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 };
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initEnc(key);
ctx.encrypt(out[0..], in[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
{
const key = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
};
const in = [_]u8{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
const exp_out = [_]u8{ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 };
var out: [exp_out.len]u8 = undefined;
var ctx = Aes256.initEnc(key);
ctx.encrypt(out[0..], in[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
test "decrypt" {
// Appendix B
{
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const in = [_]u8{ 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 };
const exp_out = [_]u8{ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 };
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initDec(key);
ctx.decrypt(out[0..], in[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
{
const key = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
};
const in = [_]u8{ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 };
const exp_out = [_]u8{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
var out: [exp_out.len]u8 = undefined;
var ctx = Aes256.initDec(key);
ctx.decrypt(out[0..], in[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
test "expand 128-bit key" {
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const exp_enc = [_]*const [32:0]u8{
"2b7e151628aed2a6abf7158809cf4f3c", "a0fafe1788542cb123a339392a6c7605", "f2c295f27a96b9435935807a7359f67f", "3d80477d4716fe3e1e237e446d7a883b", "ef44a541a8525b7fb671253bdb0bad00", "d4d1c6f87c839d87caf2b8bc11f915bc", "6d88a37a110b3efddbf98641ca0093fd", "4e54f70e5f5fc9f384a64fb24ea6dc4f", "ead27321b58dbad2312bf5607f8d292f", "ac7766f319fadc2128d12941575c006e", "d014f9a8c9ee2589e13f0cc8b6630ca6",
};
const exp_dec = [_]*const [32:0]u8{
"d014f9a8c9ee2589e13f0cc8b6630ca6", "0c7b5a631319eafeb0398890664cfbb4", "df7d925a1f62b09da320626ed6757324", "12c07647c01f22c7bc42d2f37555114a", "6efcd876d2df54807c5df034c917c3b9", "6ea30afcbc238cf6ae82a4b4b54a338d", "90884413d280860a12a128421bc89739", "7c1f13f74208c219c021ae480969bf7b", "cc7505eb3e17d1ee82296c51c9481133", "2b3708a7f262d405bc3ebdbf4b617d62", "2b7e151628aed2a6abf7158809cf4f3c",
};
const enc = Aes128.initEnc(key);
const dec = Aes128.initDec(key);
var exp: [16]u8 = undefined;
for (enc.key_schedule.round_keys, 0..) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_enc[i]);
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
for (dec.key_schedule.round_keys, 0..) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_dec[i]);
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
}
test "expand 256-bit key" {
const key = [_]u8{ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
const exp_enc = [_]*const [32:0]u8{
"603deb1015ca71be2b73aef0857d7781", "1f352c073b6108d72d9810a30914dff4", "9ba354118e6925afa51a8b5f2067fcde", "a8b09c1a93d194cdbe49846eb75d5b9a", "d59aecb85bf3c917fee94248de8ebe96", "b5a9328a2678a647983122292f6c79b3", "812c81addadf48ba24360af2fab8b464", "98c5bfc9bebd198e268c3ba709e04214", "68007bacb2df331696e939e46c518d80", "c814e20476a9fb8a5025c02d59c58239", "de1369676ccc5a71fa2563959674ee15", "5886ca5d2e2f31d77e0af1fa27cf73c3", "749c47ab18501ddae2757e4f7401905a", "cafaaae3e4d59b349adf6acebd10190d", "fe4890d1e6188d0b046df344706c631e",
};
const exp_dec = [_]*const [32:0]u8{
"fe4890d1e6188d0b046df344706c631e", "ada23f4963e23b2455427c8a5c709104", "57c96cf6074f07c0706abb07137f9241", "b668b621ce40046d36a047ae0932ed8e", "34ad1e4450866b367725bcc763152946", "32526c367828b24cf8e043c33f92aa20", "c440b289642b757227a3d7f114309581", "d669a7334a7ade7a80c8f18fc772e9e3", "25ba3c22a06bc7fb4388a28333934270", "54fb808b9c137949cab22ff547ba186c", "6c3d632985d1fbd9e3e36578701be0f3", "4a7459f9c8e8f9c256a156bc8d083799", "42107758e9ec98f066329ea193f8858b", "8ec6bff6829ca03b9e49af7edba96125", "603deb1015ca71be2b73aef0857d7781",
};
const enc = Aes256.initEnc(key);
const dec = Aes256.initDec(key);
var exp: [16]u8 = undefined;
for (enc.key_schedule.round_keys, 0..) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_enc[i]);
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
for (dec.key_schedule.round_keys, 0..) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_dec[i]);
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/utils.zig | const std = @import("../std.zig");
const debug = std.debug;
const mem = std.mem;
const random = std.crypto.random;
const testing = std.testing;
const Endian = std.builtin.Endian;
const Order = std.math.Order;
/// Compares two arrays in constant time (for a given length) and returns whether they are equal.
/// This function was designed to compare short cryptographic secrets (MACs, signatures).
/// For all other applications, use mem.eql() instead.
pub fn timingSafeEql(comptime T: type, a: T, b: T) bool {
switch (@typeInfo(T)) {
.Array => |info| {
const C = info.child;
if (@typeInfo(C) != .Int) {
@compileError("Elements to be compared must be integers");
}
var acc = @as(C, 0);
for (a, 0..) |x, i| {
acc |= x ^ b[i];
}
const s = @typeInfo(C).Int.bits;
const Cu = std.meta.Int(.unsigned, s);
const Cext = std.meta.Int(.unsigned, s + 1);
return @as(bool, @bitCast(@as(u1, @truncate((@as(Cext, @as(Cu, @bitCast(acc))) -% 1) >> s))));
},
.Vector => |info| {
const C = info.child;
if (@typeInfo(C) != .Int) {
@compileError("Elements to be compared must be integers");
}
const acc = @reduce(.Or, a ^ b);
const s = @typeInfo(C).Int.bits;
const Cu = std.meta.Int(.unsigned, s);
const Cext = std.meta.Int(.unsigned, s + 1);
return @as(bool, @bitCast(@as(u1, @truncate((@as(Cext, @as(Cu, @bitCast(acc))) -% 1) >> s))));
},
else => {
@compileError("Only arrays and vectors can be compared");
},
}
}
/// Compare two integers serialized as arrays of the same size, in constant time.
/// Returns .lt if a<b, .gt if a>b and .eq if a=b
pub fn timingSafeCompare(comptime T: type, a: []const T, b: []const T, endian: Endian) Order {
debug.assert(a.len == b.len);
const bits = switch (@typeInfo(T)) {
.Int => |cinfo| if (cinfo.signedness != .unsigned) @compileError("Elements to be compared must be unsigned") else cinfo.bits,
else => @compileError("Elements to be compared must be integers"),
};
const Cext = std.meta.Int(.unsigned, bits + 1);
var gt: T = 0;
var eq: T = 1;
if (endian == .Little) {
var i = a.len;
while (i != 0) {
i -= 1;
const x1 = a[i];
const x2 = b[i];
gt |= @as(T, @truncate((@as(Cext, x2) -% @as(Cext, x1)) >> bits)) & eq;
eq &= @as(T, @truncate((@as(Cext, (x2 ^ x1)) -% 1) >> bits));
}
} else {
for (a, 0..) |x1, i| {
const x2 = b[i];
gt |= @as(T, @truncate((@as(Cext, x2) -% @as(Cext, x1)) >> bits)) & eq;
eq &= @as(T, @truncate((@as(Cext, (x2 ^ x1)) -% 1) >> bits));
}
}
if (gt != 0) {
return Order.gt;
} else if (eq != 0) {
return Order.eq;
}
return Order.lt;
}
/// Add two integers serialized as arrays of the same size, in constant time.
/// The result is stored into `result`, and `true` is returned if an overflow occurred.
pub fn timingSafeAdd(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool {
const len = a.len;
debug.assert(len == b.len and len == result.len);
var carry: u1 = 0;
if (endian == .Little) {
var i: usize = 0;
while (i < len) : (i += 1) {
const ov1 = @addWithOverflow(a[i], b[i]);
const ov2 = @addWithOverflow(ov1[0], carry);
result[i] = ov2[0];
carry = ov1[1] | ov2[1];
}
} else {
var i: usize = len;
while (i != 0) {
i -= 1;
const ov1 = @addWithOverflow(a[i], b[i]);
const ov2 = @addWithOverflow(ov1[0], carry);
result[i] = ov2[0];
carry = ov1[1] | ov2[1];
}
}
return @as(bool, @bitCast(carry));
}
/// Subtract two integers serialized as arrays of the same size, in constant time.
/// The result is stored into `result`, and `true` is returned if an underflow occurred.
pub fn timingSafeSub(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool {
const len = a.len;
debug.assert(len == b.len and len == result.len);
var borrow: u1 = 0;
if (endian == .Little) {
var i: usize = 0;
while (i < len) : (i += 1) {
const ov1 = @subWithOverflow(a[i], b[i]);
const ov2 = @subWithOverflow(ov1[0], borrow);
result[i] = ov2[0];
borrow = ov1[1] | ov2[1];
}
} else {
var i: usize = len;
while (i != 0) {
i -= 1;
const ov1 = @subWithOverflow(a[i], b[i]);
const ov2 = @subWithOverflow(ov1[0], borrow);
result[i] = ov2[0];
borrow = ov1[1] | ov2[1];
}
}
return @as(bool, @bitCast(borrow));
}
/// Sets a slice to zeroes.
/// Prevents the store from being optimized out.
pub fn secureZero(comptime T: type, s: []T) void {
// NOTE: We do not use a volatile slice cast here since LLVM cannot
// see that it can be replaced by a memset.
const ptr = @as([*]volatile u8, @ptrCast(s.ptr));
const length = s.len * @sizeOf(T);
@memset(ptr[0..length], 0);
}
test "crypto.utils.timingSafeEql" {
var a: [100]u8 = undefined;
var b: [100]u8 = undefined;
random.bytes(a[0..]);
random.bytes(b[0..]);
try testing.expect(!timingSafeEql([100]u8, a, b));
mem.copy(u8, a[0..], b[0..]);
try testing.expect(timingSafeEql([100]u8, a, b));
}
test "crypto.utils.timingSafeEql (vectors)" {
var a: [100]u8 = undefined;
var b: [100]u8 = undefined;
random.bytes(a[0..]);
random.bytes(b[0..]);
const v1: std.meta.Vector(100, u8) = a;
const v2: std.meta.Vector(100, u8) = b;
try testing.expect(!timingSafeEql(std.meta.Vector(100, u8), v1, v2));
const v3: std.meta.Vector(100, u8) = a;
try testing.expect(timingSafeEql(std.meta.Vector(100, u8), v1, v3));
}
test "crypto.utils.timingSafeCompare" {
var a = [_]u8{10} ** 32;
var b = [_]u8{10} ** 32;
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .eq);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .eq);
a[31] = 1;
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .lt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
a[0] = 20;
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .gt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
}
test "crypto.utils.timingSafe{Add,Sub}" {
const len = 32;
var a: [len]u8 = undefined;
var b: [len]u8 = undefined;
var c: [len]u8 = undefined;
const zero = [_]u8{0} ** len;
var iterations: usize = 100;
while (iterations != 0) : (iterations -= 1) {
random.bytes(&a);
random.bytes(&b);
const endian = if (iterations % 2 == 0) Endian.Big else Endian.Little;
_ = timingSafeSub(u8, &a, &b, &c, endian); // a-b
_ = timingSafeAdd(u8, &c, &b, &c, endian); // (a-b)+b
try testing.expectEqualSlices(u8, &c, &a);
const borrow = timingSafeSub(u8, &c, &a, &c, endian); // ((a-b)+b)-a
try testing.expectEqualSlices(u8, &c, &zero);
try testing.expectEqual(borrow, false);
}
}
test "crypto.utils.secureZero" {
var a = [_]u8{0xfe} ** 8;
var b = [_]u8{0xfe} ** 8;
mem.set(u8, a[0..], 0);
secureZero(u8, b[0..]);
try testing.expectEqualSlices(u8, a[0..], b[0..]);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/benchmark.zig | // zig run -O ReleaseFast --zig-lib-dir ../.. benchmark.zig
const std = @import("../std.zig");
const builtin = @import("builtin");
const mem = std.mem;
const time = std.time;
const Timer = time.Timer;
const crypto = std.crypto;
const KiB = 1024;
const MiB = 1024 * KiB;
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
const Crypto = struct {
ty: type,
name: []const u8,
};
const hashes = [_]Crypto{
Crypto{ .ty = crypto.hash.Md5, .name = "md5" },
Crypto{ .ty = crypto.hash.Sha1, .name = "sha1" },
Crypto{ .ty = crypto.hash.sha2.Sha256, .name = "sha256" },
Crypto{ .ty = crypto.hash.sha2.Sha512, .name = "sha512" },
Crypto{ .ty = crypto.hash.sha3.Sha3_256, .name = "sha3-256" },
Crypto{ .ty = crypto.hash.sha3.Sha3_512, .name = "sha3-512" },
Crypto{ .ty = crypto.hash.Gimli, .name = "gimli-hash" },
Crypto{ .ty = crypto.hash.blake2.Blake2s256, .name = "blake2s" },
Crypto{ .ty = crypto.hash.blake2.Blake2b512, .name = "blake2b" },
Crypto{ .ty = crypto.hash.Blake3, .name = "blake3" },
};
pub fn benchmarkHash(comptime Hash: anytype, comptime bytes: comptime_int) !u64 {
var h = Hash.init(.{});
var block: [Hash.digest_length]u8 = undefined;
random.bytes(block[0..]);
var offset: usize = 0;
var timer = try Timer.start();
const start = timer.lap();
while (offset < bytes) : (offset += block.len) {
h.update(block[0..]);
}
mem.doNotOptimizeAway(&h);
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(bytes / elapsed_s));
return throughput;
}
const macs = [_]Crypto{
Crypto{ .ty = crypto.onetimeauth.Ghash, .name = "ghash" },
Crypto{ .ty = crypto.onetimeauth.Poly1305, .name = "poly1305" },
Crypto{ .ty = crypto.auth.hmac.HmacMd5, .name = "hmac-md5" },
Crypto{ .ty = crypto.auth.hmac.HmacSha1, .name = "hmac-sha1" },
Crypto{ .ty = crypto.auth.hmac.sha2.HmacSha256, .name = "hmac-sha256" },
Crypto{ .ty = crypto.auth.hmac.sha2.HmacSha512, .name = "hmac-sha512" },
Crypto{ .ty = crypto.auth.siphash.SipHash64(2, 4), .name = "siphash-2-4" },
Crypto{ .ty = crypto.auth.siphash.SipHash64(1, 3), .name = "siphash-1-3" },
Crypto{ .ty = crypto.auth.siphash.SipHash128(2, 4), .name = "siphash128-2-4" },
Crypto{ .ty = crypto.auth.siphash.SipHash128(1, 3), .name = "siphash128-1-3" },
};
pub fn benchmarkMac(comptime Mac: anytype, comptime bytes: comptime_int) !u64 {
var in: [512 * KiB]u8 = undefined;
random.bytes(in[0..]);
const key_length = if (Mac.key_length == 0) 32 else Mac.key_length;
var key: [key_length]u8 = undefined;
random.bytes(key[0..]);
var mac: [Mac.mac_length]u8 = undefined;
var offset: usize = 0;
var timer = try Timer.start();
const start = timer.lap();
while (offset < bytes) : (offset += in.len) {
Mac.create(mac[0..], in[0..], key[0..]);
mem.doNotOptimizeAway(&mac);
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(bytes / elapsed_s));
return throughput;
}
const exchanges = [_]Crypto{Crypto{ .ty = crypto.dh.X25519, .name = "x25519" }};
pub fn benchmarkKeyExchange(comptime DhKeyExchange: anytype, comptime exchange_count: comptime_int) !u64 {
std.debug.assert(DhKeyExchange.shared_length >= DhKeyExchange.secret_length);
var secret: [DhKeyExchange.shared_length]u8 = undefined;
random.bytes(secret[0..]);
var public: [DhKeyExchange.shared_length]u8 = undefined;
random.bytes(public[0..]);
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < exchange_count) : (i += 1) {
const out = try DhKeyExchange.scalarmult(secret, public);
mem.copy(u8, secret[0..16], out[0..16]);
mem.copy(u8, public[0..16], out[16..32]);
mem.doNotOptimizeAway(&out);
}
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(exchange_count / elapsed_s));
return throughput;
}
const signatures = [_]Crypto{Crypto{ .ty = crypto.sign.Ed25519, .name = "ed25519" }};
pub fn benchmarkSignature(comptime Signature: anytype, comptime signatures_count: comptime_int) !u64 {
const msg = [_]u8{0} ** 64;
const key_pair = try Signature.KeyPair.create(null);
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < signatures_count) : (i += 1) {
const sig = try Signature.sign(&msg, key_pair, null);
mem.doNotOptimizeAway(&sig);
}
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(signatures_count / elapsed_s));
return throughput;
}
const signature_verifications = [_]Crypto{Crypto{ .ty = crypto.sign.Ed25519, .name = "ed25519" }};
pub fn benchmarkSignatureVerification(comptime Signature: anytype, comptime signatures_count: comptime_int) !u64 {
const msg = [_]u8{0} ** 64;
const key_pair = try Signature.KeyPair.create(null);
const sig = try Signature.sign(&msg, key_pair, null);
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < signatures_count) : (i += 1) {
try Signature.verify(sig, &msg, key_pair.public_key);
mem.doNotOptimizeAway(&sig);
}
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(signatures_count / elapsed_s));
return throughput;
}
const batch_signature_verifications = [_]Crypto{Crypto{ .ty = crypto.sign.Ed25519, .name = "ed25519" }};
pub fn benchmarkBatchSignatureVerification(comptime Signature: anytype, comptime signatures_count: comptime_int) !u64 {
const msg = [_]u8{0} ** 64;
const key_pair = try Signature.KeyPair.create(null);
const sig = try Signature.sign(&msg, key_pair, null);
var batch: [64]Signature.BatchElement = undefined;
for (batch) |*element| {
element.* = Signature.BatchElement{ .sig = sig, .msg = &msg, .public_key = key_pair.public_key };
}
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < signatures_count) : (i += 1) {
try Signature.verifyBatch(batch.len, batch);
mem.doNotOptimizeAway(&sig);
}
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = batch.len * @as(u64, @intFromFloat(signatures_count / elapsed_s));
return throughput;
}
const aeads = [_]Crypto{
Crypto{ .ty = crypto.aead.chacha_poly.ChaCha20Poly1305, .name = "chacha20Poly1305" },
Crypto{ .ty = crypto.aead.chacha_poly.XChaCha20Poly1305, .name = "xchacha20Poly1305" },
Crypto{ .ty = crypto.aead.chacha_poly.XChaCha8Poly1305, .name = "xchacha8Poly1305" },
Crypto{ .ty = crypto.aead.salsa_poly.XSalsa20Poly1305, .name = "xsalsa20Poly1305" },
Crypto{ .ty = crypto.aead.Gimli, .name = "gimli-aead" },
Crypto{ .ty = crypto.aead.aegis.Aegis128L, .name = "aegis-128l" },
Crypto{ .ty = crypto.aead.aegis.Aegis256, .name = "aegis-256" },
Crypto{ .ty = crypto.aead.aes_gcm.Aes128Gcm, .name = "aes128-gcm" },
Crypto{ .ty = crypto.aead.aes_gcm.Aes256Gcm, .name = "aes256-gcm" },
Crypto{ .ty = crypto.aead.aes_ocb.Aes128Ocb, .name = "aes128-ocb" },
Crypto{ .ty = crypto.aead.aes_ocb.Aes256Ocb, .name = "aes256-ocb" },
Crypto{ .ty = crypto.aead.isap.IsapA128A, .name = "isapa128a" },
};
pub fn benchmarkAead(comptime Aead: anytype, comptime bytes: comptime_int) !u64 {
var in: [512 * KiB]u8 = undefined;
random.bytes(in[0..]);
var tag: [Aead.tag_length]u8 = undefined;
var key: [Aead.key_length]u8 = undefined;
random.bytes(key[0..]);
var nonce: [Aead.nonce_length]u8 = undefined;
random.bytes(nonce[0..]);
var offset: usize = 0;
var timer = try Timer.start();
const start = timer.lap();
while (offset < bytes) : (offset += in.len) {
Aead.encrypt(in[0..], tag[0..], in[0..], &[_]u8{}, nonce, key);
try Aead.decrypt(in[0..], in[0..], tag, &[_]u8{}, nonce, key);
}
mem.doNotOptimizeAway(&in);
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(2 * bytes / elapsed_s));
return throughput;
}
const aes = [_]Crypto{
Crypto{ .ty = crypto.core.aes.Aes128, .name = "aes128-single" },
Crypto{ .ty = crypto.core.aes.Aes256, .name = "aes256-single" },
};
pub fn benchmarkAes(comptime Aes: anytype, comptime count: comptime_int) !u64 {
var key: [Aes.key_bits / 8]u8 = undefined;
random.bytes(key[0..]);
const ctx = Aes.initEnc(key);
var in = [_]u8{0} ** 16;
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < count) : (i += 1) {
ctx.encrypt(&in, &in);
}
}
mem.doNotOptimizeAway(&in);
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(count / elapsed_s));
return throughput;
}
const aes8 = [_]Crypto{
Crypto{ .ty = crypto.core.aes.Aes128, .name = "aes128-8" },
Crypto{ .ty = crypto.core.aes.Aes256, .name = "aes256-8" },
};
pub fn benchmarkAes8(comptime Aes: anytype, comptime count: comptime_int) !u64 {
var key: [Aes.key_bits / 8]u8 = undefined;
random.bytes(key[0..]);
const ctx = Aes.initEnc(key);
var in = [_]u8{0} ** (8 * 16);
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < count) : (i += 1) {
ctx.encryptWide(8, &in, &in);
}
}
mem.doNotOptimizeAway(&in);
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = @as(u64, @intFromFloat(8 * count / elapsed_s));
return throughput;
}
const CryptoPwhash = struct {
ty: type,
params: *const anyopaque,
name: []const u8,
};
const bcrypt_params = crypto.pwhash.bcrypt.Params{ .rounds_log = 12 };
const pwhashes = [_]CryptoPwhash{
.{ .ty = crypto.pwhash.bcrypt, .params = &bcrypt_params, .name = "bcrypt" },
.{
.ty = crypto.pwhash.scrypt,
.params = &crypto.pwhash.scrypt.Params.interactive,
.name = "scrypt",
},
.{
.ty = crypto.pwhash.argon2,
.params = &crypto.pwhash.argon2.Params.interactive_2id,
.name = "argon2",
},
};
fn benchmarkPwhash(
comptime ty: anytype,
comptime params: *const anyopaque,
comptime count: comptime_int,
) !f64 {
const password = "testpass" ** 2;
const opts = .{ .allocator = std.testing.allocator, .params = @as(*const ty.Params, @ptrCast(params)).*, .encoding = .phc };
var buf: [256]u8 = undefined;
var timer = try Timer.start();
const start = timer.lap();
{
var i: usize = 0;
while (i < count) : (i += 1) {
_ = try ty.strHash(password, opts, &buf);
mem.doNotOptimizeAway(&buf);
}
}
const end = timer.read();
const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
const throughput = elapsed_s / count;
return throughput;
}
fn usage() void {
std.debug.print(
\\throughput_test [options]
\\
\\Options:
\\ --filter [test-name]
\\ --seed [int]
\\ --help
\\
, .{});
}
fn mode(comptime x: comptime_int) comptime_int {
return if (builtin.mode == .Debug) x / 64 else x;
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
const args = try std.process.argsAlloc(fixed.allocator());
var filter: ?[]u8 = "";
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--mode")) {
try stdout.print("{}\n", .{builtin.mode});
return;
} else if (std.mem.eql(u8, args[i], "--seed")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
const seed = try std.fmt.parseUnsigned(u32, args[i], 10);
prng.seed(seed);
} else if (std.mem.eql(u8, args[i], "--filter")) {
i += 1;
if (i == args.len) {
usage();
std.os.exit(1);
}
filter = args[i];
} else if (std.mem.eql(u8, args[i], "--help")) {
usage();
return;
} else {
usage();
std.os.exit(1);
}
}
inline for (hashes) |H| {
if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) {
const throughput = try benchmarkHash(H.ty, mode(128 * MiB));
try stdout.print("{s:>17}: {:10} MiB/s\n", .{ H.name, throughput / (1 * MiB) });
}
}
inline for (macs) |M| {
if (filter == null or std.mem.indexOf(u8, M.name, filter.?) != null) {
const throughput = try benchmarkMac(M.ty, mode(128 * MiB));
try stdout.print("{s:>17}: {:10} MiB/s\n", .{ M.name, throughput / (1 * MiB) });
}
}
inline for (exchanges) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkKeyExchange(E.ty, mode(1000));
try stdout.print("{s:>17}: {:10} exchanges/s\n", .{ E.name, throughput });
}
}
inline for (signatures) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkSignature(E.ty, mode(1000));
try stdout.print("{s:>17}: {:10} signatures/s\n", .{ E.name, throughput });
}
}
inline for (signature_verifications) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkSignatureVerification(E.ty, mode(1000));
try stdout.print("{s:>17}: {:10} verifications/s\n", .{ E.name, throughput });
}
}
inline for (batch_signature_verifications) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkBatchSignatureVerification(E.ty, mode(1000));
try stdout.print("{s:>17}: {:10} verifications/s (batch)\n", .{ E.name, throughput });
}
}
inline for (aeads) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkAead(E.ty, mode(128 * MiB));
try stdout.print("{s:>17}: {:10} MiB/s\n", .{ E.name, throughput / (1 * MiB) });
}
}
inline for (aes) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkAes(E.ty, mode(100000000));
try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput });
}
}
inline for (aes8) |E| {
if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) {
const throughput = try benchmarkAes8(E.ty, mode(10000000));
try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput });
}
}
inline for (pwhashes) |H| {
if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) {
const throughput = try benchmarkPwhash(H.ty, H.params, mode(64));
try stdout.print("{s:>17}: {d:10.3} s/ops\n", .{ H.name, throughput });
}
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/scrypt.zig | // https://tools.ietf.org/html/rfc7914
// https://github.com/golang/crypto/blob/master/scrypt/scrypt.go
const std = @import("std");
const crypto = std.crypto;
const fmt = std.fmt;
const io = std.io;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const pwhash = crypto.pwhash;
const phc_format = @import("phc_encoding.zig");
const HmacSha256 = crypto.auth.hmac.sha2.HmacSha256;
const KdfError = pwhash.KdfError;
const HasherError = pwhash.HasherError;
const EncodingError = phc_format.Error;
const Error = pwhash.Error;
const max_size = math.maxInt(usize);
const max_int = max_size >> 1;
const default_salt_len = 32;
const default_hash_len = 32;
const max_salt_len = 64;
const max_hash_len = 64;
fn blockCopy(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
mem.copy(u32, dst, src[0 .. n * 16]);
}
fn blockXor(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
for (src[0 .. n * 16], 0..) |v, i| {
dst[i] ^= v;
}
}
const QuarterRound = struct { a: usize, b: usize, c: usize, d: u6 };
fn Rp(a: usize, b: usize, c: usize, d: u6) QuarterRound {
return QuarterRound{ .a = a, .b = b, .c = c, .d = d };
}
fn salsa8core(b: *align(16) [16]u32) void {
const arx_steps = comptime [_]QuarterRound{
Rp(4, 0, 12, 7), Rp(8, 4, 0, 9), Rp(12, 8, 4, 13), Rp(0, 12, 8, 18),
Rp(9, 5, 1, 7), Rp(13, 9, 5, 9), Rp(1, 13, 9, 13), Rp(5, 1, 13, 18),
Rp(14, 10, 6, 7), Rp(2, 14, 10, 9), Rp(6, 2, 14, 13), Rp(10, 6, 2, 18),
Rp(3, 15, 11, 7), Rp(7, 3, 15, 9), Rp(11, 7, 3, 13), Rp(15, 11, 7, 18),
Rp(1, 0, 3, 7), Rp(2, 1, 0, 9), Rp(3, 2, 1, 13), Rp(0, 3, 2, 18),
Rp(6, 5, 4, 7), Rp(7, 6, 5, 9), Rp(4, 7, 6, 13), Rp(5, 4, 7, 18),
Rp(11, 10, 9, 7), Rp(8, 11, 10, 9), Rp(9, 8, 11, 13), Rp(10, 9, 8, 18),
Rp(12, 15, 14, 7), Rp(13, 12, 15, 9), Rp(14, 13, 12, 13), Rp(15, 14, 13, 18),
};
var x = b.*;
var j: usize = 0;
while (j < 8) : (j += 2) {
inline for (arx_steps) |r| {
x[r.a] ^= math.rotl(u32, x[r.b] +% x[r.c], r.d);
}
}
j = 0;
while (j < 16) : (j += 1) {
b[j] +%= x[j];
}
}
fn salsaXor(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32) void {
blockXor(tmp, in, 1);
salsa8core(tmp);
blockCopy(out, tmp, 1);
}
fn blockMix(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32, r: u30) void {
blockCopy(tmp, in[(2 * r - 1) * 16 ..], 1);
var i: usize = 0;
while (i < 2 * r) : (i += 2) {
salsaXor(tmp, in[i * 16 ..], out[i * 8 ..]);
salsaXor(tmp, in[i * 16 + 16 ..], out[i * 8 + r * 16 ..]);
}
}
fn integerify(b: []align(16) const u32, r: u30) u64 {
const j = (2 * r - 1) * 16;
return @as(u64, b[j]) | @as(u64, b[j + 1]) << 32;
}
fn smix(b: []align(16) u8, r: u30, n: usize, v: []align(16) u32, xy: []align(16) u32) void {
var x = xy[0 .. 32 * r];
var y = xy[32 * r ..];
for (x, 0..) |*v1, j| {
v1.* = mem.readIntSliceLittle(u32, b[4 * j ..]);
}
var tmp: [16]u32 align(16) = undefined;
var i: usize = 0;
while (i < n) : (i += 2) {
blockCopy(v[i * (32 * r) ..], x, 2 * r);
blockMix(&tmp, x, y, r);
blockCopy(v[(i + 1) * (32 * r) ..], y, 2 * r);
blockMix(&tmp, y, x, r);
}
i = 0;
while (i < n) : (i += 2) {
var j = @as(usize, @intCast(integerify(x, r) & (n - 1)));
blockXor(x, v[j * (32 * r) ..], 2 * r);
blockMix(&tmp, x, y, r);
j = @as(usize, @intCast(integerify(y, r) & (n - 1)));
blockXor(y, v[j * (32 * r) ..], 2 * r);
blockMix(&tmp, y, x, r);
}
for (x, 0..) |v1, j| {
mem.writeIntLittle(u32, b[4 * j ..][0..4], v1);
}
}
pub const Params = struct {
const Self = @This();
ln: u6,
r: u30,
p: u30,
/// Baseline parameters for interactive logins
pub const interactive = Self.fromLimits(524288, 16777216);
/// Baseline parameters for offline usage
pub const sensitive = Self.fromLimits(33554432, 1073741824);
/// Create parameters from ops and mem limits
pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self {
const ops = math.max(32768, ops_limit);
const r: u30 = 8;
if (ops < mem_limit / 32) {
const max_n = ops / (r * 4);
return Self{ .r = r, .p = 1, .ln = @as(u6, @intCast(math.log2(max_n))) };
} else {
const max_n = mem_limit / (@as(usize, @intCast(r)) * 128);
const ln = @as(u6, @intCast(math.log2(max_n)));
const max_rp = math.min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln));
return Self{ .r = r, .p = @as(u30, @intCast(max_rp / @as(u64, r))), .ln = ln };
}
}
};
/// Apply scrypt to generate a key from a password.
///
/// scrypt is defined in RFC 7914.
///
/// allocator: *mem.Allocator.
///
/// derived_key: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
/// May be uninitialized. All bytes will be overwritten.
/// Maximum size is `derived_key.len / 32 == 0xffff_ffff`.
///
/// password: Arbitrary sequence of bytes of any length.
///
/// salt: Arbitrary sequence of bytes of any length.
///
/// params: Params.
pub fn kdf(
allocator: *mem.Allocator,
derived_key: []u8,
password: []const u8,
salt: []const u8,
params: Params,
) KdfError!void {
if (derived_key.len == 0 or derived_key.len / 32 > 0xffff_ffff) return KdfError.OutputTooLong;
if (params.ln == 0 or params.r == 0 or params.p == 0) return KdfError.WeakParameters;
const n64 = @as(u64, 1) << params.ln;
if (n64 > max_size) return KdfError.WeakParameters;
const n = @as(usize, @intCast(n64));
if (@as(u64, params.r) * @as(u64, params.p) >= 1 << 30 or
params.r > max_int / 128 / @as(u64, params.p) or
params.r > max_int / 256 or
n > max_int / 128 / @as(u64, params.r)) return KdfError.WeakParameters;
var xy = try allocator.alignedAlloc(u32, 16, 64 * params.r);
defer allocator.free(xy);
var v = try allocator.alignedAlloc(u32, 16, 32 * n * params.r);
defer allocator.free(v);
var dk = try allocator.alignedAlloc(u8, 16, params.p * 128 * params.r);
defer allocator.free(dk);
try pwhash.pbkdf2(dk, password, salt, 1, HmacSha256);
var i: u32 = 0;
while (i < params.p) : (i += 1) {
smix(dk[i * 128 * params.r ..], params.r, n, v, xy);
}
try pwhash.pbkdf2(derived_key, password, dk, 1, HmacSha256);
}
const crypt_format = struct {
/// String prefix for scrypt
pub const prefix = "$7$";
/// Standard type for a set of scrypt parameters, with the salt and hash.
pub fn HashResult(comptime crypt_max_hash_len: usize) type {
return struct {
ln: u6,
r: u30,
p: u30,
salt: []const u8,
hash: BinValue(crypt_max_hash_len),
};
}
const Codec = CustomB64Codec("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".*);
/// A wrapped binary value whose maximum size is `max_len`.
///
/// This type must be used whenever a binary value is encoded in a PHC-formatted string.
/// This includes `salt`, `hash`, and any other binary parameters such as keys.
///
/// Once initialized, the actual value can be read with the `constSlice()` function.
pub fn BinValue(comptime max_len: usize) type {
return struct {
const Self = @This();
const capacity = max_len;
const max_encoded_length = Codec.encodedLen(max_len);
buf: [max_len]u8 = undefined,
len: usize = 0,
/// Wrap an existing byte slice
pub fn fromSlice(slice: []const u8) EncodingError!Self {
if (slice.len > capacity) return EncodingError.NoSpaceLeft;
var bin_value: Self = undefined;
mem.copy(u8, &bin_value.buf, slice);
bin_value.len = slice.len;
return bin_value;
}
/// Return the slice containing the actual value.
pub fn constSlice(self: Self) []const u8 {
return self.buf[0..self.len];
}
fn fromB64(self: *Self, str: []const u8) !void {
const len = Codec.decodedLen(str.len);
if (len > self.buf.len) return EncodingError.NoSpaceLeft;
try Codec.decode(self.buf[0..len], str);
self.len = len;
}
fn toB64(self: Self, buf: []u8) ![]const u8 {
const value = self.constSlice();
const len = Codec.encodedLen(value.len);
if (len > buf.len) return EncodingError.NoSpaceLeft;
var encoded = buf[0..len];
Codec.encode(encoded, value);
return encoded;
}
};
}
/// Expand binary data into a salt for the modular crypt format.
pub fn saltFromBin(comptime len: usize, salt: [len]u8) [Codec.encodedLen(len)]u8 {
var buf: [Codec.encodedLen(len)]u8 = undefined;
Codec.encode(&buf, &salt);
return buf;
}
/// Deserialize a string into a structure `T` (matching `HashResult`).
pub fn deserialize(comptime T: type, str: []const u8) EncodingError!T {
var out: T = undefined;
if (str.len < 16) return EncodingError.InvalidEncoding;
if (!mem.eql(u8, prefix, str[0..3])) return EncodingError.InvalidEncoding;
out.ln = try Codec.intDecode(u6, str[3..4]);
out.r = try Codec.intDecode(u30, str[4..9]);
out.p = try Codec.intDecode(u30, str[9..14]);
var it = mem.split(u8, str[14..], "$");
const salt = it.next() orelse return EncodingError.InvalidEncoding;
if (@hasField(T, "salt")) out.salt = salt;
const hash_str = it.next() orelse return EncodingError.InvalidEncoding;
if (@hasField(T, "hash")) try out.hash.fromB64(hash_str);
return out;
}
/// Serialize parameters into a string in modular crypt format.
pub fn serialize(params: anytype, str: []u8) EncodingError![]const u8 {
var buf = io.fixedBufferStream(str);
try serializeTo(params, buf.writer());
return buf.getWritten();
}
/// Compute the number of bytes required to serialize `params`
pub fn calcSize(params: anytype) usize {
var buf = io.countingWriter(io.null_writer);
serializeTo(params, buf.writer()) catch unreachable;
return @as(usize, @intCast(buf.bytes_written));
}
fn serializeTo(params: anytype, out: anytype) !void {
var header: [14]u8 = undefined;
mem.copy(u8, header[0..3], prefix);
Codec.intEncode(header[3..4], params.ln);
Codec.intEncode(header[4..9], params.r);
Codec.intEncode(header[9..14], params.p);
try out.writeAll(&header);
try out.writeAll(params.salt);
try out.writeAll("$");
var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
const hash_str = try params.hash.toB64(&buf);
try out.writeAll(hash_str);
}
/// Custom codec that maps 6 bits into 8 like regular Base64, but uses its own alphabet,
/// encodes bits in little-endian, and can also encode integers.
fn CustomB64Codec(comptime map: [64]u8) type {
return struct {
const map64 = map;
fn encodedLen(len: usize) usize {
return (len * 4 + 2) / 3;
}
fn decodedLen(len: usize) usize {
return len / 4 * 3 + (len % 4) * 3 / 4;
}
fn intEncode(dst: []u8, src: anytype) void {
var n = src;
for (dst) |*x| {
x.* = map64[@as(u6, @truncate(n))];
n = math.shr(@TypeOf(src), n, 6);
}
}
fn intDecode(comptime T: type, src: *const [(meta.bitCount(T) + 5) / 6]u8) !T {
var v: T = 0;
for (src, 0..) |x, i| {
const vi = mem.indexOfScalar(u8, &map64, x) orelse return EncodingError.InvalidEncoding;
v |= @as(T, @intCast(vi)) << @as(math.Log2Int(T), @intCast(i * 6));
}
return v;
}
fn decode(dst: []u8, src: []const u8) !void {
std.debug.assert(dst.len == decodedLen(src.len));
var i: usize = 0;
while (i < src.len / 4) : (i += 1) {
mem.writeIntSliceLittle(u24, dst[i * 3 ..], try intDecode(u24, src[i * 4 ..][0..4]));
}
const leftover = src[i * 4 ..];
var v: u24 = 0;
for (leftover, 0..) |_, j| {
v |= @as(u24, try intDecode(u6, leftover[j..][0..1])) << @as(u5, @intCast(j * 6));
}
for (dst[i * 3 ..], 0..) |*x, j| {
x.* = @as(u8, @truncate(v >> @as(u5, @intCast(j * 8))));
}
}
fn encode(dst: []u8, src: []const u8) void {
std.debug.assert(dst.len == encodedLen(src.len));
var i: usize = 0;
while (i < src.len / 3) : (i += 1) {
intEncode(dst[i * 4 ..][0..4], mem.readIntSliceLittle(u24, src[i * 3 ..]));
}
const leftover = src[i * 3 ..];
var v: u24 = 0;
for (leftover, 0..) |x, j| {
v |= @as(u24, x) << @as(u5, @intCast(j * 8));
}
intEncode(dst[i * 4 ..], v);
}
};
}
};
/// Hash and verify passwords using the PHC format.
const PhcFormatHasher = struct {
const alg_id = "scrypt";
const BinValue = phc_format.BinValue;
const HashResult = struct {
alg_id: []const u8,
ln: u6,
r: u30,
p: u30,
salt: BinValue(max_salt_len),
hash: BinValue(max_hash_len),
};
/// Return a non-deterministic hash of the password encoded as a PHC-format string
pub fn create(
allocator: *mem.Allocator,
password: []const u8,
params: Params,
buf: []u8,
) HasherError![]const u8 {
var salt: [default_salt_len]u8 = undefined;
crypto.random.bytes(&salt);
var hash: [default_hash_len]u8 = undefined;
try kdf(allocator, &hash, password, &salt, params);
return phc_format.serialize(HashResult{
.alg_id = alg_id,
.ln = params.ln,
.r = params.r,
.p = params.p,
.salt = try BinValue(max_salt_len).fromSlice(&salt),
.hash = try BinValue(max_hash_len).fromSlice(&hash),
}, buf);
}
/// Verify a password against a PHC-format encoded string
pub fn verify(
allocator: *mem.Allocator,
str: []const u8,
password: []const u8,
) HasherError!void {
const hash_result = try phc_format.deserialize(HashResult, str);
if (!mem.eql(u8, hash_result.alg_id, alg_id)) return HasherError.PasswordVerificationFailed;
const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
const expected_hash = hash_result.hash.constSlice();
var hash_buf: [max_hash_len]u8 = undefined;
if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding;
var hash = hash_buf[0..expected_hash.len];
try kdf(allocator, hash, password, hash_result.salt.constSlice(), params);
if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed;
}
};
/// Hash and verify passwords using the modular crypt format.
const CryptFormatHasher = struct {
const BinValue = crypt_format.BinValue;
const HashResult = crypt_format.HashResult(max_hash_len);
/// Length of a string returned by the create() function
pub const pwhash_str_length: usize = 101;
/// Return a non-deterministic hash of the password encoded into the modular crypt format
pub fn create(
allocator: *mem.Allocator,
password: []const u8,
params: Params,
buf: []u8,
) HasherError![]const u8 {
var salt_bin: [default_salt_len]u8 = undefined;
crypto.random.bytes(&salt_bin);
const salt = crypt_format.saltFromBin(salt_bin.len, salt_bin);
var hash: [default_hash_len]u8 = undefined;
try kdf(allocator, &hash, password, &salt, params);
return crypt_format.serialize(HashResult{
.ln = params.ln,
.r = params.r,
.p = params.p,
.salt = &salt,
.hash = try BinValue(max_hash_len).fromSlice(&hash),
}, buf);
}
/// Verify a password against a string in modular crypt format
pub fn verify(
allocator: *mem.Allocator,
str: []const u8,
password: []const u8,
) HasherError!void {
const hash_result = try crypt_format.deserialize(HashResult, str);
const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
const expected_hash = hash_result.hash.constSlice();
var hash_buf: [max_hash_len]u8 = undefined;
if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding;
var hash = hash_buf[0..expected_hash.len];
try kdf(allocator, hash, password, hash_result.salt, params);
if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed;
}
};
/// Options for hashing a password.
pub const HashOptions = struct {
allocator: ?*mem.Allocator,
params: Params,
encoding: pwhash.Encoding,
};
/// Compute a hash of a password using the scrypt key derivation function.
/// The function returns a string that includes all the parameters required for verification.
pub fn strHash(
password: []const u8,
options: HashOptions,
out: []u8,
) Error![]const u8 {
const allocator = options.allocator orelse return Error.AllocatorRequired;
switch (options.encoding) {
.phc => return PhcFormatHasher.create(allocator, password, options.params, out),
.crypt => return CryptFormatHasher.create(allocator, password, options.params, out),
}
}
/// Options for hash verification.
pub const VerifyOptions = struct {
allocator: ?*mem.Allocator,
};
/// Verify that a previously computed hash is valid for a given password.
pub fn strVerify(
str: []const u8,
password: []const u8,
options: VerifyOptions,
) Error!void {
const allocator = options.allocator orelse return Error.AllocatorRequired;
if (mem.startsWith(u8, str, crypt_format.prefix)) {
return CryptFormatHasher.verify(allocator, str, password);
} else {
return PhcFormatHasher.verify(allocator, str, password);
}
}
// These tests take way too long to run, so I have disabled them.
const run_long_tests = false;
test "kdf" {
if (!run_long_tests) return error.SkipZigTest;
const password = "testpass";
const salt = "saltsalt";
var dk: [32]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 15, .r = 8, .p = 1 });
const hex = "1e0f97c3f6609024022fbe698da29c2fe53ef1087a8e396dc6d5d2a041e886de";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 1" {
if (!run_long_tests) return error.SkipZigTest;
const password = "";
const salt = "";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 4, .r = 1, .p = 1 });
const hex = "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 2" {
if (!run_long_tests) return error.SkipZigTest;
const password = "password";
const salt = "NaCl";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 10, .r = 8, .p = 16 });
const hex = "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 3" {
if (!run_long_tests) return error.SkipZigTest;
const password = "pleaseletmein";
const salt = "SodiumChloride";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 14, .r = 8, .p = 1 });
const hex = "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 4" {
if (!run_long_tests) return error.SkipZigTest;
const password = "pleaseletmein";
const salt = "SodiumChloride";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 20, .r = 8, .p = 1 });
const hex = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "password hashing (crypt format)" {
if (!run_long_tests) return error.SkipZigTest;
const str = "$7$A6....1....TrXs5Zk6s8sWHpQgWDIXTR8kUU3s6Jc3s.DtdS8M2i4$a4ik5hGDN7foMuHOW.cp.CtX01UyCeO0.JAG.AHPpx5";
const password = "Y0!?iQa9M%5ekffW(`";
try CryptFormatHasher.verify(std.testing.allocator, str, password);
const params = Params.interactive;
var buf: [CryptFormatHasher.pwhash_str_length]u8 = undefined;
const str2 = try CryptFormatHasher.create(std.testing.allocator, password, params, &buf);
try CryptFormatHasher.verify(std.testing.allocator, str2, password);
}
test "strHash and strVerify" {
if (!run_long_tests) return error.SkipZigTest;
const alloc = std.testing.allocator;
const password = "testpass";
const verify_options = VerifyOptions{ .allocator = alloc };
var buf: [128]u8 = undefined;
const s = try strHash(
password,
HashOptions{ .allocator = alloc, .params = Params.interactive, .encoding = .crypt },
&buf,
);
try strVerify(s, password, verify_options);
const s1 = try strHash(
password,
HashOptions{ .allocator = alloc, .params = Params.interactive, .encoding = .phc },
&buf,
);
try strVerify(s1, password, verify_options);
}
test "unix-scrypt" {
if (!run_long_tests) return error.SkipZigTest;
const alloc = std.testing.allocator;
// https://gitlab.com/jas/scrypt-unix-crypt/blob/master/unix-scrypt.txt
{
const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D";
const password = "pleaseletmein";
try strVerify(str, password, .{ .allocator = alloc });
}
// one of the libsodium test vectors
{
const str = "$7$B6....1....75gBMAGwfFWZqBdyF3WdTQnWdUsuTiWjG1fF9c1jiSD$tc8RoB3.Em3/zNgMLWo2u00oGIoTyJv4fl3Fl8Tix72";
const password = "^T5H$JYt39n%K*j:W]!1s?vg!:jGi]Ax?..l7[p0v:1jHTpla9;]bUN;?bWyCbtqg nrDFal+Jxl3,2`#^tFSu%v_+7iYse8-cCkNf!tD=KrW)";
try strVerify(str, password, .{ .allocator = alloc });
}
}
test "crypt format" {
const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D";
const params = try crypt_format.deserialize(crypt_format.HashResult(32), str);
var buf: [str.len]u8 = undefined;
const s1 = try crypt_format.serialize(params, &buf);
try std.testing.expectEqualStrings(s1, str);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes_ocb.zig | const std = @import("std");
const builtin = @import("builtin");
const crypto = std.crypto;
const aes = crypto.core.aes;
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const AuthenticationError = crypto.errors.AuthenticationError;
pub const Aes128Ocb = AesOcb(aes.Aes128);
pub const Aes256Ocb = AesOcb(aes.Aes256);
const Block = [16]u8;
/// AES-OCB (RFC 7253 - https://competitions.cr.yp.to/round3/ocbv11.pdf)
fn AesOcb(comptime Aes: anytype) type {
const EncryptCtx = aes.AesEncryptCtx(Aes);
const DecryptCtx = aes.AesDecryptCtx(Aes);
return struct {
pub const key_length = Aes.key_bits / 8;
pub const nonce_length: usize = 12;
pub const tag_length: usize = 16;
const Lx = struct {
star: Block align(16),
dol: Block align(16),
table: [56]Block align(16) = undefined,
upto: usize,
inline fn double(l: Block) Block {
const l_ = mem.readIntBig(u128, &l);
const l_2 = (l_ << 1) ^ (0x87 & -%(l_ >> 127));
var l2: Block = undefined;
mem.writeIntBig(u128, &l2, l_2);
return l2;
}
fn precomp(lx: *Lx, upto: usize) []const Block {
const table = &lx.table;
assert(upto < table.len);
var i = lx.upto;
while (i + 1 <= upto) : (i += 1) {
table[i + 1] = double(table[i]);
}
lx.upto = upto;
return lx.table[0 .. upto + 1];
}
fn init(aes_enc_ctx: EncryptCtx) Lx {
const zeros = [_]u8{0} ** 16;
var star: Block = undefined;
aes_enc_ctx.encrypt(&star, &zeros);
const dol = double(star);
var lx = Lx{ .star = star, .dol = dol, .upto = 0 };
lx.table[0] = double(dol);
return lx;
}
};
fn hash(aes_enc_ctx: EncryptCtx, lx: *Lx, a: []const u8) Block {
const full_blocks: usize = a.len / 16;
const x_max = if (full_blocks > 0) math.log2_int(usize, full_blocks) else 0;
const lt = lx.precomp(x_max);
var sum = [_]u8{0} ** 16;
var offset = [_]u8{0} ** 16;
var i: usize = 0;
while (i < full_blocks) : (i += 1) {
xorWith(&offset, lt[@ctz(i + 1)]);
var e = xorBlocks(offset, a[i * 16 ..][0..16].*);
aes_enc_ctx.encrypt(&e, &e);
xorWith(&sum, e);
}
const leftover = a.len % 16;
if (leftover > 0) {
xorWith(&offset, lx.star);
var padded = [_]u8{0} ** 16;
mem.copy(u8, padded[0..leftover], a[i * 16 ..][0..leftover]);
padded[leftover] = 1;
var e = xorBlocks(offset, padded);
aes_enc_ctx.encrypt(&e, &e);
xorWith(&sum, e);
}
return sum;
}
fn getOffset(aes_enc_ctx: EncryptCtx, npub: [nonce_length]u8) Block {
var nx = [_]u8{0} ** 16;
nx[0] = @as(u8, @intCast(@as(u7, @truncate(tag_length * 8)) << 1));
nx[16 - nonce_length - 1] = 1;
mem.copy(u8, nx[16 - nonce_length ..], &npub);
const bottom = @as(u6, @truncate(nx[15]));
nx[15] &= 0xc0;
var ktop_: Block = undefined;
aes_enc_ctx.encrypt(&ktop_, &nx);
const ktop = mem.readIntBig(u128, &ktop_);
var stretch = (@as(u192, ktop) << 64) | @as(u192, @as(u64, @truncate(ktop >> 64)) ^ @as(u64, @truncate(ktop >> 56)));
var offset: Block = undefined;
mem.writeIntBig(u128, &offset, @as(u128, @truncate(stretch >> (64 - @as(u7, bottom)))));
return offset;
}
const has_aesni = std.Target.x86.featureSetHas(builtin.cpu.features, .aes);
const has_armaes = std.Target.aarch64.featureSetHas(builtin.cpu.features, .aes);
const wb: usize = if ((builtin.cpu.arch == .x86_64 and has_aesni) or (builtin.cpu.arch == .aarch64 and has_armaes)) 4 else 0;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: secret key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
assert(c.len == m.len);
const aes_enc_ctx = Aes.initEnc(key);
const full_blocks: usize = m.len / 16;
const x_max = if (full_blocks > 0) math.log2_int(usize, full_blocks) else 0;
var lx = Lx.init(aes_enc_ctx);
const lt = lx.precomp(x_max);
var offset = getOffset(aes_enc_ctx, npub);
var sum = [_]u8{0} ** 16;
var i: usize = 0;
while (wb > 0 and i + wb <= full_blocks) : (i += wb) {
var offsets: [wb]Block align(16) = undefined;
var es: [16 * wb]u8 align(16) = undefined;
var j: usize = 0;
while (j < wb) : (j += 1) {
xorWith(&offset, lt[@ctz(i + 1 + j)]);
offsets[j] = offset;
const p = m[(i + j) * 16 ..][0..16].*;
mem.copy(u8, es[j * 16 ..][0..16], &xorBlocks(p, offsets[j]));
xorWith(&sum, p);
}
aes_enc_ctx.encryptWide(wb, &es, &es);
j = 0;
while (j < wb) : (j += 1) {
const e = es[j * 16 ..][0..16].*;
mem.copy(u8, c[(i + j) * 16 ..][0..16], &xorBlocks(e, offsets[j]));
}
}
while (i < full_blocks) : (i += 1) {
xorWith(&offset, lt[@ctz(i + 1)]);
const p = m[i * 16 ..][0..16].*;
var e = xorBlocks(p, offset);
aes_enc_ctx.encrypt(&e, &e);
mem.copy(u8, c[i * 16 ..][0..16], &xorBlocks(e, offset));
xorWith(&sum, p);
}
const leftover = m.len % 16;
if (leftover > 0) {
xorWith(&offset, lx.star);
var pad = offset;
aes_enc_ctx.encrypt(&pad, &pad);
for (m[i * 16 ..], 0..) |x, j| {
c[i * 16 + j] = pad[j] ^ x;
}
var e = [_]u8{0} ** 16;
mem.copy(u8, e[0..leftover], m[i * 16 ..][0..leftover]);
e[leftover] = 0x80;
xorWith(&sum, e);
}
var e = xorBlocks(xorBlocks(sum, offset), lx.dol);
aes_enc_ctx.encrypt(&e, &e);
tag.* = xorBlocks(e, hash(aes_enc_ctx, &lx, ad));
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: secret key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
const aes_enc_ctx = Aes.initEnc(key);
const aes_dec_ctx = DecryptCtx.initFromEnc(aes_enc_ctx);
const full_blocks: usize = m.len / 16;
const x_max = if (full_blocks > 0) math.log2_int(usize, full_blocks) else 0;
var lx = Lx.init(aes_enc_ctx);
const lt = lx.precomp(x_max);
var offset = getOffset(aes_enc_ctx, npub);
var sum = [_]u8{0} ** 16;
var i: usize = 0;
while (wb > 0 and i + wb <= full_blocks) : (i += wb) {
var offsets: [wb]Block align(16) = undefined;
var es: [16 * wb]u8 align(16) = undefined;
var j: usize = 0;
while (j < wb) : (j += 1) {
xorWith(&offset, lt[@ctz(i + 1 + j)]);
offsets[j] = offset;
const q = c[(i + j) * 16 ..][0..16].*;
mem.copy(u8, es[j * 16 ..][0..16], &xorBlocks(q, offsets[j]));
}
aes_dec_ctx.decryptWide(wb, &es, &es);
j = 0;
while (j < wb) : (j += 1) {
const p = xorBlocks(es[j * 16 ..][0..16].*, offsets[j]);
mem.copy(u8, m[(i + j) * 16 ..][0..16], &p);
xorWith(&sum, p);
}
}
while (i < full_blocks) : (i += 1) {
xorWith(&offset, lt[@ctz(i + 1)]);
const q = c[i * 16 ..][0..16].*;
var e = xorBlocks(q, offset);
aes_dec_ctx.decrypt(&e, &e);
const p = xorBlocks(e, offset);
mem.copy(u8, m[i * 16 ..][0..16], &p);
xorWith(&sum, p);
}
const leftover = m.len % 16;
if (leftover > 0) {
xorWith(&offset, lx.star);
var pad = offset;
aes_enc_ctx.encrypt(&pad, &pad);
for (c[i * 16 ..], 0..) |x, j| {
m[i * 16 + j] = pad[j] ^ x;
}
var e = [_]u8{0} ** 16;
mem.copy(u8, e[0..leftover], m[i * 16 ..][0..leftover]);
e[leftover] = 0x80;
xorWith(&sum, e);
}
var e = xorBlocks(xorBlocks(sum, offset), lx.dol);
aes_enc_ctx.encrypt(&e, &e);
var computed_tag = xorBlocks(e, hash(aes_enc_ctx, &lx, ad));
const verify = crypto.utils.timingSafeEql([tag_length]u8, computed_tag, tag);
crypto.utils.secureZero(u8, &computed_tag);
if (!verify) {
return error.AuthenticationFailed;
}
}
};
}
inline fn xorBlocks(x: Block, y: Block) Block {
var z: Block = x;
for (z, 0..) |*v, i| {
v.* = x[i] ^ y[i];
}
return z;
}
inline fn xorWith(x: *Block, y: Block) void {
for (x, 0..) |*v, i| {
v.* ^= y[i];
}
}
const hexToBytes = std.fmt.hexToBytes;
test "AesOcb test vector 1" {
var k: [Aes128Ocb.key_length]u8 = undefined;
var nonce: [Aes128Ocb.nonce_length]u8 = undefined;
var tag: [Aes128Ocb.tag_length]u8 = undefined;
_ = try hexToBytes(&k, "000102030405060708090A0B0C0D0E0F");
_ = try hexToBytes(&nonce, "BBAA99887766554433221100");
var c: [0]u8 = undefined;
Aes128Ocb.encrypt(&c, &tag, "", "", nonce, k);
var expected_tag: [tag.len]u8 = undefined;
_ = try hexToBytes(&expected_tag, "785407BFFFC8AD9EDCC5520AC9111EE6");
var m: [0]u8 = undefined;
try Aes128Ocb.decrypt(&m, "", tag, "", nonce, k);
}
test "AesOcb test vector 2" {
var k: [Aes128Ocb.key_length]u8 = undefined;
var nonce: [Aes128Ocb.nonce_length]u8 = undefined;
var tag: [Aes128Ocb.tag_length]u8 = undefined;
var ad: [40]u8 = undefined;
_ = try hexToBytes(&k, "000102030405060708090A0B0C0D0E0F");
_ = try hexToBytes(&ad, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627");
_ = try hexToBytes(&nonce, "BBAA9988776655443322110E");
var c: [0]u8 = undefined;
Aes128Ocb.encrypt(&c, &tag, "", &ad, nonce, k);
var expected_tag: [tag.len]u8 = undefined;
_ = try hexToBytes(&expected_tag, "C5CD9D1850C141E358649994EE701B68");
var m: [0]u8 = undefined;
try Aes128Ocb.decrypt(&m, &c, tag, &ad, nonce, k);
}
test "AesOcb test vector 3" {
var k: [Aes128Ocb.key_length]u8 = undefined;
var nonce: [Aes128Ocb.nonce_length]u8 = undefined;
var tag: [Aes128Ocb.tag_length]u8 = undefined;
var m: [40]u8 = undefined;
var c: [m.len]u8 = undefined;
_ = try hexToBytes(&k, "000102030405060708090A0B0C0D0E0F");
_ = try hexToBytes(&m, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627");
_ = try hexToBytes(&nonce, "BBAA9988776655443322110F");
Aes128Ocb.encrypt(&c, &tag, &m, "", nonce, k);
var expected_c: [c.len]u8 = undefined;
var expected_tag: [tag.len]u8 = undefined;
_ = try hexToBytes(&expected_tag, "479AD363AC366B95A98CA5F3000B1479");
_ = try hexToBytes(&expected_c, "4412923493C57D5DE0D700F753CCE0D1D2D95060122E9F15A5DDBFC5787E50B5CC55EE507BCB084E");
var m2: [m.len]u8 = undefined;
try Aes128Ocb.decrypt(&m2, &c, tag, "", nonce, k);
assert(mem.eql(u8, &m, &m2));
}
test "AesOcb test vector 4" {
var k: [Aes128Ocb.key_length]u8 = undefined;
var nonce: [Aes128Ocb.nonce_length]u8 = undefined;
var tag: [Aes128Ocb.tag_length]u8 = undefined;
var m: [40]u8 = undefined;
var ad = m;
var c: [m.len]u8 = undefined;
_ = try hexToBytes(&k, "000102030405060708090A0B0C0D0E0F");
_ = try hexToBytes(&m, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627");
_ = try hexToBytes(&nonce, "BBAA99887766554433221104");
Aes128Ocb.encrypt(&c, &tag, &m, &ad, nonce, k);
var expected_c: [c.len]u8 = undefined;
var expected_tag: [tag.len]u8 = undefined;
_ = try hexToBytes(&expected_tag, "3AD7A4FF3835B8C5701C1CCEC8FC3358");
_ = try hexToBytes(&expected_c, "571D535B60B277188BE5147170A9A22C");
var m2: [m.len]u8 = undefined;
try Aes128Ocb.decrypt(&m2, &c, tag, &ad, nonce, k);
assert(mem.eql(u8, &m, &m2));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aegis.zig | const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const AesBlock = std.crypto.core.aes.Block;
const AuthenticationError = std.crypto.errors.AuthenticationError;
const State128L = struct {
blocks: [8]AesBlock,
fn init(key: [16]u8, nonce: [16]u8) State128L {
const c1 = AesBlock.fromBytes(&[16]u8{ 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd });
const c2 = AesBlock.fromBytes(&[16]u8{ 0x0, 0x1, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 });
const key_block = AesBlock.fromBytes(&key);
const nonce_block = AesBlock.fromBytes(&nonce);
const blocks = [8]AesBlock{
key_block.xorBlocks(nonce_block),
c1,
c2,
c1,
key_block.xorBlocks(nonce_block),
key_block.xorBlocks(c2),
key_block.xorBlocks(c1),
key_block.xorBlocks(c2),
};
var state = State128L{ .blocks = blocks };
var i: usize = 0;
while (i < 10) : (i += 1) {
state.update(nonce_block, key_block);
}
return state;
}
inline fn update(state: *State128L, d1: AesBlock, d2: AesBlock) void {
const blocks = &state.blocks;
const tmp = blocks[7];
comptime var i: usize = 7;
inline while (i > 0) : (i -= 1) {
blocks[i] = blocks[i - 1].encrypt(blocks[i]);
}
blocks[0] = tmp.encrypt(blocks[0]);
blocks[0] = blocks[0].xorBlocks(d1);
blocks[4] = blocks[4].xorBlocks(d2);
}
fn enc(state: *State128L, dst: *[32]u8, src: *const [32]u8) void {
const blocks = &state.blocks;
const msg0 = AesBlock.fromBytes(src[0..16]);
const msg1 = AesBlock.fromBytes(src[16..32]);
var tmp0 = msg0.xorBlocks(blocks[6]).xorBlocks(blocks[1]);
var tmp1 = msg1.xorBlocks(blocks[2]).xorBlocks(blocks[5]);
tmp0 = tmp0.xorBlocks(blocks[2].andBlocks(blocks[3]));
tmp1 = tmp1.xorBlocks(blocks[6].andBlocks(blocks[7]));
dst[0..16].* = tmp0.toBytes();
dst[16..32].* = tmp1.toBytes();
state.update(msg0, msg1);
}
fn dec(state: *State128L, dst: *[32]u8, src: *const [32]u8) void {
const blocks = &state.blocks;
var msg0 = AesBlock.fromBytes(src[0..16]).xorBlocks(blocks[6]).xorBlocks(blocks[1]);
var msg1 = AesBlock.fromBytes(src[16..32]).xorBlocks(blocks[2]).xorBlocks(blocks[5]);
msg0 = msg0.xorBlocks(blocks[2].andBlocks(blocks[3]));
msg1 = msg1.xorBlocks(blocks[6].andBlocks(blocks[7]));
dst[0..16].* = msg0.toBytes();
dst[16..32].* = msg1.toBytes();
state.update(msg0, msg1);
}
fn mac(state: *State128L, adlen: usize, mlen: usize) [16]u8 {
const blocks = &state.blocks;
var sizes: [16]u8 = undefined;
mem.writeIntLittle(u64, sizes[0..8], adlen * 8);
mem.writeIntLittle(u64, sizes[8..16], mlen * 8);
const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[2]);
var i: usize = 0;
while (i < 7) : (i += 1) {
state.update(tmp, tmp);
}
return blocks[0].xorBlocks(blocks[1]).xorBlocks(blocks[2]).xorBlocks(blocks[3]).xorBlocks(blocks[4])
.xorBlocks(blocks[5]).xorBlocks(blocks[6]).toBytes();
}
};
/// AEGIS is a very fast authenticated encryption system built on top of the core AES function.
///
/// The 128L variant of AEGIS has a 128 bit key, a 128 bit nonce, and processes 256 bit message blocks.
/// It was designed to fully exploit the parallelism and built-in AES support of recent Intel and ARM CPUs.
///
/// https://competitions.cr.yp.to/round3/aegisv11.pdf
pub const Aegis128L = struct {
pub const tag_length = 16;
pub const nonce_length = 16;
pub const key_length = 16;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
assert(c.len == m.len);
var state = State128L.init(key, npub);
var src: [32]u8 align(16) = undefined;
var dst: [32]u8 align(16) = undefined;
var i: usize = 0;
while (i + 32 <= ad.len) : (i += 32) {
state.enc(&dst, ad[i..][0..32]);
}
if (ad.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]);
state.enc(&dst, &src);
}
i = 0;
while (i + 32 <= m.len) : (i += 32) {
state.enc(c[i..][0..32], m[i..][0..32]);
}
if (m.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 32], m[i .. i + m.len % 32]);
state.enc(&dst, &src);
mem.copy(u8, c[i .. i + m.len % 32], dst[0 .. m.len % 32]);
}
tag.* = state.mac(ad.len, m.len);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
var state = State128L.init(key, npub);
var src: [32]u8 align(16) = undefined;
var dst: [32]u8 align(16) = undefined;
var i: usize = 0;
while (i + 32 <= ad.len) : (i += 32) {
state.enc(&dst, ad[i..][0..32]);
}
if (ad.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]);
state.enc(&dst, &src);
}
i = 0;
while (i + 32 <= m.len) : (i += 32) {
state.dec(m[i..][0..32], c[i..][0..32]);
}
if (m.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 32], c[i .. i + m.len % 32]);
state.dec(&dst, &src);
mem.copy(u8, m[i .. i + m.len % 32], dst[0 .. m.len % 32]);
mem.set(u8, dst[0 .. m.len % 32], 0);
const blocks = &state.blocks;
blocks[0] = blocks[0].xorBlocks(AesBlock.fromBytes(dst[0..16]));
blocks[4] = blocks[4].xorBlocks(AesBlock.fromBytes(dst[16..32]));
}
const computed_tag = state.mac(ad.len, m.len);
var acc: u8 = 0;
for (computed_tag, 0..) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
if (acc != 0) {
mem.set(u8, m, 0xaa);
return error.AuthenticationFailed;
}
}
};
const State256 = struct {
blocks: [6]AesBlock,
fn init(key: [32]u8, nonce: [32]u8) State256 {
const c1 = AesBlock.fromBytes(&[16]u8{ 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd });
const c2 = AesBlock.fromBytes(&[16]u8{ 0x0, 0x1, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 });
const key_block1 = AesBlock.fromBytes(key[0..16]);
const key_block2 = AesBlock.fromBytes(key[16..32]);
const nonce_block1 = AesBlock.fromBytes(nonce[0..16]);
const nonce_block2 = AesBlock.fromBytes(nonce[16..32]);
const kxn1 = key_block1.xorBlocks(nonce_block1);
const kxn2 = key_block2.xorBlocks(nonce_block2);
const blocks = [6]AesBlock{
kxn1,
kxn2,
c1,
c2,
key_block1.xorBlocks(c2),
key_block2.xorBlocks(c1),
};
var state = State256{ .blocks = blocks };
var i: usize = 0;
while (i < 4) : (i += 1) {
state.update(key_block1);
state.update(key_block2);
state.update(kxn1);
state.update(kxn2);
}
return state;
}
inline fn update(state: *State256, d: AesBlock) void {
const blocks = &state.blocks;
const tmp = blocks[5].encrypt(blocks[0]);
comptime var i: usize = 5;
inline while (i > 0) : (i -= 1) {
blocks[i] = blocks[i - 1].encrypt(blocks[i]);
}
blocks[0] = tmp.xorBlocks(d);
}
fn enc(state: *State256, dst: *[16]u8, src: *const [16]u8) void {
const blocks = &state.blocks;
const msg = AesBlock.fromBytes(src);
var tmp = msg.xorBlocks(blocks[5]).xorBlocks(blocks[4]).xorBlocks(blocks[1]);
tmp = tmp.xorBlocks(blocks[2].andBlocks(blocks[3]));
dst.* = tmp.toBytes();
state.update(msg);
}
fn dec(state: *State256, dst: *[16]u8, src: *const [16]u8) void {
const blocks = &state.blocks;
var msg = AesBlock.fromBytes(src).xorBlocks(blocks[5]).xorBlocks(blocks[4]).xorBlocks(blocks[1]);
msg = msg.xorBlocks(blocks[2].andBlocks(blocks[3]));
dst.* = msg.toBytes();
state.update(msg);
}
fn mac(state: *State256, adlen: usize, mlen: usize) [16]u8 {
const blocks = &state.blocks;
var sizes: [16]u8 = undefined;
mem.writeIntLittle(u64, sizes[0..8], adlen * 8);
mem.writeIntLittle(u64, sizes[8..16], mlen * 8);
const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[3]);
var i: usize = 0;
while (i < 7) : (i += 1) {
state.update(tmp);
}
return blocks[0].xorBlocks(blocks[1]).xorBlocks(blocks[2]).xorBlocks(blocks[3]).xorBlocks(blocks[4])
.xorBlocks(blocks[5]).toBytes();
}
};
/// AEGIS is a very fast authenticated encryption system built on top of the core AES function.
///
/// The 256 bit variant of AEGIS has a 256 bit key, a 256 bit nonce, and processes 128 bit message blocks.
///
/// https://competitions.cr.yp.to/round3/aegisv11.pdf
pub const Aegis256 = struct {
pub const tag_length = 16;
pub const nonce_length = 32;
pub const key_length = 32;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
assert(c.len == m.len);
var state = State256.init(key, npub);
var src: [16]u8 align(16) = undefined;
var dst: [16]u8 align(16) = undefined;
var i: usize = 0;
while (i + 16 <= ad.len) : (i += 16) {
state.enc(&dst, ad[i..][0..16]);
}
if (ad.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 16], ad[i .. i + ad.len % 16]);
state.enc(&dst, &src);
}
i = 0;
while (i + 16 <= m.len) : (i += 16) {
state.enc(c[i..][0..16], m[i..][0..16]);
}
if (m.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 16], m[i .. i + m.len % 16]);
state.enc(&dst, &src);
mem.copy(u8, c[i .. i + m.len % 16], dst[0 .. m.len % 16]);
}
tag.* = state.mac(ad.len, m.len);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
var state = State256.init(key, npub);
var src: [16]u8 align(16) = undefined;
var dst: [16]u8 align(16) = undefined;
var i: usize = 0;
while (i + 16 <= ad.len) : (i += 16) {
state.enc(&dst, ad[i..][0..16]);
}
if (ad.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 16], ad[i .. i + ad.len % 16]);
state.enc(&dst, &src);
}
i = 0;
while (i + 16 <= m.len) : (i += 16) {
state.dec(m[i..][0..16], c[i..][0..16]);
}
if (m.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 16], c[i .. i + m.len % 16]);
state.dec(&dst, &src);
mem.copy(u8, m[i .. i + m.len % 16], dst[0 .. m.len % 16]);
mem.set(u8, dst[0 .. m.len % 16], 0);
const blocks = &state.blocks;
blocks[0] = blocks[0].xorBlocks(AesBlock.fromBytes(&dst));
}
const computed_tag = state.mac(ad.len, m.len);
var acc: u8 = 0;
for (computed_tag, 0..) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
if (acc != 0) {
mem.set(u8, m, 0xaa);
return error.AuthenticationFailed;
}
}
};
const htest = @import("test.zig");
const testing = std.testing;
test "Aegis128L test vector 1" {
const key: [Aegis128L.key_length]u8 = [_]u8{ 0x10, 0x01 } ++ [_]u8{0x00} ** 14;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{ 0x10, 0x00, 0x02 } ++ [_]u8{0x00} ** 13;
const ad = [8]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
const m = [32]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("79d94593d8c2119d7e8fd9b8fc77845c5c077a05b2528b6ac54b563aed8efe84", &c);
try htest.assertEqual("cc6f3372f6aa1bb82388d695c3962d9a", &tag);
c[0] +%= 1;
try testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
try testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis128L test vector 2" {
const key: [Aegis128L.key_length]u8 = [_]u8{0x00} ** 16;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{0x00} ** 16;
const ad = [_]u8{};
const m = [_]u8{0x00} ** 16;
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("41de9000a7b5e40e2d68bb64d99ebb19", &c);
try htest.assertEqual("f4d997cc9b94227ada4fe4165422b1c8", &tag);
}
test "Aegis128L test vector 3" {
const key: [Aegis128L.key_length]u8 = [_]u8{0x00} ** 16;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{0x00} ** 16;
const ad = [_]u8{};
const m = [_]u8{};
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("83cc600dc4e3e7e62d4055826174f149", &tag);
}
test "Aegis256 test vector 1" {
const key: [Aegis256.key_length]u8 = [_]u8{ 0x10, 0x01 } ++ [_]u8{0x00} ** 30;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{ 0x10, 0x00, 0x02 } ++ [_]u8{0x00} ** 29;
const ad = [8]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
const m = [32]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("f373079ed84b2709faee373584585d60accd191db310ef5d8b11833df9dec711", &c);
try htest.assertEqual("8d86f91ee606e9ff26a01b64ccbdd91d", &tag);
c[0] +%= 1;
try testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
try testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis256 test vector 2" {
const key: [Aegis256.key_length]u8 = [_]u8{0x00} ** 32;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{0x00} ** 32;
const ad = [_]u8{};
const m = [_]u8{0x00} ** 16;
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("b98f03a947807713d75a4fff9fc277a6", &c);
try htest.assertEqual("478f3b50dc478ef7d5cf2d0f7cc13180", &tag);
}
test "Aegis256 test vector 3" {
const key: [Aegis256.key_length]u8 = [_]u8{0x00} ** 32;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{0x00} ** 32;
const ad = [_]u8{};
const m = [_]u8{};
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &m, &m2);
try htest.assertEqual("f7a0878f68bd083e8065354071fc27c3", &tag);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/sha2.zig | const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const htest = @import("test.zig");
/////////////////////
// Sha224 + Sha256
const RoundParam256 = struct {
a: usize,
b: usize,
c: usize,
d: usize,
e: usize,
f: usize,
g: usize,
h: usize,
i: usize,
k: u32,
};
fn roundParam256(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u32) RoundParam256 {
return RoundParam256{
.a = a,
.b = b,
.c = c,
.d = d,
.e = e,
.f = f,
.g = g,
.h = h,
.i = i,
.k = k,
};
}
const Sha2Params32 = struct {
iv0: u32,
iv1: u32,
iv2: u32,
iv3: u32,
iv4: u32,
iv5: u32,
iv6: u32,
iv7: u32,
digest_bits: usize,
};
const Sha224Params = Sha2Params32{
.iv0 = 0xC1059ED8,
.iv1 = 0x367CD507,
.iv2 = 0x3070DD17,
.iv3 = 0xF70E5939,
.iv4 = 0xFFC00B31,
.iv5 = 0x68581511,
.iv6 = 0x64F98FA7,
.iv7 = 0xBEFA4FA4,
.digest_bits = 224,
};
const Sha256Params = Sha2Params32{
.iv0 = 0x6A09E667,
.iv1 = 0xBB67AE85,
.iv2 = 0x3C6EF372,
.iv3 = 0xA54FF53A,
.iv4 = 0x510E527F,
.iv5 = 0x9B05688C,
.iv6 = 0x1F83D9AB,
.iv7 = 0x5BE0CD19,
.digest_bits = 256,
};
/// SHA-224
pub const Sha224 = Sha2x32(Sha224Params);
/// SHA-256
pub const Sha256 = Sha2x32(Sha256Params);
fn Sha2x32(comptime params: Sha2Params32) type {
return struct {
const Self = @This();
pub const block_length = 64;
pub const digest_length = params.digest_bits / 8;
pub const Options = struct {};
s: [8]u32,
// Streaming Cache
buf: [64]u8 = undefined,
buf_len: u8 = 0,
total_len: u64 = 0,
pub fn init(options: Options) Self {
_ = options;
return Self{
.s = [_]u32{
params.iv0,
params.iv1,
params.iv2,
params.iv3,
params.iv4,
params.iv5,
params.iv6,
params.iv7,
},
};
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Self.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len >= 64) {
off += 64 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.round(&d.buf);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 64 <= b.len) : (off += 64) {
d.round(b[off..][0..64]);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
d.total_len += b.len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// The buffer here will never be completely full.
mem.set(u8, d.buf[d.buf_len..], 0);
// Append padding bits.
d.buf[d.buf_len] = 0x80;
d.buf_len += 1;
// > 448 mod 512 so need to add an extra round to wrap around.
if (64 - d.buf_len < 8) {
d.round(&d.buf);
mem.set(u8, d.buf[0..], 0);
}
// Append message length.
var i: usize = 1;
var len = d.total_len >> 5;
d.buf[63] = @as(u8, @intCast(d.total_len & 0x1f)) << 3;
while (i < 8) : (i += 1) {
d.buf[63 - i] = @as(u8, @intCast(len & 0xff));
len >>= 8;
}
d.round(&d.buf);
// May truncate for possible 224 output
const rr = d.s[0 .. params.digest_bits / 32];
for (rr, 0..) |s, j| {
mem.writeIntBig(u32, out[4 * j ..][0..4], s);
}
}
fn round(d: *Self, b: *const [64]u8) void {
var s: [64]u32 = undefined;
var i: usize = 0;
while (i < 16) : (i += 1) {
s[i] = 0;
s[i] |= @as(u32, b[i * 4 + 0]) << 24;
s[i] |= @as(u32, b[i * 4 + 1]) << 16;
s[i] |= @as(u32, b[i * 4 + 2]) << 8;
s[i] |= @as(u32, b[i * 4 + 3]) << 0;
}
while (i < 64) : (i += 1) {
s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u32, s[i - 15], @as(u32, 7)) ^ math.rotr(u32, s[i - 15], @as(u32, 18)) ^ (s[i - 15] >> 3)) +% (math.rotr(u32, s[i - 2], @as(u32, 17)) ^ math.rotr(u32, s[i - 2], @as(u32, 19)) ^ (s[i - 2] >> 10));
}
var v: [8]u32 = [_]u32{
d.s[0],
d.s[1],
d.s[2],
d.s[3],
d.s[4],
d.s[5],
d.s[6],
d.s[7],
};
const round0 = comptime [_]RoundParam256{
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x71374491),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCF),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA5),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25B),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B01),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A7),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C1),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC6),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DC),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C8),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF3),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x14292967),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A85),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B2138),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D13),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A7354),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C85),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A1),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664B),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A3),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD6990624),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E3585),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA070),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C08),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774C),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4A),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3),
roundParam256(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE),
roundParam256(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F),
roundParam256(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814),
roundParam256(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC70208),
roundParam256(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA),
roundParam256(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEB),
roundParam256(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7),
roundParam256(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2),
};
inline for (round0) |r| {
v[r.h] = v[r.h] +% (math.rotr(u32, v[r.e], @as(u32, 6)) ^ math.rotr(u32, v[r.e], @as(u32, 11)) ^ math.rotr(u32, v[r.e], @as(u32, 25))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
v[r.d] = v[r.d] +% v[r.h];
v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], @as(u32, 2)) ^ math.rotr(u32, v[r.a], @as(u32, 13)) ^ math.rotr(u32, v[r.a], @as(u32, 22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
}
d.s[0] +%= v[0];
d.s[1] +%= v[1];
d.s[2] +%= v[2];
d.s[3] +%= v[3];
d.s[4] +%= v[4];
d.s[5] +%= v[5];
d.s[6] +%= v[6];
d.s[7] +%= v[7];
}
};
}
test "sha224 single" {
try htest.assertEqualHash(Sha224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", "");
try htest.assertEqualHash(Sha224, "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "abc");
try htest.assertEqualHash(Sha224, "c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha224 streaming" {
var h = Sha224.init(.{});
var out: [28]u8 = undefined;
h.final(out[0..]);
try htest.assertEqual("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", out[0..]);
h = Sha224.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
h = Sha224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
}
test "sha256 single" {
try htest.assertEqualHash(Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "");
try htest.assertEqualHash(Sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc");
try htest.assertEqualHash(Sha256, "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha256 streaming" {
var h = Sha256.init(.{});
var out: [32]u8 = undefined;
h.final(out[0..]);
try htest.assertEqual("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", out[0..]);
h = Sha256.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
h = Sha256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
}
test "sha256 aligned final" {
var block = [_]u8{0} ** Sha256.block_length;
var out: [Sha256.digest_length]u8 = undefined;
var h = Sha256.init(.{});
h.update(&block);
h.final(out[0..]);
}
/////////////////////
// Sha384 + Sha512
const RoundParam512 = struct {
a: usize,
b: usize,
c: usize,
d: usize,
e: usize,
f: usize,
g: usize,
h: usize,
i: usize,
k: u64,
};
fn roundParam512(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u64) RoundParam512 {
return RoundParam512{
.a = a,
.b = b,
.c = c,
.d = d,
.e = e,
.f = f,
.g = g,
.h = h,
.i = i,
.k = k,
};
}
const Sha2Params64 = struct {
iv0: u64,
iv1: u64,
iv2: u64,
iv3: u64,
iv4: u64,
iv5: u64,
iv6: u64,
iv7: u64,
digest_bits: usize,
};
const Sha384Params = Sha2Params64{
.iv0 = 0xCBBB9D5DC1059ED8,
.iv1 = 0x629A292A367CD507,
.iv2 = 0x9159015A3070DD17,
.iv3 = 0x152FECD8F70E5939,
.iv4 = 0x67332667FFC00B31,
.iv5 = 0x8EB44A8768581511,
.iv6 = 0xDB0C2E0D64F98FA7,
.iv7 = 0x47B5481DBEFA4FA4,
.digest_bits = 384,
};
const Sha512Params = Sha2Params64{
.iv0 = 0x6A09E667F3BCC908,
.iv1 = 0xBB67AE8584CAA73B,
.iv2 = 0x3C6EF372FE94F82B,
.iv3 = 0xA54FF53A5F1D36F1,
.iv4 = 0x510E527FADE682D1,
.iv5 = 0x9B05688C2B3E6C1F,
.iv6 = 0x1F83D9ABFB41BD6B,
.iv7 = 0x5BE0CD19137E2179,
.digest_bits = 512,
};
const Sha512256Params = Sha2Params64{
.iv0 = 0x22312194FC2BF72C,
.iv1 = 0x9F555FA3C84C64C2,
.iv2 = 0x2393B86B6F53B151,
.iv3 = 0x963877195940EABD,
.iv4 = 0x96283EE2A88EFFE3,
.iv5 = 0xBE5E1E2553863992,
.iv6 = 0x2B0199FC2C85B8AA,
.iv7 = 0x0EB72DDC81C52CA2,
.digest_bits = 256,
};
const Sha512T256Params = Sha2Params64{
.iv0 = 0x6A09E667F3BCC908,
.iv1 = 0xBB67AE8584CAA73B,
.iv2 = 0x3C6EF372FE94F82B,
.iv3 = 0xA54FF53A5F1D36F1,
.iv4 = 0x510E527FADE682D1,
.iv5 = 0x9B05688C2B3E6C1F,
.iv6 = 0x1F83D9ABFB41BD6B,
.iv7 = 0x5BE0CD19137E2179,
.digest_bits = 256,
};
/// SHA-384
pub const Sha384 = Sha2x64(Sha384Params);
/// SHA-512
pub const Sha512 = Sha2x64(Sha512Params);
/// SHA-512/256
pub const Sha512256 = Sha2x64(Sha512256Params);
/// Truncated SHA-512
pub const Sha512T256 = Sha2x64(Sha512T256Params);
fn Sha2x64(comptime params: Sha2Params64) type {
return struct {
const Self = @This();
pub const block_length = 128;
pub const digest_length = params.digest_bits / 8;
pub const Options = struct {};
s: [8]u64,
// Streaming Cache
buf: [128]u8 = undefined,
buf_len: u8 = 0,
total_len: u128 = 0,
pub fn init(options: Options) Self {
_ = options;
return Self{
.s = [_]u64{
params.iv0,
params.iv1,
params.iv2,
params.iv3,
params.iv4,
params.iv5,
params.iv6,
params.iv7,
},
};
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Self.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len >= 128) {
off += 128 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.round(&d.buf);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 128 <= b.len) : (off += 128) {
d.round(b[off..][0..128]);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
d.total_len += b.len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// The buffer here will never be completely full.
mem.set(u8, d.buf[d.buf_len..], 0);
// Append padding bits.
d.buf[d.buf_len] = 0x80;
d.buf_len += 1;
// > 896 mod 1024 so need to add an extra round to wrap around.
if (128 - d.buf_len < 16) {
d.round(d.buf[0..]);
mem.set(u8, d.buf[0..], 0);
}
// Append message length.
var i: usize = 1;
var len = d.total_len >> 5;
d.buf[127] = @as(u8, @intCast(d.total_len & 0x1f)) << 3;
while (i < 16) : (i += 1) {
d.buf[127 - i] = @as(u8, @intCast(len & 0xff));
len >>= 8;
}
d.round(d.buf[0..]);
// May truncate for possible 384 output
const rr = d.s[0 .. params.digest_bits / 64];
for (rr, 0..) |s, j| {
mem.writeIntBig(u64, out[8 * j ..][0..8], s);
}
}
fn round(d: *Self, b: *const [128]u8) void {
var s: [80]u64 = undefined;
var i: usize = 0;
while (i < 16) : (i += 1) {
s[i] = 0;
s[i] |= @as(u64, b[i * 8 + 0]) << 56;
s[i] |= @as(u64, b[i * 8 + 1]) << 48;
s[i] |= @as(u64, b[i * 8 + 2]) << 40;
s[i] |= @as(u64, b[i * 8 + 3]) << 32;
s[i] |= @as(u64, b[i * 8 + 4]) << 24;
s[i] |= @as(u64, b[i * 8 + 5]) << 16;
s[i] |= @as(u64, b[i * 8 + 6]) << 8;
s[i] |= @as(u64, b[i * 8 + 7]) << 0;
}
while (i < 80) : (i += 1) {
s[i] = s[i - 16] +% s[i - 7] +%
(math.rotr(u64, s[i - 15], @as(u64, 1)) ^ math.rotr(u64, s[i - 15], @as(u64, 8)) ^ (s[i - 15] >> 7)) +%
(math.rotr(u64, s[i - 2], @as(u64, 19)) ^ math.rotr(u64, s[i - 2], @as(u64, 61)) ^ (s[i - 2] >> 6));
}
var v: [8]u64 = [_]u64{
d.s[0],
d.s[1],
d.s[2],
d.s[3],
d.s[4],
d.s[5],
d.s[6],
d.s[7],
};
const round0 = comptime [_]RoundParam512{
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98D728AE22),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x7137449123EF65CD),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCFEC4D3B2F),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA58189DBBC),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25BF348B538),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1B605D019),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4AF194F9B),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5DA6D8118),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98A3030242),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B0145706FBE),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE4EE4B28C),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3D5FFB4E2),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74F27B896F),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE3B1696B1),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A725C71235),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174CF692694),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C19EF14AD2),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786384F25E3),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC68B8CD5B5),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC77AC9C65),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F592B0275),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA6EA6E483),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DCBD41FBD4),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA831153B5),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152EE66DFAB),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D2DB43210),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C898FB213F),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7BEEF0EE4),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF33DA88FC2),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147930AA725),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351E003826F),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x142929670A0E6E70),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A8546D22FFC),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B21385C26C926),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC5AC42AED),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D139D95B3DF),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A73548BAF63DE),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB3C77B2A8),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E47EDAEE6),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C851482353B),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A14CF10364),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664BBC423001),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70D0F89791),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A30654BE30),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819D6EF5218),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD69906245565A910),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E35855771202A),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA07032BBD1B8),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116B8D2D0C8),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C085141AB53),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774CDF8EEB99),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5E19B48A8),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3C5C95A63),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4AE3418ACB),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F7763E373),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3D6B2B8A3),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE5DEFB2FC),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F43172F60),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814A1F0AB72),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC702081A6439EC),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA23631E28),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEBDE82BDE9),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7B2C67915),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2E372532B),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 64, 0xCA273ECEEA26619C),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 65, 0xD186B8C721C0C207),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 66, 0xEADA7DD6CDE0EB1E),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 67, 0xF57D4F7FEE6ED178),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 68, 0x06F067AA72176FBA),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 69, 0x0A637DC5A2C898A6),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 70, 0x113F9804BEF90DAE),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 71, 0x1B710B35131C471B),
roundParam512(0, 1, 2, 3, 4, 5, 6, 7, 72, 0x28DB77F523047D84),
roundParam512(7, 0, 1, 2, 3, 4, 5, 6, 73, 0x32CAAB7B40C72493),
roundParam512(6, 7, 0, 1, 2, 3, 4, 5, 74, 0x3C9EBE0A15C9BEBC),
roundParam512(5, 6, 7, 0, 1, 2, 3, 4, 75, 0x431D67C49C100D4C),
roundParam512(4, 5, 6, 7, 0, 1, 2, 3, 76, 0x4CC5D4BECB3E42B6),
roundParam512(3, 4, 5, 6, 7, 0, 1, 2, 77, 0x597F299CFC657E2A),
roundParam512(2, 3, 4, 5, 6, 7, 0, 1, 78, 0x5FCB6FAB3AD6FAEC),
roundParam512(1, 2, 3, 4, 5, 6, 7, 0, 79, 0x6C44198C4A475817),
};
inline for (round0) |r| {
v[r.h] = v[r.h] +% (math.rotr(u64, v[r.e], @as(u64, 14)) ^ math.rotr(u64, v[r.e], @as(u64, 18)) ^ math.rotr(u64, v[r.e], @as(u64, 41))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
v[r.d] = v[r.d] +% v[r.h];
v[r.h] = v[r.h] +% (math.rotr(u64, v[r.a], @as(u64, 28)) ^ math.rotr(u64, v[r.a], @as(u64, 34)) ^ math.rotr(u64, v[r.a], @as(u64, 39))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
}
d.s[0] +%= v[0];
d.s[1] +%= v[1];
d.s[2] +%= v[2];
d.s[3] +%= v[3];
d.s[4] +%= v[4];
d.s[5] +%= v[5];
d.s[6] +%= v[6];
d.s[7] +%= v[7];
}
};
}
test "sha384 single" {
const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b";
try htest.assertEqualHash(Sha384, h1, "");
const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7";
try htest.assertEqualHash(Sha384, h2, "abc");
const h3 = "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039";
try htest.assertEqualHash(Sha384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha384 streaming" {
var h = Sha384.init(.{});
var out: [48]u8 = undefined;
const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7";
h = Sha384.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha512 single" {
const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
try htest.assertEqualHash(Sha512, h1, "");
const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
try htest.assertEqualHash(Sha512, h2, "abc");
const h3 = "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909";
try htest.assertEqualHash(Sha512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha512 streaming" {
var h = Sha512.init(.{});
var out: [64]u8 = undefined;
const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
h = Sha512.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha512 aligned final" {
var block = [_]u8{0} ** Sha512.block_length;
var out: [Sha512.digest_length]u8 = undefined;
var h = Sha512.init(.{});
h.update(&block);
h.final(out[0..]);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pbkdf2.zig | const std = @import("std");
const mem = std.mem;
const maxInt = std.math.maxInt;
const OutputTooLongError = std.crypto.errors.OutputTooLongError;
const WeakParametersError = std.crypto.errors.WeakParametersError;
// RFC 2898 Section 5.2
//
// FromSpec:
//
// PBKDF2 applies a pseudorandom function (see Appendix B.1 for an
// example) to derive keys. The length of the derived key is essentially
// unbounded. (However, the maximum effective search space for the
// derived key may be limited by the structure of the underlying
// pseudorandom function. See Appendix B.1 for further discussion.)
// PBKDF2 is recommended for new applications.
//
// PBKDF2 (P, S, c, dk_len)
//
// Options: PRF underlying pseudorandom function (h_len
// denotes the length in octets of the
// pseudorandom function output)
//
// Input: P password, an octet string
// S salt, an octet string
// c iteration count, a positive integer
// dk_len intended length in octets of the derived
// key, a positive integer, at most
// (2^32 - 1) * h_len
//
// Output: DK derived key, a dk_len-octet string
// Based on Apple's CommonKeyDerivation, based originally on code by Damien Bergamini.
/// Apply PBKDF2 to generate a key from a password.
///
/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.
///
/// dk: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
/// May be uninitialized. All bytes will be overwritten.
/// Maximum size is `maxInt(u32) * Hash.digest_length`
/// It is a programming error to pass buffer longer than the maximum size.
///
/// password: Arbitrary sequence of bytes of any length, including empty.
///
/// salt: Arbitrary sequence of bytes of any length, including empty. A common length is 8 bytes.
///
/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.
/// Larger iteration counts improve security by increasing the time required to compute
/// the dk. It is common to tune this parameter to achieve approximately 100ms.
///
/// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`.
pub fn pbkdf2(dk: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) (WeakParametersError || OutputTooLongError)!void {
if (rounds < 1) return error.WeakParameters;
const dk_len = dk.len;
const h_len = Prf.mac_length;
comptime std.debug.assert(h_len >= 1);
// FromSpec:
//
// 1. If dk_len > maxInt(u32) * h_len, output "derived key too long" and
// stop.
//
if (dk_len / h_len >= maxInt(u32)) {
// Counter starts at 1 and is 32 bit, so if we have to return more blocks, we would overflow
return error.OutputTooLong;
}
// FromSpec:
//
// 2. Let l be the number of h_len-long blocks of bytes in the derived key,
// rounding up, and let r be the number of bytes in the last
// block
//
const blocks_count = @as(u32, @intCast(std.math.divCeil(usize, dk_len, h_len) catch unreachable));
var r = dk_len % h_len;
if (r == 0) {
r = h_len;
}
// FromSpec:
//
// 3. For each block of the derived key apply the function F defined
// below to the password P, the salt S, the iteration count c, and
// the block index to compute the block:
//
// T_1 = F (P, S, c, 1) ,
// T_2 = F (P, S, c, 2) ,
// ...
// T_l = F (P, S, c, l) ,
//
// where the function F is defined as the exclusive-or sum of the
// first c iterates of the underlying pseudorandom function PRF
// applied to the password P and the concatenation of the salt S
// and the block index i:
//
// F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
//
// where
//
// U_1 = PRF (P, S || INT (i)) ,
// U_2 = PRF (P, U_1) ,
// ...
// U_c = PRF (P, U_{c-1}) .
//
// Here, INT (i) is a four-octet encoding of the integer i, most
// significant octet first.
//
// 4. Concatenate the blocks and extract the first dk_len octets to
// produce a derived key DK:
//
// DK = T_1 || T_2 || ... || T_l<0..r-1>
var block: u32 = 0;
while (block < blocks_count) : (block += 1) {
var prev_block: [h_len]u8 = undefined;
var new_block: [h_len]u8 = undefined;
// U_1 = PRF (P, S || INT (i))
const block_index = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
var ctx = Prf.init(password);
ctx.update(salt);
ctx.update(block_index[0..]);
ctx.final(prev_block[0..]);
// Choose portion of DK to write into (T_n) and initialize
const offset = block * h_len;
const block_len = if (block != blocks_count - 1) h_len else r;
const dk_block: []u8 = dk[offset..][0..block_len];
mem.copy(u8, dk_block, prev_block[0..dk_block.len]);
var i: u32 = 1;
while (i < rounds) : (i += 1) {
// U_c = PRF (P, U_{c-1})
Prf.create(&new_block, prev_block[0..], password);
mem.copy(u8, prev_block[0..], new_block[0..]);
// F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
for (dk_block, 0..) |_, j| {
dk_block[j] ^= new_block[j];
}
}
}
}
const htest = @import("test.zig");
const HmacSha1 = std.crypto.auth.hmac.HmacSha1;
// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors
test "RFC 6070 one iteration" {
const p = "password";
const s = "salt";
const c = 1;
const dk_len = 20;
var dk: [dk_len]u8 = undefined;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 two iterations" {
const p = "password";
const s = "salt";
const c = 2;
const dk_len = 20;
var dk: [dk_len]u8 = undefined;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 4096 iterations" {
const p = "password";
const s = "salt";
const c = 4096;
const dk_len = 20;
var dk: [dk_len]u8 = undefined;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "4b007901b765489abead49d926f721d065a429c1";
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 16,777,216 iterations" {
// These iteration tests are slow so we always skip them. Results have been verified.
if (true) {
return error.SkipZigTest;
}
const p = "password";
const s = "salt";
const c = 16777216;
const dk_len = 20;
var dk = [_]u8{0} ** dk_len;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 multi-block salt and password" {
const p = "passwordPASSWORDpassword";
const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";
const c = 4096;
const dk_len = 25;
var dk: [dk_len]u8 = undefined;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 embedded NUL" {
const p = "pass\x00word";
const s = "sa\x00lt";
const c = 4096;
const dk_len = 16;
var dk: [dk_len]u8 = undefined;
try pbkdf2(&dk, p, s, c, HmacSha1);
const expected = "56fa6aa75548099dcc37d7f03425e0c3";
try htest.assertEqual(expected, dk[0..]);
}
test "Very large dk_len" {
// This test allocates 8GB of memory and is expected to take several hours to run.
if (true) {
return error.SkipZigTest;
}
const p = "password";
const s = "salt";
const c = 1;
const dk_len = 1 << 33;
var dk = try std.testing.allocator.alloc(u8, dk_len);
defer {
std.testing.allocator.free(dk);
}
// Just verify this doesn't crash with an overflow
try pbkdf2(dk, p, s, c, HmacSha1);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/md5.zig | const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const RoundParam = struct {
a: usize,
b: usize,
c: usize,
d: usize,
k: usize,
s: u32,
t: u32,
};
fn roundParam(a: usize, b: usize, c: usize, d: usize, k: usize, s: u32, t: u32) RoundParam {
return RoundParam{
.a = a,
.b = b,
.c = c,
.d = d,
.k = k,
.s = s,
.t = t,
};
}
/// The MD5 function is now considered cryptographically broken.
/// Namely, it is trivial to find multiple inputs producing the same hash.
/// For a fast-performing, cryptographically secure hash function, see SHA512/256, BLAKE2 or BLAKE3.
pub const Md5 = struct {
const Self = @This();
pub const block_length = 64;
pub const digest_length = 16;
pub const Options = struct {};
s: [4]u32,
// Streaming Cache
buf: [64]u8,
buf_len: u8,
total_len: u64,
pub fn init(options: Options) Self {
_ = options;
return Self{
.s = [_]u32{
0x67452301,
0xEFCDAB89,
0x98BADCFE,
0x10325476,
},
.buf = undefined,
.buf_len = 0,
.total_len = 0,
};
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Md5.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len >= 64) {
off += 64 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.round(&d.buf);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 64 <= b.len) : (off += 64) {
d.round(b[off..][0..64]);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
// Md5 uses the bottom 64-bits for length padding
d.total_len +%= b.len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// The buffer here will never be completely full.
mem.set(u8, d.buf[d.buf_len..], 0);
// Append padding bits.
d.buf[d.buf_len] = 0x80;
d.buf_len += 1;
// > 448 mod 512 so need to add an extra round to wrap around.
if (64 - d.buf_len < 8) {
d.round(d.buf[0..]);
mem.set(u8, d.buf[0..], 0);
}
// Append message length.
var i: usize = 1;
var len = d.total_len >> 5;
d.buf[56] = @as(u8, @intCast(d.total_len & 0x1f)) << 3;
while (i < 8) : (i += 1) {
d.buf[56 + i] = @as(u8, @intCast(len & 0xff));
len >>= 8;
}
d.round(d.buf[0..]);
for (d.s, 0..) |s, j| {
mem.writeIntLittle(u32, out[4 * j ..][0..4], s);
}
}
fn round(d: *Self, b: *const [64]u8) void {
var s: [16]u32 = undefined;
var i: usize = 0;
while (i < 16) : (i += 1) {
// NOTE: Performing or's separately improves perf by ~10%
s[i] = 0;
s[i] |= @as(u32, b[i * 4 + 0]);
s[i] |= @as(u32, b[i * 4 + 1]) << 8;
s[i] |= @as(u32, b[i * 4 + 2]) << 16;
s[i] |= @as(u32, b[i * 4 + 3]) << 24;
}
var v: [4]u32 = [_]u32{
d.s[0],
d.s[1],
d.s[2],
d.s[3],
};
const round0 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 0, 7, 0xD76AA478),
roundParam(3, 0, 1, 2, 1, 12, 0xE8C7B756),
roundParam(2, 3, 0, 1, 2, 17, 0x242070DB),
roundParam(1, 2, 3, 0, 3, 22, 0xC1BDCEEE),
roundParam(0, 1, 2, 3, 4, 7, 0xF57C0FAF),
roundParam(3, 0, 1, 2, 5, 12, 0x4787C62A),
roundParam(2, 3, 0, 1, 6, 17, 0xA8304613),
roundParam(1, 2, 3, 0, 7, 22, 0xFD469501),
roundParam(0, 1, 2, 3, 8, 7, 0x698098D8),
roundParam(3, 0, 1, 2, 9, 12, 0x8B44F7AF),
roundParam(2, 3, 0, 1, 10, 17, 0xFFFF5BB1),
roundParam(1, 2, 3, 0, 11, 22, 0x895CD7BE),
roundParam(0, 1, 2, 3, 12, 7, 0x6B901122),
roundParam(3, 0, 1, 2, 13, 12, 0xFD987193),
roundParam(2, 3, 0, 1, 14, 17, 0xA679438E),
roundParam(1, 2, 3, 0, 15, 22, 0x49B40821),
};
inline for (round0) |r| {
v[r.a] = v[r.a] +% (v[r.d] ^ (v[r.b] & (v[r.c] ^ v[r.d]))) +% r.t +% s[r.k];
v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s);
}
const round1 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 1, 5, 0xF61E2562),
roundParam(3, 0, 1, 2, 6, 9, 0xC040B340),
roundParam(2, 3, 0, 1, 11, 14, 0x265E5A51),
roundParam(1, 2, 3, 0, 0, 20, 0xE9B6C7AA),
roundParam(0, 1, 2, 3, 5, 5, 0xD62F105D),
roundParam(3, 0, 1, 2, 10, 9, 0x02441453),
roundParam(2, 3, 0, 1, 15, 14, 0xD8A1E681),
roundParam(1, 2, 3, 0, 4, 20, 0xE7D3FBC8),
roundParam(0, 1, 2, 3, 9, 5, 0x21E1CDE6),
roundParam(3, 0, 1, 2, 14, 9, 0xC33707D6),
roundParam(2, 3, 0, 1, 3, 14, 0xF4D50D87),
roundParam(1, 2, 3, 0, 8, 20, 0x455A14ED),
roundParam(0, 1, 2, 3, 13, 5, 0xA9E3E905),
roundParam(3, 0, 1, 2, 2, 9, 0xFCEFA3F8),
roundParam(2, 3, 0, 1, 7, 14, 0x676F02D9),
roundParam(1, 2, 3, 0, 12, 20, 0x8D2A4C8A),
};
inline for (round1) |r| {
v[r.a] = v[r.a] +% (v[r.c] ^ (v[r.d] & (v[r.b] ^ v[r.c]))) +% r.t +% s[r.k];
v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s);
}
const round2 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 5, 4, 0xFFFA3942),
roundParam(3, 0, 1, 2, 8, 11, 0x8771F681),
roundParam(2, 3, 0, 1, 11, 16, 0x6D9D6122),
roundParam(1, 2, 3, 0, 14, 23, 0xFDE5380C),
roundParam(0, 1, 2, 3, 1, 4, 0xA4BEEA44),
roundParam(3, 0, 1, 2, 4, 11, 0x4BDECFA9),
roundParam(2, 3, 0, 1, 7, 16, 0xF6BB4B60),
roundParam(1, 2, 3, 0, 10, 23, 0xBEBFBC70),
roundParam(0, 1, 2, 3, 13, 4, 0x289B7EC6),
roundParam(3, 0, 1, 2, 0, 11, 0xEAA127FA),
roundParam(2, 3, 0, 1, 3, 16, 0xD4EF3085),
roundParam(1, 2, 3, 0, 6, 23, 0x04881D05),
roundParam(0, 1, 2, 3, 9, 4, 0xD9D4D039),
roundParam(3, 0, 1, 2, 12, 11, 0xE6DB99E5),
roundParam(2, 3, 0, 1, 15, 16, 0x1FA27CF8),
roundParam(1, 2, 3, 0, 2, 23, 0xC4AC5665),
};
inline for (round2) |r| {
v[r.a] = v[r.a] +% (v[r.b] ^ v[r.c] ^ v[r.d]) +% r.t +% s[r.k];
v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s);
}
const round3 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 0, 6, 0xF4292244),
roundParam(3, 0, 1, 2, 7, 10, 0x432AFF97),
roundParam(2, 3, 0, 1, 14, 15, 0xAB9423A7),
roundParam(1, 2, 3, 0, 5, 21, 0xFC93A039),
roundParam(0, 1, 2, 3, 12, 6, 0x655B59C3),
roundParam(3, 0, 1, 2, 3, 10, 0x8F0CCC92),
roundParam(2, 3, 0, 1, 10, 15, 0xFFEFF47D),
roundParam(1, 2, 3, 0, 1, 21, 0x85845DD1),
roundParam(0, 1, 2, 3, 8, 6, 0x6FA87E4F),
roundParam(3, 0, 1, 2, 15, 10, 0xFE2CE6E0),
roundParam(2, 3, 0, 1, 6, 15, 0xA3014314),
roundParam(1, 2, 3, 0, 13, 21, 0x4E0811A1),
roundParam(0, 1, 2, 3, 4, 6, 0xF7537E82),
roundParam(3, 0, 1, 2, 11, 10, 0xBD3AF235),
roundParam(2, 3, 0, 1, 2, 15, 0x2AD7D2BB),
roundParam(1, 2, 3, 0, 9, 21, 0xEB86D391),
};
inline for (round3) |r| {
v[r.a] = v[r.a] +% (v[r.c] ^ (v[r.b] | ~v[r.d])) +% r.t +% s[r.k];
v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s);
}
d.s[0] +%= v[0];
d.s[1] +%= v[1];
d.s[2] +%= v[2];
d.s[3] +%= v[3];
}
};
const htest = @import("test.zig");
test "md5 single" {
try htest.assertEqualHash(Md5, "d41d8cd98f00b204e9800998ecf8427e", "");
try htest.assertEqualHash(Md5, "0cc175b9c0f1b6a831c399e269772661", "a");
try htest.assertEqualHash(Md5, "900150983cd24fb0d6963f7d28e17f72", "abc");
try htest.assertEqualHash(Md5, "f96b697d7cb7938d525a2f31aaf161d0", "message digest");
try htest.assertEqualHash(Md5, "c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz");
try htest.assertEqualHash(Md5, "d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
try htest.assertEqualHash(Md5, "57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890123456789012345678901234567890123456789012345678901234567890");
}
test "md5 streaming" {
var h = Md5.init(.{});
var out: [16]u8 = undefined;
h.final(out[0..]);
try htest.assertEqual("d41d8cd98f00b204e9800998ecf8427e", out[0..]);
h = Md5.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
h = Md5.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
}
test "md5 aligned final" {
var block = [_]u8{0} ** Md5.block_length;
var out: [Md5.digest_length]u8 = undefined;
var h = Md5.init(.{});
h.update(&block);
h.final(out[0..]);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/blake3.zig | // Translated from BLAKE3 reference implementation.
// Source: https://github.com/BLAKE3-team/BLAKE3
const std = @import("../std.zig");
const builtin = @import("builtin");
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const Vector = std.meta.Vector;
const ChunkIterator = struct {
slice: []u8,
chunk_len: usize,
fn init(slice: []u8, chunk_len: usize) ChunkIterator {
return ChunkIterator{
.slice = slice,
.chunk_len = chunk_len,
};
}
fn next(self: *ChunkIterator) ?[]u8 {
const next_chunk = self.slice[0..math.min(self.chunk_len, self.slice.len)];
self.slice = self.slice[next_chunk.len..];
return if (next_chunk.len > 0) next_chunk else null;
}
};
const OUT_LEN: usize = 32;
const KEY_LEN: usize = 32;
const BLOCK_LEN: usize = 64;
const CHUNK_LEN: usize = 1024;
const IV = [8]u32{
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
};
const MSG_SCHEDULE = [7][16]u8{
[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
[_]u8{ 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8 },
[_]u8{ 3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1 },
[_]u8{ 10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6 },
[_]u8{ 12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4 },
[_]u8{ 9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7 },
[_]u8{ 11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13 },
};
// These are the internal flags that we use to domain separate root/non-root,
// chunk/parent, and chunk beginning/middle/end. These get set at the high end
// of the block flags word in the compression function, so their values start
// high and go down.
const CHUNK_START: u8 = 1 << 0;
const CHUNK_END: u8 = 1 << 1;
const PARENT: u8 = 1 << 2;
const ROOT: u8 = 1 << 3;
const KEYED_HASH: u8 = 1 << 4;
const DERIVE_KEY_CONTEXT: u8 = 1 << 5;
const DERIVE_KEY_MATERIAL: u8 = 1 << 6;
const CompressVectorized = struct {
const Lane = Vector(4, u32);
const Rows = [4]Lane;
inline fn g(comptime even: bool, rows: *Rows, m: Lane) void {
rows[0] +%= rows[1] +% m;
rows[3] ^= rows[0];
rows[3] = math.rotr(Lane, rows[3], if (even) 8 else 16);
rows[2] +%= rows[3];
rows[1] ^= rows[2];
rows[1] = math.rotr(Lane, rows[1], if (even) 7 else 12);
}
inline fn diagonalize(rows: *Rows) void {
rows[0] = @shuffle(u32, rows[0], undefined, [_]i32{ 3, 0, 1, 2 });
rows[3] = @shuffle(u32, rows[3], undefined, [_]i32{ 2, 3, 0, 1 });
rows[2] = @shuffle(u32, rows[2], undefined, [_]i32{ 1, 2, 3, 0 });
}
inline fn undiagonalize(rows: *Rows) void {
rows[0] = @shuffle(u32, rows[0], undefined, [_]i32{ 1, 2, 3, 0 });
rows[3] = @shuffle(u32, rows[3], undefined, [_]i32{ 2, 3, 0, 1 });
rows[2] = @shuffle(u32, rows[2], undefined, [_]i32{ 3, 0, 1, 2 });
}
fn compress(
chaining_value: [8]u32,
block_words: [16]u32,
block_len: u32,
counter: u64,
flags: u8,
) [16]u32 {
const md = Lane{ @as(u32, @truncate(counter)), @as(u32, @truncate(counter >> 32)), block_len, @as(u32, flags) };
var rows = Rows{ chaining_value[0..4].*, chaining_value[4..8].*, IV[0..4].*, md };
var m = Rows{ block_words[0..4].*, block_words[4..8].*, block_words[8..12].*, block_words[12..16].* };
var t0 = @shuffle(u32, m[0], m[1], [_]i32{ 0, 2, (-1 - 0), (-1 - 2) });
g(false, &rows, t0);
var t1 = @shuffle(u32, m[0], m[1], [_]i32{ 1, 3, (-1 - 1), (-1 - 3) });
g(true, &rows, t1);
diagonalize(&rows);
var t2 = @shuffle(u32, m[2], m[3], [_]i32{ 0, 2, (-1 - 0), (-1 - 2) });
t2 = @shuffle(u32, t2, undefined, [_]i32{ 3, 0, 1, 2 });
g(false, &rows, t2);
var t3 = @shuffle(u32, m[2], m[3], [_]i32{ 1, 3, (-1 - 1), (-1 - 3) });
t3 = @shuffle(u32, t3, undefined, [_]i32{ 3, 0, 1, 2 });
g(true, &rows, t3);
undiagonalize(&rows);
m = Rows{ t0, t1, t2, t3 };
var i: usize = 0;
while (i < 6) : (i += 1) {
t0 = @shuffle(u32, m[0], m[1], [_]i32{ 2, 1, (-1 - 1), (-1 - 3) });
t0 = @shuffle(u32, t0, undefined, [_]i32{ 1, 2, 3, 0 });
g(false, &rows, t0);
t1 = @shuffle(u32, m[2], m[3], [_]i32{ 2, 2, (-1 - 3), (-1 - 3) });
var tt = @shuffle(u32, m[0], undefined, [_]i32{ 3, 3, 0, 0 });
t1 = @shuffle(u32, tt, t1, [_]i32{ 0, (-1 - 1), 2, (-1 - 3) });
g(true, &rows, t1);
diagonalize(&rows);
t2 = @shuffle(u32, m[3], m[1], [_]i32{ 0, 1, (-1 - 0), (-1 - 1) });
tt = @shuffle(u32, t2, m[2], [_]i32{ 0, 1, 2, (-1 - 3) });
t2 = @shuffle(u32, tt, undefined, [_]i32{ 0, 2, 3, 1 });
g(false, &rows, t2);
t3 = @shuffle(u32, m[1], m[3], [_]i32{ 2, (-1 - 2), 3, (-1 - 3) });
tt = @shuffle(u32, m[2], t3, [_]i32{ 0, (-1 - 0), 1, (-1 - 1) });
t3 = @shuffle(u32, tt, undefined, [_]i32{ 2, 3, 1, 0 });
g(true, &rows, t3);
undiagonalize(&rows);
m = Rows{ t0, t1, t2, t3 };
}
rows[0] ^= rows[2];
rows[1] ^= rows[3];
rows[2] ^= Vector(4, u32){ chaining_value[0], chaining_value[1], chaining_value[2], chaining_value[3] };
rows[3] ^= Vector(4, u32){ chaining_value[4], chaining_value[5], chaining_value[6], chaining_value[7] };
return @as([16]u32, @bitCast(rows));
}
};
const CompressGeneric = struct {
fn g(state: *[16]u32, comptime a: usize, comptime b: usize, comptime c: usize, comptime d: usize, mx: u32, my: u32) void {
state[a] +%= state[b] +% mx;
state[d] = math.rotr(u32, state[d] ^ state[a], 16);
state[c] +%= state[d];
state[b] = math.rotr(u32, state[b] ^ state[c], 12);
state[a] +%= state[b] +% my;
state[d] = math.rotr(u32, state[d] ^ state[a], 8);
state[c] +%= state[d];
state[b] = math.rotr(u32, state[b] ^ state[c], 7);
}
fn round(state: *[16]u32, msg: [16]u32, schedule: [16]u8) void {
// Mix the columns.
g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);
g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]);
g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]);
g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]);
// Mix the diagonals.
g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]);
g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]);
g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]);
g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]);
}
fn compress(
chaining_value: [8]u32,
block_words: [16]u32,
block_len: u32,
counter: u64,
flags: u8,
) [16]u32 {
var state = [16]u32{
chaining_value[0],
chaining_value[1],
chaining_value[2],
chaining_value[3],
chaining_value[4],
chaining_value[5],
chaining_value[6],
chaining_value[7],
IV[0],
IV[1],
IV[2],
IV[3],
@as(u32, @truncate(counter)),
@as(u32, @truncate(counter >> 32)),
block_len,
flags,
};
for (MSG_SCHEDULE) |schedule| {
round(&state, block_words, schedule);
}
for (chaining_value, 0..) |_, i| {
state[i] ^= state[i + 8];
state[i + 8] ^= chaining_value[i];
}
return state;
}
};
const compress = if (builtin.cpu.arch == .x86_64) CompressVectorized.compress else CompressGeneric.compress;
fn first8Words(words: [16]u32) [8]u32 {
return @as(*const [8]u32, @ptrCast(&words)).*;
}
fn wordsFromLittleEndianBytes(comptime count: usize, bytes: [count * 4]u8) [count]u32 {
var words: [count]u32 = undefined;
for (words, 0..) |*word, i| {
word.* = mem.readIntSliceLittle(u32, bytes[4 * i ..]);
}
return words;
}
// Each chunk or parent node can produce either an 8-word chaining value or, by
// setting the ROOT flag, any number of final output bytes. The Output struct
// captures the state just prior to choosing between those two possibilities.
const Output = struct {
input_chaining_value: [8]u32 align(16),
block_words: [16]u32 align(16),
block_len: u32,
counter: u64,
flags: u8,
fn chainingValue(self: *const Output) [8]u32 {
return first8Words(compress(
self.input_chaining_value,
self.block_words,
self.block_len,
self.counter,
self.flags,
));
}
fn rootOutputBytes(self: *const Output, output: []u8) void {
var out_block_it = ChunkIterator.init(output, 2 * OUT_LEN);
var output_block_counter: usize = 0;
while (out_block_it.next()) |out_block| {
var words = compress(
self.input_chaining_value,
self.block_words,
self.block_len,
output_block_counter,
self.flags | ROOT,
);
var out_word_it = ChunkIterator.init(out_block, 4);
var word_counter: usize = 0;
while (out_word_it.next()) |out_word| {
var word_bytes: [4]u8 = undefined;
mem.writeIntLittle(u32, &word_bytes, words[word_counter]);
mem.copy(u8, out_word, word_bytes[0..out_word.len]);
word_counter += 1;
}
output_block_counter += 1;
}
}
};
const ChunkState = struct {
chaining_value: [8]u32 align(16),
chunk_counter: u64,
block: [BLOCK_LEN]u8 align(16) = [_]u8{0} ** BLOCK_LEN,
block_len: u8 = 0,
blocks_compressed: u8 = 0,
flags: u8,
fn init(key: [8]u32, chunk_counter: u64, flags: u8) ChunkState {
return ChunkState{
.chaining_value = key,
.chunk_counter = chunk_counter,
.flags = flags,
};
}
fn len(self: *const ChunkState) usize {
return BLOCK_LEN * @as(usize, self.blocks_compressed) + @as(usize, self.block_len);
}
fn fillBlockBuf(self: *ChunkState, input: []const u8) []const u8 {
const want = BLOCK_LEN - self.block_len;
const take = math.min(want, input.len);
mem.copy(u8, self.block[self.block_len..][0..take], input[0..take]);
self.block_len += @as(u8, @truncate(take));
return input[take..];
}
fn startFlag(self: *const ChunkState) u8 {
return if (self.blocks_compressed == 0) CHUNK_START else 0;
}
fn update(self: *ChunkState, input_slice: []const u8) void {
var input = input_slice;
while (input.len > 0) {
// If the block buffer is full, compress it and clear it. More
// input is coming, so this compression is not CHUNK_END.
if (self.block_len == BLOCK_LEN) {
const block_words = wordsFromLittleEndianBytes(16, self.block);
self.chaining_value = first8Words(compress(
self.chaining_value,
block_words,
BLOCK_LEN,
self.chunk_counter,
self.flags | self.startFlag(),
));
self.blocks_compressed += 1;
self.block = [_]u8{0} ** BLOCK_LEN;
self.block_len = 0;
}
// Copy input bytes into the block buffer.
input = self.fillBlockBuf(input);
}
}
fn output(self: *const ChunkState) Output {
const block_words = wordsFromLittleEndianBytes(16, self.block);
return Output{
.input_chaining_value = self.chaining_value,
.block_words = block_words,
.block_len = self.block_len,
.counter = self.chunk_counter,
.flags = self.flags | self.startFlag() | CHUNK_END,
};
}
};
fn parentOutput(
left_child_cv: [8]u32,
right_child_cv: [8]u32,
key: [8]u32,
flags: u8,
) Output {
var block_words: [16]u32 align(16) = undefined;
mem.copy(u32, block_words[0..8], left_child_cv[0..]);
mem.copy(u32, block_words[8..], right_child_cv[0..]);
return Output{
.input_chaining_value = key,
.block_words = block_words,
.block_len = BLOCK_LEN, // Always BLOCK_LEN (64) for parent nodes.
.counter = 0, // Always 0 for parent nodes.
.flags = PARENT | flags,
};
}
fn parentCv(
left_child_cv: [8]u32,
right_child_cv: [8]u32,
key: [8]u32,
flags: u8,
) [8]u32 {
return parentOutput(left_child_cv, right_child_cv, key, flags).chainingValue();
}
/// An incremental hasher that can accept any number of writes.
pub const Blake3 = struct {
pub const Options = struct { key: ?[digest_length]u8 = null };
pub const KdfOptions = struct {};
chunk_state: ChunkState,
key: [8]u32,
cv_stack: [54][8]u32 = undefined, // Space for 54 subtree chaining values:
cv_stack_len: u8 = 0, // 2^54 * CHUNK_LEN = 2^64
flags: u8,
pub const block_length = BLOCK_LEN;
pub const digest_length = OUT_LEN;
pub const key_length = KEY_LEN;
fn init_internal(key: [8]u32, flags: u8) Blake3 {
return Blake3{
.chunk_state = ChunkState.init(key, 0, flags),
.key = key,
.flags = flags,
};
}
/// Construct a new `Blake3` for the hash function, with an optional key
pub fn init(options: Options) Blake3 {
if (options.key) |key| {
const key_words = wordsFromLittleEndianBytes(8, key);
return Blake3.init_internal(key_words, KEYED_HASH);
} else {
return Blake3.init_internal(IV, 0);
}
}
/// Construct a new `Blake3` for the key derivation function. The context
/// string should be hardcoded, globally unique, and application-specific.
pub fn initKdf(context: []const u8, options: KdfOptions) Blake3 {
_ = options;
var context_hasher = Blake3.init_internal(IV, DERIVE_KEY_CONTEXT);
context_hasher.update(context);
var context_key: [KEY_LEN]u8 = undefined;
context_hasher.final(context_key[0..]);
const context_key_words = wordsFromLittleEndianBytes(8, context_key);
return Blake3.init_internal(context_key_words, DERIVE_KEY_MATERIAL);
}
pub fn hash(b: []const u8, out: []u8, options: Options) void {
var d = Blake3.init(options);
d.update(b);
d.final(out);
}
fn pushCv(self: *Blake3, cv: [8]u32) void {
self.cv_stack[self.cv_stack_len] = cv;
self.cv_stack_len += 1;
}
fn popCv(self: *Blake3) [8]u32 {
self.cv_stack_len -= 1;
return self.cv_stack[self.cv_stack_len];
}
// Section 5.1.2 of the BLAKE3 spec explains this algorithm in more detail.
fn addChunkChainingValue(self: *Blake3, first_cv: [8]u32, total_chunks: u64) void {
// This chunk might complete some subtrees. For each completed subtree,
// its left child will be the current top entry in the CV stack, and
// its right child will be the current value of `new_cv`. Pop each left
// child off the stack, merge it with `new_cv`, and overwrite `new_cv`
// with the result. After all these merges, push the final value of
// `new_cv` onto the stack. The number of completed subtrees is given
// by the number of trailing 0-bits in the new total number of chunks.
var new_cv = first_cv;
var chunk_counter = total_chunks;
while (chunk_counter & 1 == 0) {
new_cv = parentCv(self.popCv(), new_cv, self.key, self.flags);
chunk_counter >>= 1;
}
self.pushCv(new_cv);
}
/// Add input to the hash state. This can be called any number of times.
pub fn update(self: *Blake3, input_slice: []const u8) void {
var input = input_slice;
while (input.len > 0) {
// If the current chunk is complete, finalize it and reset the
// chunk state. More input is coming, so this chunk is not ROOT.
if (self.chunk_state.len() == CHUNK_LEN) {
const chunk_cv = self.chunk_state.output().chainingValue();
const total_chunks = self.chunk_state.chunk_counter + 1;
self.addChunkChainingValue(chunk_cv, total_chunks);
self.chunk_state = ChunkState.init(self.key, total_chunks, self.flags);
}
// Compress input bytes into the current chunk state.
const want = CHUNK_LEN - self.chunk_state.len();
const take = math.min(want, input.len);
self.chunk_state.update(input[0..take]);
input = input[take..];
}
}
/// Finalize the hash and write any number of output bytes.
pub fn final(self: *const Blake3, out_slice: []u8) void {
// Starting with the Output from the current chunk, compute all the
// parent chaining values along the right edge of the tree, until we
// have the root Output.
var output = self.chunk_state.output();
var parent_nodes_remaining: usize = self.cv_stack_len;
while (parent_nodes_remaining > 0) {
parent_nodes_remaining -= 1;
output = parentOutput(
self.cv_stack[parent_nodes_remaining],
output.chainingValue(),
self.key,
self.flags,
);
}
output.rootOutputBytes(out_slice);
}
};
// Use named type declarations to workaround crash with anonymous structs (issue #4373).
const ReferenceTest = struct {
key: *const [KEY_LEN]u8,
context_string: []const u8,
cases: []const ReferenceTestCase,
};
const ReferenceTestCase = struct {
input_len: usize,
hash: *const [262]u8,
keyed_hash: *const [262]u8,
derive_key: *const [262]u8,
};
// Each test is an input length and three outputs, one for each of the `hash`, `keyed_hash`, and
// `derive_key` modes. The input in each case is filled with a 251-byte-long repeating pattern:
// 0, 1, 2, ..., 249, 250, 0, 1, ... The key used with `keyed_hash` is the 32-byte ASCII string
// given in the `key` field below. For `derive_key`, the test input is used as the input key, and
// the context string is 'BLAKE3 2019-12-27 16:29:52 test vectors context'. (As good practice for
// following the security requirements of `derive_key`, test runners should make that context
// string a hardcoded constant, and we do not provided it in machine-readable form.) Outputs are
// encoded as hexadecimal. Each case is an extended output, and implementations should also check
// that the first 32 bytes match their default-length output.
//
// Source: https://github.com/BLAKE3-team/BLAKE3/blob/92d421dea1a89e2f079f4dbd93b0dab41234b279/test_vectors/test_vectors.json
const reference_test = ReferenceTest{
.key = "whats the Elvish word for friend",
.context_string = "BLAKE3 2019-12-27 16:29:52 test vectors context",
.cases = &[_]ReferenceTestCase{
.{
.input_len = 0,
.hash = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262e00f03e7b69af26b7faaf09fcd333050338ddfe085b8cc869ca98b206c08243a26f5487789e8f660afe6c99ef9e0c52b92e7393024a80459cf91f476f9ffdbda7001c22e159b402631f277ca96f2defdf1078282314e763699a31c5363165421cce14d",
.keyed_hash = "92b2b75604ed3c761f9d6f62392c8a9227ad0ea3f09573e783f1498a4ed60d26b18171a2f22a4b94822c701f107153dba24918c4bae4d2945c20ece13387627d3b73cbf97b797d5e59948c7ef788f54372df45e45e4293c7dc18c1d41144a9758be58960856be1eabbe22c2653190de560ca3b2ac4aa692a9210694254c371e851bc8f",
.derive_key = "2cc39783c223154fea8dfb7c1b1660f2ac2dcbd1c1de8277b0b0dd39b7e50d7d905630c8be290dfcf3e6842f13bddd573c098c3f17361f1f206b8cad9d088aa4a3f746752c6b0ce6a83b0da81d59649257cdf8eb3e9f7d4998e41021fac119deefb896224ac99f860011f73609e6e0e4540f93b273e56547dfd3aa1a035ba6689d89a0",
},
.{
.input_len = 1,
.hash = "2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213c3a6cb8bf623e20cdb535f8d1a5ffb86342d9c0b64aca3bce1d31f60adfa137b358ad4d79f97b47c3d5e79f179df87a3b9776ef8325f8329886ba42f07fb138bb502f4081cbcec3195c5871e6c23e2cc97d3c69a613eba131e5f1351f3f1da786545e5",
.keyed_hash = "6d7878dfff2f485635d39013278ae14f1454b8c0a3a2d34bc1ab38228a80c95b6568c0490609413006fbd428eb3fd14e7756d90f73a4725fad147f7bf70fd61c4e0cf7074885e92b0e3f125978b4154986d4fb202a3f331a3fb6cf349a3a70e49990f98fe4289761c8602c4e6ab1138d31d3b62218078b2f3ba9a88e1d08d0dd4cea11",
.derive_key = "b3e2e340a117a499c6cf2398a19ee0d29cca2bb7404c73063382693bf66cb06c5827b91bf889b6b97c5477f535361caefca0b5d8c4746441c57617111933158950670f9aa8a05d791daae10ac683cbef8faf897c84e6114a59d2173c3f417023a35d6983f2c7dfa57e7fc559ad751dbfb9ffab39c2ef8c4aafebc9ae973a64f0c76551",
},
.{
.input_len = 1023,
.hash = "10108970eeda3eb932baac1428c7a2163b0e924c9a9e25b35bba72b28f70bd11a182d27a591b05592b15607500e1e8dd56bc6c7fc063715b7a1d737df5bad3339c56778957d870eb9717b57ea3d9fb68d1b55127bba6a906a4a24bbd5acb2d123a37b28f9e9a81bbaae360d58f85e5fc9d75f7c370a0cc09b6522d9c8d822f2f28f485",
.keyed_hash = "c951ecdf03288d0fcc96ee3413563d8a6d3589547f2c2fb36d9786470f1b9d6e890316d2e6d8b8c25b0a5b2180f94fb1a158ef508c3cde45e2966bd796a696d3e13efd86259d756387d9becf5c8bf1ce2192b87025152907b6d8cc33d17826d8b7b9bc97e38c3c85108ef09f013e01c229c20a83d9e8efac5b37470da28575fd755a10",
.derive_key = "74a16c1c3d44368a86e1ca6df64be6a2f64cce8f09220787450722d85725dea59c413264404661e9e4d955409dfe4ad3aa487871bcd454ed12abfe2c2b1eb7757588cf6cb18d2eccad49e018c0d0fec323bec82bf1644c6325717d13ea712e6840d3e6e730d35553f59eff5377a9c350bcc1556694b924b858f329c44ee64b884ef00d",
},
.{
.input_len = 1024,
.hash = "42214739f095a406f3fc83deb889744ac00df831c10daa55189b5d121c855af71cf8107265ecdaf8505b95d8fcec83a98a6a96ea5109d2c179c47a387ffbb404756f6eeae7883b446b70ebb144527c2075ab8ab204c0086bb22b7c93d465efc57f8d917f0b385c6df265e77003b85102967486ed57db5c5ca170ba441427ed9afa684e",
.keyed_hash = "75c46f6f3d9eb4f55ecaaee480db732e6c2105546f1e675003687c31719c7ba4a78bc838c72852d4f49c864acb7adafe2478e824afe51c8919d06168414c265f298a8094b1ad813a9b8614acabac321f24ce61c5a5346eb519520d38ecc43e89b5000236df0597243e4d2493fd626730e2ba17ac4d8824d09d1a4a8f57b8227778e2de",
.derive_key = "7356cd7720d5b66b6d0697eb3177d9f8d73a4a5c5e968896eb6a6896843027066c23b601d3ddfb391e90d5c8eccdef4ae2a264bce9e612ba15e2bc9d654af1481b2e75dbabe615974f1070bba84d56853265a34330b4766f8e75edd1f4a1650476c10802f22b64bd3919d246ba20a17558bc51c199efdec67e80a227251808d8ce5bad",
},
.{
.input_len = 1025,
.hash = "d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444f4c4a22b4b399155358a994e52bf255de60035742ec71bd08ac275a1b51cc6bfe332b0ef84b409108cda080e6269ed4b3e2c3f7d722aa4cdc98d16deb554e5627be8f955c98e1d5f9565a9194cad0c4285f93700062d9595adb992ae68ff12800ab67a",
.keyed_hash = "357dc55de0c7e382c900fd6e320acc04146be01db6a8ce7210b7189bd664ea69362396b77fdc0d2634a552970843722066c3c15902ae5097e00ff53f1e116f1cd5352720113a837ab2452cafbde4d54085d9cf5d21ca613071551b25d52e69d6c81123872b6f19cd3bc1333edf0c52b94de23ba772cf82636cff4542540a7738d5b930",
.derive_key = "effaa245f065fbf82ac186839a249707c3bddf6d3fdda22d1b95a3c970379bcb5d31013a167509e9066273ab6e2123bc835b408b067d88f96addb550d96b6852dad38e320b9d940f86db74d398c770f462118b35d2724efa13da97194491d96dd37c3c09cbef665953f2ee85ec83d88b88d11547a6f911c8217cca46defa2751e7f3ad",
},
.{
.input_len = 2048,
.hash = "e776b6028c7cd22a4d0ba182a8bf62205d2ef576467e838ed6f2529b85fba24a9a60bf80001410ec9eea6698cd537939fad4749edd484cb541aced55cd9bf54764d063f23f6f1e32e12958ba5cfeb1bf618ad094266d4fc3c968c2088f677454c288c67ba0dba337b9d91c7e1ba586dc9a5bc2d5e90c14f53a8863ac75655461cea8f9",
.keyed_hash = "879cf1fa2ea0e79126cb1063617a05b6ad9d0b696d0d757cf053439f60a99dd10173b961cd574288194b23ece278c330fbb8585485e74967f31352a8183aa782b2b22f26cdcadb61eed1a5bc144b8198fbb0c13abbf8e3192c145d0a5c21633b0ef86054f42809df823389ee40811a5910dcbd1018af31c3b43aa55201ed4edaac74fe",
.derive_key = "7b2945cb4fef70885cc5d78a87bf6f6207dd901ff239201351ffac04e1088a23e2c11a1ebffcea4d80447867b61badb1383d842d4e79645d48dd82ccba290769caa7af8eaa1bd78a2a5e6e94fbdab78d9c7b74e894879f6a515257ccf6f95056f4e25390f24f6b35ffbb74b766202569b1d797f2d4bd9d17524c720107f985f4ddc583",
},
.{
.input_len = 2049,
.hash = "5f4d72f40d7a5f82b15ca2b2e44b1de3c2ef86c426c95c1af0b687952256303096de31d71d74103403822a2e0bc1eb193e7aecc9643a76b7bbc0c9f9c52e8783aae98764ca468962b5c2ec92f0c74eb5448d519713e09413719431c802f948dd5d90425a4ecdadece9eb178d80f26efccae630734dff63340285adec2aed3b51073ad3",
.keyed_hash = "9f29700902f7c86e514ddc4df1e3049f258b2472b6dd5267f61bf13983b78dd5f9a88abfefdfa1e00b418971f2b39c64ca621e8eb37fceac57fd0c8fc8e117d43b81447be22d5d8186f8f5919ba6bcc6846bd7d50726c06d245672c2ad4f61702c646499ee1173daa061ffe15bf45a631e2946d616a4c345822f1151284712f76b2b0e",
.derive_key = "2ea477c5515cc3dd606512ee72bb3e0e758cfae7232826f35fb98ca1bcbdf27316d8e9e79081a80b046b60f6a263616f33ca464bd78d79fa18200d06c7fc9bffd808cc4755277a7d5e09da0f29ed150f6537ea9bed946227ff184cc66a72a5f8c1e4bd8b04e81cf40fe6dc4427ad5678311a61f4ffc39d195589bdbc670f63ae70f4b6",
},
.{
.input_len = 3072,
.hash = "b98cb0ff3623be03326b373de6b9095218513e64f1ee2edd2525c7ad1e5cffd29a3f6b0b978d6608335c09dc94ccf682f9951cdfc501bfe47b9c9189a6fc7b404d120258506341a6d802857322fbd20d3e5dae05b95c88793fa83db1cb08e7d8008d1599b6209d78336e24839724c191b2a52a80448306e0daa84a3fdb566661a37e11",
.keyed_hash = "044a0e7b172a312dc02a4c9a818c036ffa2776368d7f528268d2e6b5df19177022f302d0529e4174cc507c463671217975e81dab02b8fdeb0d7ccc7568dd22574c783a76be215441b32e91b9a904be8ea81f7a0afd14bad8ee7c8efc305ace5d3dd61b996febe8da4f56ca0919359a7533216e2999fc87ff7d8f176fbecb3d6f34278b",
.derive_key = "050df97f8c2ead654d9bb3ab8c9178edcd902a32f8495949feadcc1e0480c46b3604131bbd6e3ba573b6dd682fa0a63e5b165d39fc43a625d00207607a2bfeb65ff1d29292152e26b298868e3b87be95d6458f6f2ce6118437b632415abe6ad522874bcd79e4030a5e7bad2efa90a7a7c67e93f0a18fb28369d0a9329ab5c24134ccb0",
},
.{
.input_len = 3073,
.hash = "7124b49501012f81cc7f11ca069ec9226cecb8a2c850cfe644e327d22d3e1cd39a27ae3b79d68d89da9bf25bc27139ae65a324918a5f9b7828181e52cf373c84f35b639b7fccbb985b6f2fa56aea0c18f531203497b8bbd3a07ceb5926f1cab74d14bd66486d9a91eba99059a98bd1cd25876b2af5a76c3e9eed554ed72ea952b603bf",
.keyed_hash = "68dede9bef00ba89e43f31a6825f4cf433389fedae75c04ee9f0cf16a427c95a96d6da3fe985054d3478865be9a092250839a697bbda74e279e8a9e69f0025e4cfddd6cfb434b1cd9543aaf97c635d1b451a4386041e4bb100f5e45407cbbc24fa53ea2de3536ccb329e4eb9466ec37093a42cf62b82903c696a93a50b702c80f3c3c5",
.derive_key = "72613c9ec9ff7e40f8f5c173784c532ad852e827dba2bf85b2ab4b76f7079081576288e552647a9d86481c2cae75c2dd4e7c5195fb9ada1ef50e9c5098c249d743929191441301c69e1f48505a4305ec1778450ee48b8e69dc23a25960fe33070ea549119599760a8a2d28aeca06b8c5e9ba58bc19e11fe57b6ee98aa44b2a8e6b14a5",
},
.{
.input_len = 4096,
.hash = "015094013f57a5277b59d8475c0501042c0b642e531b0a1c8f58d2163229e9690289e9409ddb1b99768eafe1623da896faf7e1114bebeadc1be30829b6f8af707d85c298f4f0ff4d9438aef948335612ae921e76d411c3a9111df62d27eaf871959ae0062b5492a0feb98ef3ed4af277f5395172dbe5c311918ea0074ce0036454f620",
.keyed_hash = "befc660aea2f1718884cd8deb9902811d332f4fc4a38cf7c7300d597a081bfc0bbb64a36edb564e01e4b4aaf3b060092a6b838bea44afebd2deb8298fa562b7b597c757b9df4c911c3ca462e2ac89e9a787357aaf74c3b56d5c07bc93ce899568a3eb17d9250c20f6c5f6c1e792ec9a2dcb715398d5a6ec6d5c54f586a00403a1af1de",
.derive_key = "1e0d7f3db8c414c97c6307cbda6cd27ac3b030949da8e23be1a1a924ad2f25b9d78038f7b198596c6cc4a9ccf93223c08722d684f240ff6569075ed81591fd93f9fff1110b3a75bc67e426012e5588959cc5a4c192173a03c00731cf84544f65a2fb9378989f72e9694a6a394a8a30997c2e67f95a504e631cd2c5f55246024761b245",
},
.{
.input_len = 4097,
.hash = "9b4052b38f1c5fc8b1f9ff7ac7b27cd242487b3d890d15c96a1c25b8aa0fb99505f91b0b5600a11251652eacfa9497b31cd3c409ce2e45cfe6c0a016967316c426bd26f619eab5d70af9a418b845c608840390f361630bd497b1ab44019316357c61dbe091ce72fc16dc340ac3d6e009e050b3adac4b5b2c92e722cffdc46501531956",
.keyed_hash = "00df940cd36bb9fa7cbbc3556744e0dbc8191401afe70520ba292ee3ca80abbc606db4976cfdd266ae0abf667d9481831ff12e0caa268e7d3e57260c0824115a54ce595ccc897786d9dcbf495599cfd90157186a46ec800a6763f1c59e36197e9939e900809f7077c102f888caaf864b253bc41eea812656d46742e4ea42769f89b83f",
.derive_key = "aca51029626b55fda7117b42a7c211f8c6e9ba4fe5b7a8ca922f34299500ead8a897f66a400fed9198fd61dd2d58d382458e64e100128075fc54b860934e8de2e84170734b06e1d212a117100820dbc48292d148afa50567b8b84b1ec336ae10d40c8c975a624996e12de31abbe135d9d159375739c333798a80c64ae895e51e22f3ad",
},
.{
.input_len = 5120,
.hash = "9cadc15fed8b5d854562b26a9536d9707cadeda9b143978f319ab34230535833acc61c8fdc114a2010ce8038c853e121e1544985133fccdd0a2d507e8e615e611e9a0ba4f47915f49e53d721816a9198e8b30f12d20ec3689989175f1bf7a300eee0d9321fad8da232ece6efb8e9fd81b42ad161f6b9550a069e66b11b40487a5f5059",
.keyed_hash = "2c493e48e9b9bf31e0553a22b23503c0a3388f035cece68eb438d22fa1943e209b4dc9209cd80ce7c1f7c9a744658e7e288465717ae6e56d5463d4f80cdb2ef56495f6a4f5487f69749af0c34c2cdfa857f3056bf8d807336a14d7b89bf62bef2fb54f9af6a546f818dc1e98b9e07f8a5834da50fa28fb5874af91bf06020d1bf0120e",
.derive_key = "7a7acac8a02adcf3038d74cdd1d34527de8a0fcc0ee3399d1262397ce5817f6055d0cefd84d9d57fe792d65a278fd20384ac6c30fdb340092f1a74a92ace99c482b28f0fc0ef3b923e56ade20c6dba47e49227166251337d80a037e987ad3a7f728b5ab6dfafd6e2ab1bd583a95d9c895ba9c2422c24ea0f62961f0dca45cad47bfa0d",
},
.{
.input_len = 5121,
.hash = "628bd2cb2004694adaab7bbd778a25df25c47b9d4155a55f8fbd79f2fe154cff96adaab0613a6146cdaabe498c3a94e529d3fc1da2bd08edf54ed64d40dcd6777647eac51d8277d70219a9694334a68bc8f0f23e20b0ff70ada6f844542dfa32cd4204ca1846ef76d811cdb296f65e260227f477aa7aa008bac878f72257484f2b6c95",
.keyed_hash = "6ccf1c34753e7a044db80798ecd0782a8f76f33563accaddbfbb2e0ea4b2d0240d07e63f13667a8d1490e5e04f13eb617aea16a8c8a5aaed1ef6fbde1b0515e3c81050b361af6ead126032998290b563e3caddeaebfab592e155f2e161fb7cba939092133f23f9e65245e58ec23457b78a2e8a125588aad6e07d7f11a85b88d375b72d",
.derive_key = "b07f01e518e702f7ccb44a267e9e112d403a7b3f4883a47ffbed4b48339b3c341a0add0ac032ab5aaea1e4e5b004707ec5681ae0fcbe3796974c0b1cf31a194740c14519273eedaabec832e8a784b6e7cfc2c5952677e6c3f2c3914454082d7eb1ce1766ac7d75a4d3001fc89544dd46b5147382240d689bbbaefc359fb6ae30263165",
},
.{
.input_len = 6144,
.hash = "3e2e5b74e048f3add6d21faab3f83aa44d3b2278afb83b80b3c35164ebeca2054d742022da6fdda444ebc384b04a54c3ac5839b49da7d39f6d8a9db03deab32aade156c1c0311e9b3435cde0ddba0dce7b26a376cad121294b689193508dd63151603c6ddb866ad16c2ee41585d1633a2cea093bea714f4c5d6b903522045b20395c83",
.keyed_hash = "3d6b6d21281d0ade5b2b016ae4034c5dec10ca7e475f90f76eac7138e9bc8f1dc35754060091dc5caf3efabe0603c60f45e415bb3407db67e6beb3d11cf8e4f7907561f05dace0c15807f4b5f389c841eb114d81a82c02a00b57206b1d11fa6e803486b048a5ce87105a686dee041207e095323dfe172df73deb8c9532066d88f9da7e",
.derive_key = "2a95beae63ddce523762355cf4b9c1d8f131465780a391286a5d01abb5683a1597099e3c6488aab6c48f3c15dbe1942d21dbcdc12115d19a8b8465fb54e9053323a9178e4275647f1a9927f6439e52b7031a0b465c861a3fc531527f7758b2b888cf2f20582e9e2c593709c0a44f9c6e0f8b963994882ea4168827823eef1f64169fef",
},
.{
.input_len = 6145,
.hash = "f1323a8631446cc50536a9f705ee5cb619424d46887f3c376c695b70e0f0507f18a2cfdd73c6e39dd75ce7c1c6e3ef238fd54465f053b25d21044ccb2093beb015015532b108313b5829c3621ce324b8e14229091b7c93f32db2e4e63126a377d2a63a3597997d4f1cba59309cb4af240ba70cebff9a23d5e3ff0cdae2cfd54e070022",
.keyed_hash = "9ac301e9e39e45e3250a7e3b3df701aa0fb6889fbd80eeecf28dbc6300fbc539f3c184ca2f59780e27a576c1d1fb9772e99fd17881d02ac7dfd39675aca918453283ed8c3169085ef4a466b91c1649cc341dfdee60e32231fc34c9c4e0b9a2ba87ca8f372589c744c15fd6f985eec15e98136f25beeb4b13c4e43dc84abcc79cd4646c",
.derive_key = "379bcc61d0051dd489f686c13de00d5b14c505245103dc040d9e4dd1facab8e5114493d029bdbd295aaa744a59e31f35c7f52dba9c3642f773dd0b4262a9980a2aef811697e1305d37ba9d8b6d850ef07fe41108993180cf779aeece363704c76483458603bbeeb693cffbbe5588d1f3535dcad888893e53d977424bb707201569a8d2",
},
.{
.input_len = 7168,
.hash = "61da957ec2499a95d6b8023e2b0e604ec7f6b50e80a9678b89d2628e99ada77a5707c321c83361793b9af62a40f43b523df1c8633cecb4cd14d00bdc79c78fca5165b863893f6d38b02ff7236c5a9a8ad2dba87d24c547cab046c29fc5bc1ed142e1de4763613bb162a5a538e6ef05ed05199d751f9eb58d332791b8d73fb74e4fce95",
.keyed_hash = "b42835e40e9d4a7f42ad8cc04f85a963a76e18198377ed84adddeaecacc6f3fca2f01d5277d69bb681c70fa8d36094f73ec06e452c80d2ff2257ed82e7ba348400989a65ee8daa7094ae0933e3d2210ac6395c4af24f91c2b590ef87d7788d7066ea3eaebca4c08a4f14b9a27644f99084c3543711b64a070b94f2c9d1d8a90d035d52",
.derive_key = "11c37a112765370c94a51415d0d651190c288566e295d505defdad895dae223730d5a5175a38841693020669c7638f40b9bc1f9f39cf98bda7a5b54ae24218a800a2116b34665aa95d846d97ea988bfcb53dd9c055d588fa21ba78996776ea6c40bc428b53c62b5f3ccf200f647a5aae8067f0ea1976391fcc72af1945100e2a6dcb88",
},
.{
.input_len = 7169,
.hash = "a003fc7a51754a9b3c7fae0367ab3d782dccf28855a03d435f8cfe74605e781798a8b20534be1ca9eb2ae2df3fae2ea60e48c6fb0b850b1385b5de0fe460dbe9d9f9b0d8db4435da75c601156df9d047f4ede008732eb17adc05d96180f8a73548522840779e6062d643b79478a6e8dbce68927f36ebf676ffa7d72d5f68f050b119c8",
.keyed_hash = "ed9b1a922c046fdb3d423ae34e143b05ca1bf28b710432857bf738bcedbfa5113c9e28d72fcbfc020814ce3f5d4fc867f01c8f5b6caf305b3ea8a8ba2da3ab69fabcb438f19ff11f5378ad4484d75c478de425fb8e6ee809b54eec9bdb184315dc856617c09f5340451bf42fd3270a7b0b6566169f242e533777604c118a6358250f54",
.derive_key = "554b0a5efea9ef183f2f9b931b7497995d9eb26f5c5c6dad2b97d62fc5ac31d99b20652c016d88ba2a611bbd761668d5eda3e568e940faae24b0d9991c3bd25a65f770b89fdcadabcb3d1a9c1cb63e69721cacf1ae69fefdcef1e3ef41bc5312ccc17222199e47a26552c6adc460cf47a72319cb5039369d0060eaea59d6c65130f1dd",
},
.{
.input_len = 8192,
.hash = "aae792484c8efe4f19e2ca7d371d8c467ffb10748d8a5a1ae579948f718a2a635fe51a27db045a567c1ad51be5aa34c01c6651c4d9b5b5ac5d0fd58cf18dd61a47778566b797a8c67df7b1d60b97b19288d2d877bb2df417ace009dcb0241ca1257d62712b6a4043b4ff33f690d849da91ea3bf711ed583cb7b7a7da2839ba71309bbf",
.keyed_hash = "dc9637c8845a770b4cbf76b8daec0eebf7dc2eac11498517f08d44c8fc00d58a4834464159dcbc12a0ba0c6d6eb41bac0ed6585cabfe0aca36a375e6c5480c22afdc40785c170f5a6b8a1107dbee282318d00d915ac9ed1143ad40765ec120042ee121cd2baa36250c618adaf9e27260fda2f94dea8fb6f08c04f8f10c78292aa46102",
.derive_key = "ad01d7ae4ad059b0d33baa3c01319dcf8088094d0359e5fd45d6aeaa8b2d0c3d4c9e58958553513b67f84f8eac653aeeb02ae1d5672dcecf91cd9985a0e67f4501910ecba25555395427ccc7241d70dc21c190e2aadee875e5aae6bf1912837e53411dabf7a56cbf8e4fb780432b0d7fe6cec45024a0788cf5874616407757e9e6bef7",
},
.{
.input_len = 8193,
.hash = "bab6c09cb8ce8cf459261398d2e7aef35700bf488116ceb94a36d0f5f1b7bc3bb2282aa69be089359ea1154b9a9286c4a56af4de975a9aa4a5c497654914d279bea60bb6d2cf7225a2fa0ff5ef56bbe4b149f3ed15860f78b4e2ad04e158e375c1e0c0b551cd7dfc82f1b155c11b6b3ed51ec9edb30d133653bb5709d1dbd55f4e1ff6",
.keyed_hash = "954a2a75420c8d6547e3ba5b98d963e6fa6491addc8c023189cc519821b4a1f5f03228648fd983aef045c2fa8290934b0866b615f585149587dda2299039965328835a2b18f1d63b7e300fc76ff260b571839fe44876a4eae66cbac8c67694411ed7e09df51068a22c6e67d6d3dd2cca8ff12e3275384006c80f4db68023f24eebba57",
.derive_key = "af1e0346e389b17c23200270a64aa4e1ead98c61695d917de7d5b00491c9b0f12f20a01d6d622edf3de026a4db4e4526225debb93c1237934d71c7340bb5916158cbdafe9ac3225476b6ab57a12357db3abbad7a26c6e66290e44034fb08a20a8d0ec264f309994d2810c49cfba6989d7abb095897459f5425adb48aba07c5fb3c83c0",
},
.{
.input_len = 16384,
.hash = "f875d6646de28985646f34ee13be9a576fd515f76b5b0a26bb324735041ddde49d764c270176e53e97bdffa58d549073f2c660be0e81293767ed4e4929f9ad34bbb39a529334c57c4a381ffd2a6d4bfdbf1482651b172aa883cc13408fa67758a3e47503f93f87720a3177325f7823251b85275f64636a8f1d599c2e49722f42e93893",
.keyed_hash = "9e9fc4eb7cf081ea7c47d1807790ed211bfec56aa25bb7037784c13c4b707b0df9e601b101e4cf63a404dfe50f2e1865bb12edc8fca166579ce0c70dba5a5c0fc960ad6f3772183416a00bd29d4c6e651ea7620bb100c9449858bf14e1ddc9ecd35725581ca5b9160de04060045993d972571c3e8f71e9d0496bfa744656861b169d65",
.derive_key = "160e18b5878cd0df1c3af85eb25a0db5344d43a6fbd7a8ef4ed98d0714c3f7e160dc0b1f09caa35f2f417b9ef309dfe5ebd67f4c9507995a531374d099cf8ae317542e885ec6f589378864d3ea98716b3bbb65ef4ab5e0ab5bb298a501f19a41ec19af84a5e6b428ecd813b1a47ed91c9657c3fba11c406bc316768b58f6802c9e9b57",
},
.{
.input_len = 31744,
.hash = "62b6960e1a44bcc1eb1a611a8d6235b6b4b78f32e7abc4fb4c6cdcce94895c47860cc51f2b0c28a7b77304bd55fe73af663c02d3f52ea053ba43431ca5bab7bfea2f5e9d7121770d88f70ae9649ea713087d1914f7f312147e247f87eb2d4ffef0ac978bf7b6579d57d533355aa20b8b77b13fd09748728a5cc327a8ec470f4013226f",
.keyed_hash = "efa53b389ab67c593dba624d898d0f7353ab99e4ac9d42302ee64cbf9939a4193a7258db2d9cd32a7a3ecfce46144114b15c2fcb68a618a976bd74515d47be08b628be420b5e830fade7c080e351a076fbc38641ad80c736c8a18fe3c66ce12f95c61c2462a9770d60d0f77115bbcd3782b593016a4e728d4c06cee4505cb0c08a42ec",
.derive_key = "39772aef80e0ebe60596361e45b061e8f417429d529171b6764468c22928e28e9759adeb797a3fbf771b1bcea30150a020e317982bf0d6e7d14dd9f064bc11025c25f31e81bd78a921db0174f03dd481d30e93fd8e90f8b2fee209f849f2d2a52f31719a490fb0ba7aea1e09814ee912eba111a9fde9d5c274185f7bae8ba85d300a2b",
},
.{
.input_len = 102400,
.hash = "bc3e3d41a1146b069abffad3c0d44860cf664390afce4d9661f7902e7943e085e01c59dab908c04c3342b816941a26d69c2605ebee5ec5291cc55e15b76146e6745f0601156c3596cb75065a9c57f35585a52e1ac70f69131c23d611ce11ee4ab1ec2c009012d236648e77be9295dd0426f29b764d65de58eb7d01dd42248204f45f8e",
.keyed_hash = "1c35d1a5811083fd7119f5d5d1ba027b4d01c0c6c49fb6ff2cf75393ea5db4a7f9dbdd3e1d81dcbca3ba241bb18760f207710b751846faaeb9dff8262710999a59b2aa1aca298a032d94eacfadf1aa192418eb54808db23b56e34213266aa08499a16b354f018fc4967d05f8b9d2ad87a7278337be9693fc638a3bfdbe314574ee6fc4",
.derive_key = "4652cff7a3f385a6103b5c260fc1593e13c778dbe608efb092fe7ee69df6e9c6d83a3e041bc3a48df2879f4a0a3ed40e7c961c73eff740f3117a0504c2dff4786d44fb17f1549eb0ba585e40ec29bf7732f0b7e286ff8acddc4cb1e23b87ff5d824a986458dcc6a04ac83969b80637562953df51ed1a7e90a7926924d2763778be8560",
},
},
};
fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) !void {
// Save initial state
const initial_state = hasher.*;
// Setup input pattern
var input_pattern: [251]u8 = undefined;
for (input_pattern, 0..) |*e, i| e.* = @as(u8, @truncate(i));
// Write repeating input pattern to hasher
var input_counter = input_len;
while (input_counter > 0) {
const update_len = math.min(input_counter, input_pattern.len);
hasher.update(input_pattern[0..update_len]);
input_counter -= update_len;
}
// Read final hash value
var actual_bytes: [expected_hex.len / 2]u8 = undefined;
hasher.final(actual_bytes[0..]);
// Compare to expected value
var expected_bytes: [expected_hex.len / 2]u8 = undefined;
_ = fmt.hexToBytes(expected_bytes[0..], expected_hex[0..]) catch unreachable;
try testing.expectEqual(actual_bytes, expected_bytes);
// Restore initial state
hasher.* = initial_state;
}
test "BLAKE3 reference test cases" {
var hash = &Blake3.init(.{});
var keyed_hash = &Blake3.init(.{ .key = reference_test.key.* });
var derive_key = &Blake3.initKdf(reference_test.context_string, .{});
for (reference_test.cases) |t| {
try testBlake3(hash, t.input_len, t.hash.*);
try testBlake3(keyed_hash, t.input_len, t.keyed_hash.*);
try testBlake3(derive_key, t.input_len, t.derive_key.*);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/siphash.zig | //
// SipHash is a moderately fast pseudorandom function, returning a 64-bit or 128-bit tag for an arbitrary long input.
//
// Typical use cases include:
// - protection against DoS attacks for hash tables and bloom filters
// - authentication of short-lived messages in online protocols
//
// https://www.aumasson.jp/siphash/siphash.pdf
const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const math = std.math;
const mem = std.mem;
/// SipHash function with 64-bit output.
///
/// Recommended parameters are:
/// - (c_rounds=4, d_rounds=8) for conservative security; regular hash functions such as BLAKE2 or BLAKE3 are usually a better alternative.
/// - (c_rounds=2, d_rounds=4) standard parameters.
/// - (c_rounds=1, d_rounds=3) reduced-round function. Faster, no known implications on its practical security level.
/// - (c_rounds=1, d_rounds=2) fastest option, but the output may be distinguishable from random data with related keys or non-uniform input - not suitable as a PRF.
///
/// SipHash is not a traditional hash function. If the input includes untrusted content, a secret key is absolutely necessary.
/// And due to its small output size, collisions in SipHash64 can be found with an exhaustive search.
pub fn SipHash64(comptime c_rounds: usize, comptime d_rounds: usize) type {
return SipHash(u64, c_rounds, d_rounds);
}
/// SipHash function with 128-bit output.
///
/// Recommended parameters are:
/// - (c_rounds=4, d_rounds=8) for conservative security; regular hash functions such as BLAKE2 or BLAKE3 are usually a better alternative.
/// - (c_rounds=2, d_rounds=4) standard parameters.
/// - (c_rounds=1, d_rounds=4) reduced-round function. Recommended to hash very short, similar strings, when a 128-bit PRF output is still required.
/// - (c_rounds=1, d_rounds=3) reduced-round function. Faster, no known implications on its practical security level.
/// - (c_rounds=1, d_rounds=2) fastest option, but the output may be distinguishable from random data with related keys or non-uniform input - not suitable as a PRF.
///
/// SipHash is not a traditional hash function. If the input includes untrusted content, a secret key is absolutely necessary.
pub fn SipHash128(comptime c_rounds: usize, comptime d_rounds: usize) type {
return SipHash(u128, c_rounds, d_rounds);
}
fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) type {
assert(T == u64 or T == u128);
assert(c_rounds > 0 and d_rounds > 0);
return struct {
const Self = @This();
const block_length = 64;
const digest_length = 64;
const key_length = 16;
v0: u64,
v1: u64,
v2: u64,
v3: u64,
msg_len: u8,
pub fn init(key: *const [key_length]u8) Self {
const k0 = mem.readIntLittle(u64, key[0..8]);
const k1 = mem.readIntLittle(u64, key[8..16]);
var d = Self{
.v0 = k0 ^ 0x736f6d6570736575,
.v1 = k1 ^ 0x646f72616e646f6d,
.v2 = k0 ^ 0x6c7967656e657261,
.v3 = k1 ^ 0x7465646279746573,
.msg_len = 0,
};
if (T == u128) {
d.v1 ^= 0xee;
}
return d;
}
pub fn update(self: *Self, b: []const u8) void {
std.debug.assert(b.len % 8 == 0);
var off: usize = 0;
while (off < b.len) : (off += 8) {
@call(.{ .modifier = .always_inline }, self.round, .{b[off..][0..8].*});
}
self.msg_len +%= @as(u8, @truncate(b.len));
}
pub fn final(self: *Self, b: []const u8) T {
std.debug.assert(b.len < 8);
self.msg_len +%= @as(u8, @truncate(b.len));
var buf = [_]u8{0} ** 8;
mem.copy(u8, buf[0..], b[0..]);
buf[7] = self.msg_len;
self.round(buf);
if (T == u128) {
self.v2 ^= 0xee;
} else {
self.v2 ^= 0xff;
}
// TODO this is a workaround, should be able to supply the value without a separate variable
const inl = std.builtin.CallOptions{ .modifier = .always_inline };
comptime var i: usize = 0;
inline while (i < d_rounds) : (i += 1) {
@call(inl, sipRound, .{self});
}
const b1 = self.v0 ^ self.v1 ^ self.v2 ^ self.v3;
if (T == u64) {
return b1;
}
self.v1 ^= 0xdd;
comptime var j: usize = 0;
inline while (j < d_rounds) : (j += 1) {
@call(inl, sipRound, .{self});
}
const b2 = self.v0 ^ self.v1 ^ self.v2 ^ self.v3;
return (@as(u128, b2) << 64) | b1;
}
fn round(self: *Self, b: [8]u8) void {
const m = mem.readIntLittle(u64, b[0..8]);
self.v3 ^= m;
// TODO this is a workaround, should be able to supply the value without a separate variable
const inl = std.builtin.CallOptions{ .modifier = .always_inline };
comptime var i: usize = 0;
inline while (i < c_rounds) : (i += 1) {
@call(inl, sipRound, .{self});
}
self.v0 ^= m;
}
fn sipRound(d: *Self) void {
d.v0 +%= d.v1;
d.v1 = math.rotl(u64, d.v1, @as(u64, 13));
d.v1 ^= d.v0;
d.v0 = math.rotl(u64, d.v0, @as(u64, 32));
d.v2 +%= d.v3;
d.v3 = math.rotl(u64, d.v3, @as(u64, 16));
d.v3 ^= d.v2;
d.v0 +%= d.v3;
d.v3 = math.rotl(u64, d.v3, @as(u64, 21));
d.v3 ^= d.v0;
d.v2 +%= d.v1;
d.v1 = math.rotl(u64, d.v1, @as(u64, 17));
d.v1 ^= d.v2;
d.v2 = math.rotl(u64, d.v2, @as(u64, 32));
}
pub fn hash(msg: []const u8, key: *const [key_length]u8) T {
const aligned_len = msg.len - (msg.len % 8);
var c = Self.init(key);
@call(.{ .modifier = .always_inline }, c.update, .{msg[0..aligned_len]});
return @call(.{ .modifier = .always_inline }, c.final, .{msg[aligned_len..]});
}
};
}
fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) type {
assert(T == u64 or T == u128);
assert(c_rounds > 0 and d_rounds > 0);
return struct {
const State = SipHashStateless(T, c_rounds, d_rounds);
const Self = @This();
pub const key_length = 16;
pub const mac_length = @sizeOf(T);
pub const block_length = 8;
state: State,
buf: [8]u8,
buf_len: usize,
/// Initialize a state for a SipHash function
pub fn init(key: *const [key_length]u8) Self {
return Self{
.state = State.init(key),
.buf = undefined,
.buf_len = 0,
};
}
/// Add data to the state
pub fn update(self: *Self, b: []const u8) void {
var off: usize = 0;
if (self.buf_len != 0 and self.buf_len + b.len >= 8) {
off += 8 - self.buf_len;
mem.copy(u8, self.buf[self.buf_len..], b[0..off]);
self.state.update(self.buf[0..]);
self.buf_len = 0;
}
const remain_len = b.len - off;
const aligned_len = remain_len - (remain_len % 8);
self.state.update(b[off .. off + aligned_len]);
mem.copy(u8, self.buf[self.buf_len..], b[off + aligned_len ..]);
self.buf_len += @as(u8, @intCast(b[off + aligned_len ..].len));
}
/// Return an authentication tag for the current state
/// Assumes `out` is less than or equal to `mac_length`.
pub fn final(self: *Self, out: *[mac_length]u8) void {
mem.writeIntLittle(T, out, self.state.final(self.buf[0..self.buf_len]));
}
/// Return an authentication tag for a message and a key
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [key_length]u8) void {
var ctx = Self.init(key);
ctx.update(msg);
ctx.final(out);
}
/// Return an authentication tag for the current state, as an integer
pub fn finalInt(self: *Self) T {
return self.state.final(self.buf[0..self.buf_len]);
}
/// Return an authentication tag for a message and a key, as an integer
pub fn toInt(msg: []const u8, key: *const [key_length]u8) T {
return State.hash(msg, key);
}
};
}
// Test vectors from reference implementation.
// https://github.com/veorq/SipHash/blob/master/vectors.h
const test_key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";
test "siphash64-2-4 sanity" {
const vectors = [_][8]u8{
"\x31\x0e\x0e\xdd\x47\xdb\x6f\x72".*, // ""
"\xfd\x67\xdc\x93\xc5\x39\xf8\x74".*, // "\x00"
"\x5a\x4f\xa9\xd9\x09\x80\x6c\x0d".*, // "\x00\x01" ... etc
"\x2d\x7e\xfb\xd7\x96\x66\x67\x85".*,
"\xb7\x87\x71\x27\xe0\x94\x27\xcf".*,
"\x8d\xa6\x99\xcd\x64\x55\x76\x18".*,
"\xce\xe3\xfe\x58\x6e\x46\xc9\xcb".*,
"\x37\xd1\x01\x8b\xf5\x00\x02\xab".*,
"\x62\x24\x93\x9a\x79\xf5\xf5\x93".*,
"\xb0\xe4\xa9\x0b\xdf\x82\x00\x9e".*,
"\xf3\xb9\xdd\x94\xc5\xbb\x5d\x7a".*,
"\xa7\xad\x6b\x22\x46\x2f\xb3\xf4".*,
"\xfb\xe5\x0e\x86\xbc\x8f\x1e\x75".*,
"\x90\x3d\x84\xc0\x27\x56\xea\x14".*,
"\xee\xf2\x7a\x8e\x90\xca\x23\xf7".*,
"\xe5\x45\xbe\x49\x61\xca\x29\xa1".*,
"\xdb\x9b\xc2\x57\x7f\xcc\x2a\x3f".*,
"\x94\x47\xbe\x2c\xf5\xe9\x9a\x69".*,
"\x9c\xd3\x8d\x96\xf0\xb3\xc1\x4b".*,
"\xbd\x61\x79\xa7\x1d\xc9\x6d\xbb".*,
"\x98\xee\xa2\x1a\xf2\x5c\xd6\xbe".*,
"\xc7\x67\x3b\x2e\xb0\xcb\xf2\xd0".*,
"\x88\x3e\xa3\xe3\x95\x67\x53\x93".*,
"\xc8\xce\x5c\xcd\x8c\x03\x0c\xa8".*,
"\x94\xaf\x49\xf6\xc6\x50\xad\xb8".*,
"\xea\xb8\x85\x8a\xde\x92\xe1\xbc".*,
"\xf3\x15\xbb\x5b\xb8\x35\xd8\x17".*,
"\xad\xcf\x6b\x07\x63\x61\x2e\x2f".*,
"\xa5\xc9\x1d\xa7\xac\xaa\x4d\xde".*,
"\x71\x65\x95\x87\x66\x50\xa2\xa6".*,
"\x28\xef\x49\x5c\x53\xa3\x87\xad".*,
"\x42\xc3\x41\xd8\xfa\x92\xd8\x32".*,
"\xce\x7c\xf2\x72\x2f\x51\x27\x71".*,
"\xe3\x78\x59\xf9\x46\x23\xf3\xa7".*,
"\x38\x12\x05\xbb\x1a\xb0\xe0\x12".*,
"\xae\x97\xa1\x0f\xd4\x34\xe0\x15".*,
"\xb4\xa3\x15\x08\xbe\xff\x4d\x31".*,
"\x81\x39\x62\x29\xf0\x90\x79\x02".*,
"\x4d\x0c\xf4\x9e\xe5\xd4\xdc\xca".*,
"\x5c\x73\x33\x6a\x76\xd8\xbf\x9a".*,
"\xd0\xa7\x04\x53\x6b\xa9\x3e\x0e".*,
"\x92\x59\x58\xfc\xd6\x42\x0c\xad".*,
"\xa9\x15\xc2\x9b\xc8\x06\x73\x18".*,
"\x95\x2b\x79\xf3\xbc\x0a\xa6\xd4".*,
"\xf2\x1d\xf2\xe4\x1d\x45\x35\xf9".*,
"\x87\x57\x75\x19\x04\x8f\x53\xa9".*,
"\x10\xa5\x6c\xf5\xdf\xcd\x9a\xdb".*,
"\xeb\x75\x09\x5c\xcd\x98\x6c\xd0".*,
"\x51\xa9\xcb\x9e\xcb\xa3\x12\xe6".*,
"\x96\xaf\xad\xfc\x2c\xe6\x66\xc7".*,
"\x72\xfe\x52\x97\x5a\x43\x64\xee".*,
"\x5a\x16\x45\xb2\x76\xd5\x92\xa1".*,
"\xb2\x74\xcb\x8e\xbf\x87\x87\x0a".*,
"\x6f\x9b\xb4\x20\x3d\xe7\xb3\x81".*,
"\xea\xec\xb2\xa3\x0b\x22\xa8\x7f".*,
"\x99\x24\xa4\x3c\xc1\x31\x57\x24".*,
"\xbd\x83\x8d\x3a\xaf\xbf\x8d\xb7".*,
"\x0b\x1a\x2a\x32\x65\xd5\x1a\xea".*,
"\x13\x50\x79\xa3\x23\x1c\xe6\x60".*,
"\x93\x2b\x28\x46\xe4\xd7\x06\x66".*,
"\xe1\x91\x5f\x5c\xb1\xec\xa4\x6c".*,
"\xf3\x25\x96\x5c\xa1\x6d\x62\x9f".*,
"\x57\x5f\xf2\x8e\x60\x38\x1b\xe5".*,
"\x72\x45\x06\xeb\x4c\x32\x8a\x95".*,
};
const siphash = SipHash64(2, 4);
var buffer: [64]u8 = undefined;
for (vectors, 0..) |vector, i| {
buffer[i] = @as(u8, @intCast(i));
var out: [siphash.mac_length]u8 = undefined;
siphash.create(&out, buffer[0..i], test_key);
try testing.expectEqual(out, vector);
}
}
test "siphash128-2-4 sanity" {
const vectors = [_][16]u8{
"\xa3\x81\x7f\x04\xba\x25\xa8\xe6\x6d\xf6\x72\x14\xc7\x55\x02\x93".*,
"\xda\x87\xc1\xd8\x6b\x99\xaf\x44\x34\x76\x59\x11\x9b\x22\xfc\x45".*,
"\x81\x77\x22\x8d\xa4\xa4\x5d\xc7\xfc\xa3\x8b\xde\xf6\x0a\xff\xe4".*,
"\x9c\x70\xb6\x0c\x52\x67\xa9\x4e\x5f\x33\xb6\xb0\x29\x85\xed\x51".*,
"\xf8\x81\x64\xc1\x2d\x9c\x8f\xaf\x7d\x0f\x6e\x7c\x7b\xcd\x55\x79".*,
"\x13\x68\x87\x59\x80\x77\x6f\x88\x54\x52\x7a\x07\x69\x0e\x96\x27".*,
"\x14\xee\xca\x33\x8b\x20\x86\x13\x48\x5e\xa0\x30\x8f\xd7\xa1\x5e".*,
"\xa1\xf1\xeb\xbe\xd8\xdb\xc1\x53\xc0\xb8\x4a\xa6\x1f\xf0\x82\x39".*,
"\x3b\x62\xa9\xba\x62\x58\xf5\x61\x0f\x83\xe2\x64\xf3\x14\x97\xb4".*,
"\x26\x44\x99\x06\x0a\xd9\xba\xab\xc4\x7f\x8b\x02\xbb\x6d\x71\xed".*,
"\x00\x11\x0d\xc3\x78\x14\x69\x56\xc9\x54\x47\xd3\xf3\xd0\xfb\xba".*,
"\x01\x51\xc5\x68\x38\x6b\x66\x77\xa2\xb4\xdc\x6f\x81\xe5\xdc\x18".*,
"\xd6\x26\xb2\x66\x90\x5e\xf3\x58\x82\x63\x4d\xf6\x85\x32\xc1\x25".*,
"\x98\x69\xe2\x47\xe9\xc0\x8b\x10\xd0\x29\x93\x4f\xc4\xb9\x52\xf7".*,
"\x31\xfc\xef\xac\x66\xd7\xde\x9c\x7e\xc7\x48\x5f\xe4\x49\x49\x02".*,
"\x54\x93\xe9\x99\x33\xb0\xa8\x11\x7e\x08\xec\x0f\x97\xcf\xc3\xd9".*,
"\x6e\xe2\xa4\xca\x67\xb0\x54\xbb\xfd\x33\x15\xbf\x85\x23\x05\x77".*,
"\x47\x3d\x06\xe8\x73\x8d\xb8\x98\x54\xc0\x66\xc4\x7a\xe4\x77\x40".*,
"\xa4\x26\xe5\xe4\x23\xbf\x48\x85\x29\x4d\xa4\x81\xfe\xae\xf7\x23".*,
"\x78\x01\x77\x31\xcf\x65\xfa\xb0\x74\xd5\x20\x89\x52\x51\x2e\xb1".*,
"\x9e\x25\xfc\x83\x3f\x22\x90\x73\x3e\x93\x44\xa5\xe8\x38\x39\xeb".*,
"\x56\x8e\x49\x5a\xbe\x52\x5a\x21\x8a\x22\x14\xcd\x3e\x07\x1d\x12".*,
"\x4a\x29\xb5\x45\x52\xd1\x6b\x9a\x46\x9c\x10\x52\x8e\xff\x0a\xae".*,
"\xc9\xd1\x84\xdd\xd5\xa9\xf5\xe0\xcf\x8c\xe2\x9a\x9a\xbf\x69\x1c".*,
"\x2d\xb4\x79\xae\x78\xbd\x50\xd8\x88\x2a\x8a\x17\x8a\x61\x32\xad".*,
"\x8e\xce\x5f\x04\x2d\x5e\x44\x7b\x50\x51\xb9\xea\xcb\x8d\x8f\x6f".*,
"\x9c\x0b\x53\xb4\xb3\xc3\x07\xe8\x7e\xae\xe0\x86\x78\x14\x1f\x66".*,
"\xab\xf2\x48\xaf\x69\xa6\xea\xe4\xbf\xd3\xeb\x2f\x12\x9e\xeb\x94".*,
"\x06\x64\xda\x16\x68\x57\x4b\x88\xb9\x35\xf3\x02\x73\x58\xae\xf4".*,
"\xaa\x4b\x9d\xc4\xbf\x33\x7d\xe9\x0c\xd4\xfd\x3c\x46\x7c\x6a\xb7".*,
"\xea\x5c\x7f\x47\x1f\xaf\x6b\xde\x2b\x1a\xd7\xd4\x68\x6d\x22\x87".*,
"\x29\x39\xb0\x18\x32\x23\xfa\xfc\x17\x23\xde\x4f\x52\xc4\x3d\x35".*,
"\x7c\x39\x56\xca\x5e\xea\xfc\x3e\x36\x3e\x9d\x55\x65\x46\xeb\x68".*,
"\x77\xc6\x07\x71\x46\xf0\x1c\x32\xb6\xb6\x9d\x5f\x4e\xa9\xff\xcf".*,
"\x37\xa6\x98\x6c\xb8\x84\x7e\xdf\x09\x25\xf0\xf1\x30\x9b\x54\xde".*,
"\xa7\x05\xf0\xe6\x9d\xa9\xa8\xf9\x07\x24\x1a\x2e\x92\x3c\x8c\xc8".*,
"\x3d\xc4\x7d\x1f\x29\xc4\x48\x46\x1e\x9e\x76\xed\x90\x4f\x67\x11".*,
"\x0d\x62\xbf\x01\xe6\xfc\x0e\x1a\x0d\x3c\x47\x51\xc5\xd3\x69\x2b".*,
"\x8c\x03\x46\x8b\xca\x7c\x66\x9e\xe4\xfd\x5e\x08\x4b\xbe\xe7\xb5".*,
"\x52\x8a\x5b\xb9\x3b\xaf\x2c\x9c\x44\x73\xcc\xe5\xd0\xd2\x2b\xd9".*,
"\xdf\x6a\x30\x1e\x95\xc9\x5d\xad\x97\xae\x0c\xc8\xc6\x91\x3b\xd8".*,
"\x80\x11\x89\x90\x2c\x85\x7f\x39\xe7\x35\x91\x28\x5e\x70\xb6\xdb".*,
"\xe6\x17\x34\x6a\xc9\xc2\x31\xbb\x36\x50\xae\x34\xcc\xca\x0c\x5b".*,
"\x27\xd9\x34\x37\xef\xb7\x21\xaa\x40\x18\x21\xdc\xec\x5a\xdf\x89".*,
"\x89\x23\x7d\x9d\xed\x9c\x5e\x78\xd8\xb1\xc9\xb1\x66\xcc\x73\x42".*,
"\x4a\x6d\x80\x91\xbf\x5e\x7d\x65\x11\x89\xfa\x94\xa2\x50\xb1\x4c".*,
"\x0e\x33\xf9\x60\x55\xe7\xae\x89\x3f\xfc\x0e\x3d\xcf\x49\x29\x02".*,
"\xe6\x1c\x43\x2b\x72\x0b\x19\xd1\x8e\xc8\xd8\x4b\xdc\x63\x15\x1b".*,
"\xf7\xe5\xae\xf5\x49\xf7\x82\xcf\x37\x90\x55\xa6\x08\x26\x9b\x16".*,
"\x43\x8d\x03\x0f\xd0\xb7\xa5\x4f\xa8\x37\xf2\xad\x20\x1a\x64\x03".*,
"\xa5\x90\xd3\xee\x4f\xbf\x04\xe3\x24\x7e\x0d\x27\xf2\x86\x42\x3f".*,
"\x5f\xe2\xc1\xa1\x72\xfe\x93\xc4\xb1\x5c\xd3\x7c\xae\xf9\xf5\x38".*,
"\x2c\x97\x32\x5c\xbd\x06\xb3\x6e\xb2\x13\x3d\xd0\x8b\x3a\x01\x7c".*,
"\x92\xc8\x14\x22\x7a\x6b\xca\x94\x9f\xf0\x65\x9f\x00\x2a\xd3\x9e".*,
"\xdc\xe8\x50\x11\x0b\xd8\x32\x8c\xfb\xd5\x08\x41\xd6\x91\x1d\x87".*,
"\x67\xf1\x49\x84\xc7\xda\x79\x12\x48\xe3\x2b\xb5\x92\x25\x83\xda".*,
"\x19\x38\xf2\xcf\x72\xd5\x4e\xe9\x7e\x94\x16\x6f\xa9\x1d\x2a\x36".*,
"\x74\x48\x1e\x96\x46\xed\x49\xfe\x0f\x62\x24\x30\x16\x04\x69\x8e".*,
"\x57\xfc\xa5\xde\x98\xa9\xd6\xd8\x00\x64\x38\xd0\x58\x3d\x8a\x1d".*,
"\x9f\xec\xde\x1c\xef\xdc\x1c\xbe\xd4\x76\x36\x74\xd9\x57\x53\x59".*,
"\xe3\x04\x0c\x00\xeb\x28\xf1\x53\x66\xca\x73\xcb\xd8\x72\xe7\x40".*,
"\x76\x97\x00\x9a\x6a\x83\x1d\xfe\xcc\xa9\x1c\x59\x93\x67\x0f\x7a".*,
"\x58\x53\x54\x23\x21\xf5\x67\xa0\x05\xd5\x47\xa4\xf0\x47\x59\xbd".*,
"\x51\x50\xd1\x77\x2f\x50\x83\x4a\x50\x3e\x06\x9a\x97\x3f\xbd\x7c".*,
};
const siphash = SipHash128(2, 4);
var buffer: [64]u8 = undefined;
for (vectors, 0..) |vector, i| {
buffer[i] = @as(u8, @intCast(i));
var out: [siphash.mac_length]u8 = undefined;
siphash.create(&out, buffer[0..i], test_key[0..]);
try testing.expectEqual(out, vector);
}
}
test "iterative non-divisible update" {
var buf: [1024]u8 = undefined;
for (buf, 0..) |*e, i| {
e.* = @as(u8, @truncate(i));
}
const key = "0x128dad08f12307";
const Siphash = SipHash64(2, 4);
var end: usize = 9;
while (end < buf.len) : (end += 9) {
const non_iterative_hash = Siphash.toInt(buf[0..end], key[0..]);
var siphash = Siphash.init(key);
var i: usize = 0;
while (i < end) : (i += 7) {
siphash.update(buf[i..std.math.min(i + 7, end)]);
}
const iterative_hash = siphash.finalInt();
try std.testing.expectEqual(iterative_hash, non_iterative_hash);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/phc_encoding.zig | // https://github.com/P-H-C/phc-string-format
const std = @import("std");
const fmt = std.fmt;
const io = std.io;
const mem = std.mem;
const meta = std.meta;
const fields_delimiter = "$";
const version_param_name = "v";
const params_delimiter = ",";
const kv_delimiter = "=";
pub const Error = std.crypto.errors.EncodingError || error{NoSpaceLeft};
const B64Decoder = std.base64.standard_no_pad.Decoder;
const B64Encoder = std.base64.standard_no_pad.Encoder;
/// A wrapped binary value whose maximum size is `max_len`.
///
/// This type must be used whenever a binary value is encoded in a PHC-formatted string.
/// This includes `salt`, `hash`, and any other binary parameters such as keys.
///
/// Once initialized, the actual value can be read with the `constSlice()` function.
pub fn BinValue(comptime max_len: usize) type {
return struct {
const Self = @This();
const capacity = max_len;
const max_encoded_length = B64Encoder.calcSize(max_len);
buf: [max_len]u8 = undefined,
len: usize = 0,
/// Wrap an existing byte slice
pub fn fromSlice(slice: []const u8) Error!Self {
if (slice.len > capacity) return Error.NoSpaceLeft;
var bin_value: Self = undefined;
mem.copy(u8, &bin_value.buf, slice);
bin_value.len = slice.len;
return bin_value;
}
/// Return the slice containing the actual value.
pub fn constSlice(self: Self) []const u8 {
return self.buf[0..self.len];
}
fn fromB64(self: *Self, str: []const u8) !void {
const len = B64Decoder.calcSizeForSlice(str) catch return Error.InvalidEncoding;
if (len > self.buf.len) return Error.NoSpaceLeft;
B64Decoder.decode(&self.buf, str) catch return Error.InvalidEncoding;
self.len = len;
}
fn toB64(self: Self, buf: []u8) ![]const u8 {
const value = self.constSlice();
const len = B64Encoder.calcSize(value.len);
if (len > buf.len) return Error.NoSpaceLeft;
return B64Encoder.encode(buf, value);
}
};
}
/// Deserialize a PHC-formatted string into a structure `HashResult`.
///
/// Required field in the `HashResult` structure:
/// - `alg_id`: algorithm identifier
/// Optional, special fields:
/// - `alg_version`: algorithm version (unsigned integer)
/// - `salt`: salt
/// - `hash`: output of the hash function
///
/// Other fields will also be deserialized from the function parameters section.
pub fn deserialize(comptime HashResult: type, str: []const u8) Error!HashResult {
var out = mem.zeroes(HashResult);
var it = mem.split(u8, str, fields_delimiter);
var set_fields: usize = 0;
while (true) {
// Read the algorithm identifier
if ((it.next() orelse return Error.InvalidEncoding).len != 0) return Error.InvalidEncoding;
out.alg_id = it.next() orelse return Error.InvalidEncoding;
set_fields += 1;
// Read the optional version number
var field = it.next() orelse break;
if (kvSplit(field)) |opt_version| {
if (mem.eql(u8, opt_version.key, version_param_name)) {
if (@hasField(HashResult, "alg_version")) {
const value_type_info = switch (@typeInfo(@TypeOf(out.alg_version))) {
.Optional => |opt| comptime @typeInfo(opt.child),
else => |t| t,
};
out.alg_version = fmt.parseUnsigned(
@Type(value_type_info),
opt_version.value,
10,
) catch return Error.InvalidEncoding;
set_fields += 1;
}
field = it.next() orelse break;
}
} else |_| {}
// Read optional parameters
var has_params = false;
var it_params = mem.split(u8, field, params_delimiter);
while (it_params.next()) |params| {
const param = kvSplit(params) catch break;
var found = false;
inline for (comptime meta.fields(HashResult)) |p| {
if (mem.eql(u8, p.name, param.key)) {
switch (@typeInfo(p.field_type)) {
.Int => @field(out, p.name) = fmt.parseUnsigned(
p.field_type,
param.value,
10,
) catch return Error.InvalidEncoding,
.Pointer => |ptr| {
if (!ptr.is_const) @compileError("Value slice must be constant");
@field(out, p.name) = param.value;
},
.Struct => try @field(out, p.name).fromB64(param.value),
else => std.debug.panic(
"Value for [{s}] must be an integer, a constant slice or a BinValue",
.{p.name},
),
}
set_fields += 1;
found = true;
break;
}
}
if (!found) return Error.InvalidEncoding; // An unexpected parameter was found in the string
has_params = true;
}
// No separator between an empty parameters set and the salt
if (has_params) field = it.next() orelse break;
// Read an optional salt
if (@hasField(HashResult, "salt")) {
try out.salt.fromB64(field);
set_fields += 1;
} else {
return Error.InvalidEncoding;
}
// Read an optional hash
field = it.next() orelse break;
if (@hasField(HashResult, "hash")) {
try out.hash.fromB64(field);
set_fields += 1;
} else {
return Error.InvalidEncoding;
}
break;
}
// Check that all the required fields have been set, excluding optional values and parameters
// with default values
var expected_fields: usize = 0;
inline for (comptime meta.fields(HashResult)) |p| {
if (@typeInfo(p.field_type) != .Optional and p.default_value == null) {
expected_fields += 1;
}
}
if (set_fields < expected_fields) return Error.InvalidEncoding;
return out;
}
/// Serialize parameters into a PHC string.
///
/// Required field for `params`:
/// - `alg_id`: algorithm identifier
/// Optional, special fields:
/// - `alg_version`: algorithm version (unsigned integer)
/// - `salt`: salt
/// - `hash`: output of the hash function
///
/// `params` can also include any additional parameters.
pub fn serialize(params: anytype, str: []u8) Error![]const u8 {
var buf = io.fixedBufferStream(str);
try serializeTo(params, buf.writer());
return buf.getWritten();
}
/// Compute the number of bytes required to serialize `params`
pub fn calcSize(params: anytype) usize {
var buf = io.countingWriter(io.null_writer);
serializeTo(params, buf.writer()) catch unreachable;
return @as(usize, @intCast(buf.bytes_written));
}
fn serializeTo(params: anytype, out: anytype) !void {
const HashResult = @TypeOf(params);
try out.writeAll(fields_delimiter);
try out.writeAll(params.alg_id);
if (@hasField(HashResult, "alg_version")) {
if (@typeInfo(@TypeOf(params.alg_version)) == .Optional) {
if (params.alg_version) |alg_version| {
try out.print(
"{s}{s}{s}{}",
.{ fields_delimiter, version_param_name, kv_delimiter, alg_version },
);
}
} else {
try out.print(
"{s}{s}{s}{}",
.{ fields_delimiter, version_param_name, kv_delimiter, params.alg_version },
);
}
}
var has_params = false;
inline for (comptime meta.fields(HashResult)) |p| {
if (!(mem.eql(u8, p.name, "alg_id") or
mem.eql(u8, p.name, "alg_version") or
mem.eql(u8, p.name, "hash") or
mem.eql(u8, p.name, "salt")))
{
const value = @field(params, p.name);
try out.writeAll(if (has_params) params_delimiter else fields_delimiter);
if (@typeInfo(p.field_type) == .Struct) {
var buf: [@TypeOf(value).max_encoded_length]u8 = undefined;
try out.print("{s}{s}{s}", .{ p.name, kv_delimiter, try value.toB64(&buf) });
} else {
try out.print(
if (@typeInfo(@TypeOf(value)) == .Pointer) "{s}{s}{s}" else "{s}{s}{}",
.{ p.name, kv_delimiter, value },
);
}
has_params = true;
}
}
var has_salt = false;
if (@hasField(HashResult, "salt")) {
var buf: [@TypeOf(params.salt).max_encoded_length]u8 = undefined;
try out.print("{s}{s}", .{ fields_delimiter, try params.salt.toB64(&buf) });
has_salt = true;
}
if (@hasField(HashResult, "hash")) {
var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
if (!has_salt) try out.writeAll(fields_delimiter);
try out.print("{s}{s}", .{ fields_delimiter, try params.hash.toB64(&buf) });
}
}
// Split a `key=value` string into `key` and `value`
fn kvSplit(str: []const u8) !struct { key: []const u8, value: []const u8 } {
var it = mem.split(u8, str, kv_delimiter);
const key = it.next() orelse return Error.InvalidEncoding;
const value = it.next() orelse return Error.InvalidEncoding;
const ret = .{ .key = key, .value = value };
return ret;
}
test "phc format - encoding/decoding" {
const Input = struct {
str: []const u8,
HashResult: type,
};
const inputs = [_]Input{
.{
.str = "$argon2id$v=19$key=a2V5,m=4096,t=0,p=1$X1NhbHQAAAAAAAAAAAAAAA$bWh++MKN1OiFHKgIWTLvIi1iHicmHH7+Fv3K88ifFfI",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
key: BinValue(16),
m: usize,
t: u64,
p: u32,
salt: BinValue(16),
hash: BinValue(32),
},
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct {
alg_id: []const u8,
alg_version: ?u30,
ln: u6,
r: u30,
p: u30,
salt: BinValue(16),
hash: BinValue(16),
},
},
.{
.str = "$scrypt",
.HashResult = struct { alg_id: []const u8 },
},
.{ .str = "$scrypt$v=1", .HashResult = struct { alg_id: []const u8, alg_version: u16 } },
.{
.str = "$scrypt$ln=15,r=8,p=1",
.HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
},
.{
.str = "$scrypt$c2FsdHNhbHQ",
.HashResult = struct { alg_id: []const u8, salt: BinValue(16) },
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
ln: u6,
r: u30,
p: u30,
salt: BinValue(16),
},
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1",
.HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
},
.{
.str = "$scrypt$v=1$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
salt: BinValue(16),
hash: BinValue(16),
},
},
.{
.str = "$scrypt$v=1$c2FsdHNhbHQ",
.HashResult = struct { alg_id: []const u8, alg_version: u16, salt: BinValue(16) },
},
.{
.str = "$scrypt$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct { alg_id: []const u8, salt: BinValue(16), hash: BinValue(16) },
},
};
inline for (inputs) |input| {
const v = try deserialize(input.HashResult, input.str);
var buf: [input.str.len]u8 = undefined;
const s1 = try serialize(v, &buf);
try std.testing.expectEqualSlices(u8, input.str, s1);
}
}
test "phc format - empty input string" {
const s = "";
const v = deserialize(struct { alg_id: []const u8 }, s);
try std.testing.expectError(Error.InvalidEncoding, v);
}
test "phc format - hash without salt" {
const s = "$scrypt";
const v = deserialize(struct { alg_id: []const u8, hash: BinValue(16) }, s);
try std.testing.expectError(Error.InvalidEncoding, v);
}
test "phc format - calcSize" {
const s = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M";
const v = try deserialize(struct {
alg_id: []const u8,
alg_version: u16,
ln: u6,
r: u30,
p: u30,
salt: BinValue(8),
hash: BinValue(8),
}, s);
try std.testing.expectEqual(calcSize(v), s.len);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/isap.zig | const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const math = std.math;
const testing = std.testing;
const AuthenticationError = std.crypto.errors.AuthenticationError;
/// ISAPv2 is an authenticated encryption system hardened against side channels and fault attacks.
/// https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/round-2/spec-doc-rnd2/isap-spec-round2.pdf
///
/// Note that ISAP is not suitable for high-performance applications.
///
/// However:
/// - if allowing physical access to the device is part of your threat model,
/// - or if you need resistance against microcode/hardware-level side channel attacks,
/// - or if software-induced fault attacks such as rowhammer are a concern,
///
/// then you may consider ISAP for highly sensitive data.
pub const IsapA128A = struct {
pub const key_length = 16;
pub const nonce_length = 16;
pub const tag_length: usize = 16;
const iv1 = [_]u8{ 0x01, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const iv2 = [_]u8{ 0x02, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const iv3 = [_]u8{ 0x03, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const Block = [5]u64;
block: Block,
fn round(isap: *IsapA128A, rk: u64) void {
var x = &isap.block;
x[2] ^= rk;
x[0] ^= x[4];
x[4] ^= x[3];
x[2] ^= x[1];
var t = x.*;
x[0] = t[0] ^ ((~t[1]) & t[2]);
x[2] = t[2] ^ ((~t[3]) & t[4]);
x[4] = t[4] ^ ((~t[0]) & t[1]);
x[1] = t[1] ^ ((~t[2]) & t[3]);
x[3] = t[3] ^ ((~t[4]) & t[0]);
x[1] ^= x[0];
t[1] = x[1];
x[1] = math.rotr(u64, x[1], 39);
x[3] ^= x[2];
t[2] = x[2];
x[2] = math.rotr(u64, x[2], 1);
t[4] = x[4];
t[2] ^= x[2];
x[2] = math.rotr(u64, x[2], 5);
t[3] = x[3];
t[1] ^= x[1];
x[3] = math.rotr(u64, x[3], 10);
x[0] ^= x[4];
x[4] = math.rotr(u64, x[4], 7);
t[3] ^= x[3];
x[2] ^= t[2];
x[1] = math.rotr(u64, x[1], 22);
t[0] = x[0];
x[2] = ~x[2];
x[3] = math.rotr(u64, x[3], 7);
t[4] ^= x[4];
x[4] = math.rotr(u64, x[4], 34);
x[3] ^= t[3];
x[1] ^= t[1];
x[0] = math.rotr(u64, x[0], 19);
x[4] ^= t[4];
t[0] ^= x[0];
x[0] = math.rotr(u64, x[0], 9);
x[0] ^= t[0];
}
fn p12(isap: *IsapA128A) void {
const rks = [12]u64{ 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b };
inline for (rks) |rk| {
isap.round(rk);
}
}
fn p6(isap: *IsapA128A) void {
const rks = [6]u64{ 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b };
inline for (rks) |rk| {
isap.round(rk);
}
}
fn p1(isap: *IsapA128A) void {
isap.round(0x4b);
}
fn absorb(isap: *IsapA128A, m: []const u8) void {
var block = &isap.block;
var i: usize = 0;
while (true) : (i += 8) {
const left = m.len - i;
if (left >= 8) {
block[0] ^= mem.readIntBig(u64, m[i..][0..8]);
isap.p12();
if (left == 8) {
block[0] ^= 0x8000000000000000;
isap.p12();
break;
}
} else {
var padded = [_]u8{0} ** 8;
mem.copy(u8, padded[0..left], m[i..]);
padded[left] = 0x80;
block[0] ^= mem.readIntBig(u64, padded[0..]);
isap.p12();
break;
}
}
}
fn trickle(k: [16]u8, iv: [8]u8, y: []const u8, comptime out_len: usize) [out_len]u8 {
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, k[0..8]),
mem.readIntBig(u64, k[8..16]),
mem.readIntBig(u64, iv[0..8]),
0,
0,
},
};
isap.p12();
var i: usize = 0;
while (i < y.len * 8 - 1) : (i += 1) {
const cur_byte_pos = i / 8;
const cur_bit_pos = @as(u3, @truncate(7 - (i % 8)));
const cur_bit = @as(u64, ((y[cur_byte_pos] >> cur_bit_pos) & 1) << 7);
isap.block[0] ^= cur_bit << 56;
isap.p1();
}
const cur_bit = @as(u64, (y[y.len - 1] & 1) << 7);
isap.block[0] ^= cur_bit << 56;
isap.p12();
var out: [out_len]u8 = undefined;
var j: usize = 0;
while (j < out_len) : (j += 8) {
mem.writeIntBig(u64, out[j..][0..8], isap.block[j / 8]);
}
std.crypto.utils.secureZero(u64, &isap.block);
return out;
}
fn mac(c: []const u8, ad: []const u8, npub: [16]u8, key: [16]u8) [16]u8 {
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, npub[0..8]),
mem.readIntBig(u64, npub[8..16]),
mem.readIntBig(u64, iv1[0..]),
0,
0,
},
};
isap.p12();
isap.absorb(ad);
isap.block[4] ^= 1;
isap.absorb(c);
var y: [16]u8 = undefined;
mem.writeIntBig(u64, y[0..8], isap.block[0]);
mem.writeIntBig(u64, y[8..16], isap.block[1]);
const nb = trickle(key, iv2, y[0..], 16);
isap.block[0] = mem.readIntBig(u64, nb[0..8]);
isap.block[1] = mem.readIntBig(u64, nb[8..16]);
isap.p12();
var tag: [16]u8 = undefined;
mem.writeIntBig(u64, tag[0..8], isap.block[0]);
mem.writeIntBig(u64, tag[8..16], isap.block[1]);
std.crypto.utils.secureZero(u64, &isap.block);
return tag;
}
fn xor(out: []u8, in: []const u8, npub: [16]u8, key: [16]u8) void {
debug.assert(in.len == out.len);
const nb = trickle(key, iv3, npub[0..], 24);
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, nb[0..8]),
mem.readIntBig(u64, nb[8..16]),
mem.readIntBig(u64, nb[16..24]),
mem.readIntBig(u64, npub[0..8]),
mem.readIntBig(u64, npub[8..16]),
},
};
isap.p6();
var i: usize = 0;
while (true) : (i += 8) {
const left = in.len - i;
if (left >= 8) {
mem.writeIntNative(u64, out[i..][0..8], mem.bigToNative(u64, isap.block[0]) ^ mem.readIntNative(u64, in[i..][0..8]));
if (left == 8) {
break;
}
isap.p6();
} else {
var pad = [_]u8{0} ** 8;
mem.copy(u8, pad[0..left], in[i..][0..left]);
mem.writeIntNative(u64, pad[i..][0..8], mem.bigToNative(u64, isap.block[0]) ^ mem.readIntNative(u64, pad[i..][0..8]));
mem.copy(u8, out[i..][0..left], pad[0..left]);
break;
}
}
std.crypto.utils.secureZero(u64, &isap.block);
}
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
xor(c, m, npub, key);
tag.* = mac(c, ad, npub, key);
}
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
var computed_tag = mac(c, ad, npub, key);
var acc: u8 = 0;
for (computed_tag, 0..) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
std.crypto.utils.secureZero(u8, &computed_tag);
if (acc != 0) {
return error.AuthenticationFailed;
}
xor(m, c, npub, key);
}
};
test "ISAP" {
const k = [_]u8{1} ** 16;
const n = [_]u8{2} ** 16;
var tag: [16]u8 = undefined;
const ad = "ad";
var msg = "test";
var c: [msg.len]u8 = undefined;
IsapA128A.encrypt(c[0..], &tag, msg[0..], ad, n, k);
try testing.expect(mem.eql(u8, &[_]u8{ 0x8f, 0x68, 0x03, 0x8d }, c[0..]));
try testing.expect(mem.eql(u8, &[_]u8{ 0x6c, 0x25, 0xe8, 0xe2, 0xe1, 0x1f, 0x38, 0xe9, 0x80, 0x75, 0xde, 0xd5, 0x2d, 0xb2, 0x31, 0x82 }, tag[0..]));
try IsapA128A.decrypt(c[0..], c[0..], tag, ad, n, k);
try testing.expect(mem.eql(u8, msg, c[0..]));
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/test.zig | const std = @import("../std.zig");
const testing = std.testing;
const fmt = std.fmt;
// Hash using the specified hasher `H` asserting `expected == H(input)`.
pub fn assertEqualHash(comptime Hasher: anytype, comptime expected_hex: *const [Hasher.digest_length * 2:0]u8, input: []const u8) !void {
var h: [Hasher.digest_length]u8 = undefined;
Hasher.hash(input, &h, .{});
try assertEqual(expected_hex, &h);
}
// Assert `expected` == hex(`input`) where `input` is a bytestring
pub fn assertEqual(comptime expected_hex: [:0]const u8, input: []const u8) !void {
var expected_bytes: [expected_hex.len / 2]u8 = undefined;
for (expected_bytes, 0..) |*r, i| {
r.* = fmt.parseInt(u8, expected_hex[2 * i .. 2 * i + 2], 16) catch unreachable;
}
try testing.expectEqualSlices(u8, &expected_bytes, input);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/chacha20.zig | // Based on public domain Supercop by Daniel J. Bernstein
const std = @import("../std.zig");
const builtin = @import("builtin");
const math = std.math;
const mem = std.mem;
const assert = std.debug.assert;
const testing = std.testing;
const maxInt = math.maxInt;
const Vector = std.meta.Vector;
const Poly1305 = std.crypto.onetimeauth.Poly1305;
const AuthenticationError = std.crypto.errors.AuthenticationError;
/// IETF-variant of the ChaCha20 stream cipher, as designed for TLS.
pub const ChaCha20IETF = ChaChaIETF(20);
/// IETF-variant of the ChaCha20 stream cipher, reduced to 12 rounds.
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha12IETF = ChaChaIETF(12);
/// IETF-variant of the ChaCha20 stream cipher, reduced to 8 rounds.
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha8IETF = ChaChaIETF(8);
/// Original ChaCha20 stream cipher.
pub const ChaCha20With64BitNonce = ChaChaWith64BitNonce(20);
/// Original ChaCha20 stream cipher, reduced to 12 rounds.
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha12With64BitNonce = ChaChaWith64BitNonce(12);
/// Original ChaCha20 stream cipher, reduced to 8 rounds.
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha8With64BitNonce = ChaChaWith64BitNonce(8);
/// XChaCha20 (nonce-extended version of the IETF ChaCha20 variant) stream cipher
pub const XChaCha20IETF = XChaChaIETF(20);
/// XChaCha20 (nonce-extended version of the IETF ChaCha20 variant) stream cipher, reduced to 12 rounds
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const XChaCha12IETF = XChaChaIETF(12);
/// XChaCha20 (nonce-extended version of the IETF ChaCha20 variant) stream cipher, reduced to 8 rounds
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const XChaCha8IETF = XChaChaIETF(8);
/// ChaCha20-Poly1305 authenticated cipher, as designed for TLS
pub const ChaCha20Poly1305 = ChaChaPoly1305(20);
/// ChaCha20-Poly1305 authenticated cipher, reduced to 12 rounds
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha12Poly1305 = ChaChaPoly1305(12);
/// ChaCha20-Poly1305 authenticated cipher, reduced to 8 rounds
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const ChaCha8Poly1305 = ChaChaPoly1305(8);
/// XChaCha20-Poly1305 authenticated cipher
pub const XChaCha20Poly1305 = XChaChaPoly1305(20);
/// XChaCha20-Poly1305 authenticated cipher
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const XChaCha12Poly1305 = XChaChaPoly1305(12);
/// XChaCha20-Poly1305 authenticated cipher
/// Reduced-rounds versions are faster than the full-round version, but have a lower security margin.
/// However, ChaCha is still believed to have a comfortable security even with only with 8 rounds.
pub const XChaCha8Poly1305 = XChaChaPoly1305(8);
// Vectorized implementation of the core function
fn ChaChaVecImpl(comptime rounds_nb: usize) type {
return struct {
const Lane = Vector(4, u32);
const BlockVec = [4]Lane;
fn initContext(key: [8]u32, d: [4]u32) BlockVec {
const c = "expand 32-byte k";
const constant_le = comptime Lane{
mem.readIntLittle(u32, c[0..4]),
mem.readIntLittle(u32, c[4..8]),
mem.readIntLittle(u32, c[8..12]),
mem.readIntLittle(u32, c[12..16]),
};
return BlockVec{
constant_le,
Lane{ key[0], key[1], key[2], key[3] },
Lane{ key[4], key[5], key[6], key[7] },
Lane{ d[0], d[1], d[2], d[3] },
};
}
inline fn chacha20Core(x: *BlockVec, input: BlockVec) void {
x.* = input;
var r: usize = 0;
while (r < rounds_nb) : (r += 2) {
x[0] +%= x[1];
x[3] ^= x[0];
x[3] = math.rotl(Lane, x[3], 16);
x[2] +%= x[3];
x[1] ^= x[2];
x[1] = math.rotl(Lane, x[1], 12);
x[0] +%= x[1];
x[3] ^= x[0];
x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 3, 0, 1, 2 });
x[3] = math.rotl(Lane, x[3], 8);
x[2] +%= x[3];
x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 });
x[1] ^= x[2];
x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 1, 2, 3, 0 });
x[1] = math.rotl(Lane, x[1], 7);
x[0] +%= x[1];
x[3] ^= x[0];
x[3] = math.rotl(Lane, x[3], 16);
x[2] +%= x[3];
x[1] ^= x[2];
x[1] = math.rotl(Lane, x[1], 12);
x[0] +%= x[1];
x[3] ^= x[0];
x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 1, 2, 3, 0 });
x[3] = math.rotl(Lane, x[3], 8);
x[2] +%= x[3];
x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 });
x[1] ^= x[2];
x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 3, 0, 1, 2 });
x[1] = math.rotl(Lane, x[1], 7);
}
}
inline fn hashToBytes(out: *[64]u8, x: BlockVec) void {
var i: usize = 0;
while (i < 4) : (i += 1) {
mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i][0]);
mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i][1]);
mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i][2]);
mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i][3]);
}
}
inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void {
x[0] +%= ctx[0];
x[1] +%= ctx[1];
x[2] +%= ctx[2];
x[3] +%= ctx[3];
}
fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void {
var ctx = initContext(key, counter);
var x: BlockVec = undefined;
var buf: [64]u8 = undefined;
var i: usize = 0;
while (i + 64 <= in.len) : (i += 64) {
chacha20Core(x[0..], ctx);
contextFeedback(&x, ctx);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < 64) : (j += 1) {
xout[j] = xin[j];
}
j = 0;
while (j < 64) : (j += 1) {
xout[j] ^= buf[j];
}
ctx[3][0] += 1;
}
if (i < in.len) {
chacha20Core(x[0..], ctx);
contextFeedback(&x, ctx);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < in.len % 64) : (j += 1) {
xout[j] = xin[j] ^ buf[j];
}
}
}
fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 {
var c: [4]u32 = undefined;
for (c, 0..) |_, i| {
c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]);
}
const ctx = initContext(keyToWords(key), c);
var x: BlockVec = undefined;
chacha20Core(x[0..], ctx);
var out: [32]u8 = undefined;
mem.writeIntLittle(u32, out[0..4], x[0][0]);
mem.writeIntLittle(u32, out[4..8], x[0][1]);
mem.writeIntLittle(u32, out[8..12], x[0][2]);
mem.writeIntLittle(u32, out[12..16], x[0][3]);
mem.writeIntLittle(u32, out[16..20], x[3][0]);
mem.writeIntLittle(u32, out[20..24], x[3][1]);
mem.writeIntLittle(u32, out[24..28], x[3][2]);
mem.writeIntLittle(u32, out[28..32], x[3][3]);
return out;
}
};
}
// Non-vectorized implementation of the core function
fn ChaChaNonVecImpl(comptime rounds_nb: usize) type {
return struct {
const BlockVec = [16]u32;
fn initContext(key: [8]u32, d: [4]u32) BlockVec {
const c = "expand 32-byte k";
const constant_le = comptime [4]u32{
mem.readIntLittle(u32, c[0..4]),
mem.readIntLittle(u32, c[4..8]),
mem.readIntLittle(u32, c[8..12]),
mem.readIntLittle(u32, c[12..16]),
};
return BlockVec{
constant_le[0], constant_le[1], constant_le[2], constant_le[3],
key[0], key[1], key[2], key[3],
key[4], key[5], key[6], key[7],
d[0], d[1], d[2], d[3],
};
}
const QuarterRound = struct {
a: usize,
b: usize,
c: usize,
d: usize,
};
fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound {
return QuarterRound{
.a = a,
.b = b,
.c = c,
.d = d,
};
}
inline fn chacha20Core(x: *BlockVec, input: BlockVec) void {
x.* = input;
const rounds = comptime [_]QuarterRound{
Rp(0, 4, 8, 12),
Rp(1, 5, 9, 13),
Rp(2, 6, 10, 14),
Rp(3, 7, 11, 15),
Rp(0, 5, 10, 15),
Rp(1, 6, 11, 12),
Rp(2, 7, 8, 13),
Rp(3, 4, 9, 14),
};
comptime var j: usize = 0;
inline while (j < rounds_nb) : (j += 2) {
inline for (rounds) |r| {
x[r.a] +%= x[r.b];
x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16));
x[r.c] +%= x[r.d];
x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12));
x[r.a] +%= x[r.b];
x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8));
x[r.c] +%= x[r.d];
x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7));
}
}
}
inline fn hashToBytes(out: *[64]u8, x: BlockVec) void {
var i: usize = 0;
while (i < 4) : (i += 1) {
mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0]);
mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1]);
mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2]);
mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3]);
}
}
inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void {
var i: usize = 0;
while (i < 16) : (i += 1) {
x[i] +%= ctx[i];
}
}
fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void {
var ctx = initContext(key, counter);
var x: BlockVec = undefined;
var buf: [64]u8 = undefined;
var i: usize = 0;
while (i + 64 <= in.len) : (i += 64) {
chacha20Core(x[0..], ctx);
contextFeedback(&x, ctx);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < 64) : (j += 1) {
xout[j] = xin[j];
}
j = 0;
while (j < 64) : (j += 1) {
xout[j] ^= buf[j];
}
ctx[12] += 1;
}
if (i < in.len) {
chacha20Core(x[0..], ctx);
contextFeedback(&x, ctx);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < in.len % 64) : (j += 1) {
xout[j] = xin[j] ^ buf[j];
}
}
}
fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 {
var c: [4]u32 = undefined;
for (c, 0..) |_, i| {
c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]);
}
const ctx = initContext(keyToWords(key), c);
var x: BlockVec = undefined;
chacha20Core(x[0..], ctx);
var out: [32]u8 = undefined;
mem.writeIntLittle(u32, out[0..4], x[0]);
mem.writeIntLittle(u32, out[4..8], x[1]);
mem.writeIntLittle(u32, out[8..12], x[2]);
mem.writeIntLittle(u32, out[12..16], x[3]);
mem.writeIntLittle(u32, out[16..20], x[12]);
mem.writeIntLittle(u32, out[20..24], x[13]);
mem.writeIntLittle(u32, out[24..28], x[14]);
mem.writeIntLittle(u32, out[28..32], x[15]);
return out;
}
};
}
fn ChaChaImpl(comptime rounds_nb: usize) type {
return if (builtin.cpu.arch == .x86_64) ChaChaVecImpl(rounds_nb) else ChaChaNonVecImpl(rounds_nb);
}
fn keyToWords(key: [32]u8) [8]u32 {
var k: [8]u32 = undefined;
var i: usize = 0;
while (i < 8) : (i += 1) {
k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]);
}
return k;
}
fn extend(key: [32]u8, nonce: [24]u8, comptime rounds_nb: usize) struct { key: [32]u8, nonce: [12]u8 } {
var subnonce: [12]u8 = undefined;
mem.set(u8, subnonce[0..4], 0);
mem.copy(u8, subnonce[4..], nonce[16..24]);
return .{
.key = ChaChaImpl(rounds_nb).hchacha20(nonce[0..16].*, key),
.nonce = subnonce,
};
}
fn ChaChaIETF(comptime rounds_nb: usize) type {
return struct {
/// Nonce length in bytes.
pub const nonce_length = 12;
/// Key length in bytes.
pub const key_length = 32;
/// Add the output of the ChaCha20 stream cipher to `in` and stores the result into `out`.
/// WARNING: This function doesn't provide authenticated encryption.
/// Using the AEAD or one of the `box` versions is usually preferred.
pub fn xor(out: []u8, in: []const u8, counter: u32, key: [key_length]u8, nonce: [nonce_length]u8) void {
assert(in.len == out.len);
assert(in.len / 64 <= (1 << 32 - 1) - counter);
var d: [4]u32 = undefined;
d[0] = counter;
d[1] = mem.readIntLittle(u32, nonce[0..4]);
d[2] = mem.readIntLittle(u32, nonce[4..8]);
d[3] = mem.readIntLittle(u32, nonce[8..12]);
ChaChaImpl(rounds_nb).chacha20Xor(out, in, keyToWords(key), d);
}
};
}
fn ChaChaWith64BitNonce(comptime rounds_nb: usize) type {
return struct {
/// Nonce length in bytes.
pub const nonce_length = 8;
/// Key length in bytes.
pub const key_length = 32;
/// Add the output of the ChaCha20 stream cipher to `in` and stores the result into `out`.
/// WARNING: This function doesn't provide authenticated encryption.
/// Using the AEAD or one of the `box` versions is usually preferred.
pub fn xor(out: []u8, in: []const u8, counter: u64, key: [key_length]u8, nonce: [nonce_length]u8) void {
assert(in.len == out.len);
assert(in.len / 64 <= (1 << 64 - 1) - counter);
var cursor: usize = 0;
const k = keyToWords(key);
var c: [4]u32 = undefined;
c[0] = @as(u32, @truncate(counter));
c[1] = @as(u32, @truncate(counter >> 32));
c[2] = mem.readIntLittle(u32, nonce[0..4]);
c[3] = mem.readIntLittle(u32, nonce[4..8]);
const block_length = (1 << 6);
// The full block size is greater than the address space on a 32bit machine
const big_block = if (@sizeOf(usize) > 4) (block_length << 32) else maxInt(usize);
// first partial big block
if (((@as(u64, @intCast(maxInt(u32) - @as(u32, @truncate(counter)))) + 1) << 6) < in.len) {
ChaChaImpl(rounds_nb).chacha20Xor(out[cursor..big_block], in[cursor..big_block], k, c);
cursor = big_block - cursor;
c[1] += 1;
if (comptime @sizeOf(usize) > 4) {
// A big block is giant: 256 GiB, but we can avoid this limitation
var remaining_blocks: u32 = @as(u32, @intCast((in.len / big_block)));
while (remaining_blocks > 0) : (remaining_blocks -= 1) {
ChaChaImpl(rounds_nb).chacha20Xor(out[cursor .. cursor + big_block], in[cursor .. cursor + big_block], k, c);
c[1] += 1; // upper 32-bit of counter, generic chacha20Xor() doesn't know about this.
cursor += big_block;
}
}
}
ChaChaImpl(rounds_nb).chacha20Xor(out[cursor..], in[cursor..], k, c);
}
};
}
fn XChaChaIETF(comptime rounds_nb: usize) type {
return struct {
/// Nonce length in bytes.
pub const nonce_length = 24;
/// Key length in bytes.
pub const key_length = 32;
/// Add the output of the XChaCha20 stream cipher to `in` and stores the result into `out`.
/// WARNING: This function doesn't provide authenticated encryption.
/// Using the AEAD or one of the `box` versions is usually preferred.
pub fn xor(out: []u8, in: []const u8, counter: u32, key: [key_length]u8, nonce: [nonce_length]u8) void {
const extended = extend(key, nonce, rounds_nb);
ChaChaIETF(rounds_nb).xor(out, in, counter, extended.key, extended.nonce);
}
};
}
fn ChaChaPoly1305(comptime rounds_nb: usize) type {
return struct {
pub const tag_length = 16;
pub const nonce_length = 12;
pub const key_length = 32;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
assert(c.len == m.len);
var polyKey = [_]u8{0} ** 32;
ChaChaIETF(rounds_nb).xor(polyKey[0..], polyKey[0..], 0, k, npub);
ChaChaIETF(rounds_nb).xor(c[0..m.len], m, 1, k, npub);
var mac = Poly1305.init(polyKey[0..]);
mac.update(ad);
if (ad.len % 16 != 0) {
const zeros = [_]u8{0} ** 16;
const padding = 16 - (ad.len % 16);
mac.update(zeros[0..padding]);
}
mac.update(c[0..m.len]);
if (m.len % 16 != 0) {
const zeros = [_]u8{0} ** 16;
const padding = 16 - (m.len % 16);
mac.update(zeros[0..padding]);
}
var lens: [16]u8 = undefined;
mem.writeIntLittle(u64, lens[0..8], ad.len);
mem.writeIntLittle(u64, lens[8..16], m.len);
mac.update(lens[0..]);
mac.final(tag);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
/// NOTE: the check of the authentication tag is currently not done in constant time
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
var polyKey = [_]u8{0} ** 32;
ChaChaIETF(rounds_nb).xor(polyKey[0..], polyKey[0..], 0, k, npub);
var mac = Poly1305.init(polyKey[0..]);
mac.update(ad);
if (ad.len % 16 != 0) {
const zeros = [_]u8{0} ** 16;
const padding = 16 - (ad.len % 16);
mac.update(zeros[0..padding]);
}
mac.update(c);
if (c.len % 16 != 0) {
const zeros = [_]u8{0} ** 16;
const padding = 16 - (c.len % 16);
mac.update(zeros[0..padding]);
}
var lens: [16]u8 = undefined;
mem.writeIntLittle(u64, lens[0..8], ad.len);
mem.writeIntLittle(u64, lens[8..16], c.len);
mac.update(lens[0..]);
var computedTag: [16]u8 = undefined;
mac.final(computedTag[0..]);
var acc: u8 = 0;
for (computedTag, 0..) |_, i| {
acc |= computedTag[i] ^ tag[i];
}
if (acc != 0) {
return error.AuthenticationFailed;
}
ChaChaIETF(rounds_nb).xor(m[0..c.len], c, 1, k, npub);
}
};
}
fn XChaChaPoly1305(comptime rounds_nb: usize) type {
return struct {
pub const tag_length = 16;
pub const nonce_length = 24;
pub const key_length = 32;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
const extended = extend(k, npub, rounds_nb);
return ChaChaPoly1305(rounds_nb).encrypt(c, tag, m, ad, extended.nonce, extended.key);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
const extended = extend(k, npub, rounds_nb);
return ChaChaPoly1305(rounds_nb).decrypt(m, c, tag, ad, extended.nonce, extended.key);
}
};
}
test "chacha20 AEAD API" {
const aeads = [_]type{ ChaCha20Poly1305, XChaCha20Poly1305 };
const m = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";
const ad = "Additional data";
inline for (aeads) |aead| {
const key = [_]u8{69} ** aead.key_length;
const nonce = [_]u8{42} ** aead.nonce_length;
var c: [m.len]u8 = undefined;
var tag: [aead.tag_length]u8 = undefined;
var out: [m.len]u8 = undefined;
aead.encrypt(c[0..], tag[0..], m, ad, nonce, key);
try aead.decrypt(out[0..], c[0..], tag, ad[0..], nonce, key);
try testing.expectEqualSlices(u8, out[0..], m);
c[0] += 1;
try testing.expectError(error.AuthenticationFailed, aead.decrypt(out[0..], c[0..], tag, ad[0..], nonce, key));
}
}
// https://tools.ietf.org/html/rfc7539#section-2.4.2
test "crypto.chacha20 test vector sunscreen" {
const expected_result = [_]u8{
0x6e, 0x2e, 0x35, 0x9a, 0x25, 0x68, 0xf9, 0x80,
0x41, 0xba, 0x07, 0x28, 0xdd, 0x0d, 0x69, 0x81,
0xe9, 0x7e, 0x7a, 0xec, 0x1d, 0x43, 0x60, 0xc2,
0x0a, 0x27, 0xaf, 0xcc, 0xfd, 0x9f, 0xae, 0x0b,
0xf9, 0x1b, 0x65, 0xc5, 0x52, 0x47, 0x33, 0xab,
0x8f, 0x59, 0x3d, 0xab, 0xcd, 0x62, 0xb3, 0x57,
0x16, 0x39, 0xd6, 0x24, 0xe6, 0x51, 0x52, 0xab,
0x8f, 0x53, 0x0c, 0x35, 0x9f, 0x08, 0x61, 0xd8,
0x07, 0xca, 0x0d, 0xbf, 0x50, 0x0d, 0x6a, 0x61,
0x56, 0xa3, 0x8e, 0x08, 0x8a, 0x22, 0xb6, 0x5e,
0x52, 0xbc, 0x51, 0x4d, 0x16, 0xcc, 0xf8, 0x06,
0x81, 0x8c, 0xe9, 0x1a, 0xb7, 0x79, 0x37, 0x36,
0x5a, 0xf9, 0x0b, 0xbf, 0x74, 0xa3, 0x5b, 0xe6,
0xb4, 0x0b, 0x8e, 0xed, 0xf2, 0x78, 0x5e, 0x42,
0x87, 0x4d,
};
const m = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";
var result: [114]u8 = undefined;
const key = [_]u8{
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
};
const nonce = [_]u8{
0, 0, 0, 0,
0, 0, 0, 0x4a,
0, 0, 0, 0,
};
ChaCha20IETF.xor(result[0..], m[0..], 1, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
var m2: [114]u8 = undefined;
ChaCha20IETF.xor(m2[0..], result[0..], 1, key, nonce);
try testing.expect(mem.order(u8, m, &m2) == .eq);
}
// https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7
test "crypto.chacha20 test vector 1" {
const expected_result = [_]u8{
0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90,
0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28,
0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a,
0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7,
0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d,
0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37,
0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,
0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86,
};
const m = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 2" {
const expected_result = [_]u8{
0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96,
0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96,
0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60,
0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41,
0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2,
0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c,
0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81,
0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63,
};
const m = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 3" {
const expected_result = [_]u8{
0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5,
0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a,
0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13,
0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31,
0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45,
0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b,
0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e,
0x44, 0x5f, 0x41, 0xe3,
};
const m = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
var result: [60]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 1 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 4" {
const expected_result = [_]u8{
0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb,
0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80,
0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac,
0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32,
0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c,
0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54,
0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d,
0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b,
};
const m = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 5" {
const expected_result = [_]u8{
0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69,
0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75,
0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93,
0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1,
0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41,
0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69,
0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1,
0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a,
0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94,
0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66,
0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58,
0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd,
0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56,
0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e,
0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e,
0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7,
0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15,
0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3,
0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a,
0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25,
0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5,
0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69,
0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4,
0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7,
0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79,
0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a,
0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a,
0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2,
0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a,
0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09,
0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a,
0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9,
};
const m = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
var result: [256]u8 = undefined;
const key = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
};
const nonce = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
};
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "seal" {
{
const m = "";
const ad = "";
const key = [_]u8{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
};
const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 };
const exp_out = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 };
var out: [exp_out.len]u8 = undefined;
ChaCha20Poly1305.encrypt(out[0..m.len], out[m.len..], m, ad, nonce, key);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
{
const m = [_]u8{
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73,
0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63,
0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f,
0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73,
0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,
0x74, 0x2e,
};
const ad = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 };
const key = [_]u8{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
};
const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 };
const exp_out = [_]u8{
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,
0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,
0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,
0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,
0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58,
0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,
0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60,
0x6, 0x91,
};
var out: [exp_out.len]u8 = undefined;
ChaCha20Poly1305.encrypt(out[0..m.len], out[m.len..], m[0..], ad[0..], nonce, key);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
test "open" {
{
const c = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 };
const ad = "";
const key = [_]u8{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
};
const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 };
const exp_out = "";
var out: [exp_out.len]u8 = undefined;
try ChaCha20Poly1305.decrypt(out[0..], c[0..exp_out.len], c[exp_out.len..].*, ad[0..], nonce, key);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
{
const c = [_]u8{
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,
0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,
0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,
0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,
0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58,
0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,
0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60,
0x6, 0x91,
};
const ad = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 };
const key = [_]u8{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
};
const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 };
const exp_out = [_]u8{
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73,
0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63,
0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f,
0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73,
0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,
0x74, 0x2e,
};
var out: [exp_out.len]u8 = undefined;
try ChaCha20Poly1305.decrypt(out[0..], c[0..exp_out.len], c[exp_out.len..].*, ad[0..], nonce, key);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
// corrupting the ciphertext, data, key, or nonce should cause a failure
var bad_c = c;
bad_c[0] ^= 1;
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], bad_c[0..out.len], bad_c[out.len..].*, ad[0..], nonce, key));
var bad_ad = ad;
bad_ad[0] ^= 1;
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, bad_ad[0..], nonce, key));
var bad_key = key;
bad_key[0] ^= 1;
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], nonce, bad_key));
var bad_nonce = nonce;
bad_nonce[0] ^= 1;
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], bad_nonce, key));
}
}
test "crypto.xchacha20" {
const key = [_]u8{69} ** 32;
const nonce = [_]u8{42} ** 24;
const m = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";
{
var c: [m.len]u8 = undefined;
XChaCha20IETF.xor(c[0..], m[0..], 0, key, nonce);
var buf: [2 * c.len]u8 = undefined;
try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE167C240D");
}
{
const ad = "Additional data";
var c: [m.len + XChaCha20Poly1305.tag_length]u8 = undefined;
XChaCha20Poly1305.encrypt(c[0..m.len], c[m.len..], m, ad, nonce, key);
var out: [m.len]u8 = undefined;
try XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key);
var buf: [2 * c.len]u8 = undefined;
try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234");
try testing.expectEqualSlices(u8, out[0..], m);
c[0] += 1;
try testing.expectError(error.AuthenticationFailed, XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key));
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/sha3.zig | const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const debug = std.debug;
const htest = @import("test.zig");
pub const Sha3_224 = Keccak(224, 0x06);
pub const Sha3_256 = Keccak(256, 0x06);
pub const Sha3_384 = Keccak(384, 0x06);
pub const Sha3_512 = Keccak(512, 0x06);
pub const Keccak_256 = Keccak(256, 0x01);
pub const Keccak_512 = Keccak(512, 0x01);
fn Keccak(comptime bits: usize, comptime delim: u8) type {
return struct {
const Self = @This();
pub const block_length = 200;
pub const digest_length = bits / 8;
pub const Options = struct {};
s: [200]u8,
offset: usize,
rate: usize,
pub fn init(options: Options) Self {
_ = options;
return Self{ .s = [_]u8{0} ** 200, .offset = 0, .rate = 200 - (bits / 4) };
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Self.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var ip: usize = 0;
var len = b.len;
var rate = d.rate - d.offset;
var offset = d.offset;
// absorb
while (len >= rate) {
for (d.s[offset .. offset + rate], 0..) |*r, i|
r.* ^= b[ip..][i];
keccakF(1600, &d.s);
ip += rate;
len -= rate;
rate = d.rate;
offset = 0;
}
for (d.s[offset .. offset + len], 0..) |*r, i|
r.* ^= b[ip..][i];
d.offset = offset + len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// padding
d.s[d.offset] ^= delim;
d.s[d.rate - 1] ^= 0x80;
keccakF(1600, &d.s);
// squeeze
var op: usize = 0;
var len: usize = bits / 8;
while (len >= d.rate) {
mem.copy(u8, out[op..], d.s[0..d.rate]);
keccakF(1600, &d.s);
op += d.rate;
len -= d.rate;
}
mem.copy(u8, out[op..], d.s[0..len]);
}
};
}
const RC = [_]u64{
0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000,
0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003,
0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a,
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
};
const ROTC = [_]usize{
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44,
};
const PIL = [_]usize{
10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1,
};
const M5 = [_]usize{
0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
};
fn keccakF(comptime F: usize, d: *[F / 8]u8) void {
const B = F / 25;
const no_rounds = comptime x: {
break :x 12 + 2 * math.log2(B);
};
var s = [_]u64{0} ** 25;
var t = [_]u64{0} ** 1;
var c = [_]u64{0} ** 5;
for (s, 0..) |*r, i| {
r.* = mem.readIntLittle(u64, d[8 * i ..][0..8]);
}
comptime var x: usize = 0;
comptime var y: usize = 0;
for (RC[0..no_rounds]) |round| {
// theta
x = 0;
inline while (x < 5) : (x += 1) {
c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20];
}
x = 0;
inline while (x < 5) : (x += 1) {
t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], @as(usize, 1));
y = 0;
inline while (y < 5) : (y += 1) {
s[x + y * 5] ^= t[0];
}
}
// rho+pi
t[0] = s[1];
x = 0;
inline while (x < 24) : (x += 1) {
c[0] = s[PIL[x]];
s[PIL[x]] = math.rotl(u64, t[0], ROTC[x]);
t[0] = c[0];
}
// chi
y = 0;
inline while (y < 5) : (y += 1) {
x = 0;
inline while (x < 5) : (x += 1) {
c[x] = s[x + y * 5];
}
x = 0;
inline while (x < 5) : (x += 1) {
s[x + y * 5] = c[x] ^ (~c[M5[x + 1]] & c[M5[x + 2]]);
}
}
// iota
s[0] ^= round;
}
for (s, 0..) |r, i| {
mem.writeIntLittle(u64, d[8 * i ..][0..8], r);
}
}
test "sha3-224 single" {
try htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", "");
try htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc");
try htest.assertEqualHash(Sha3_224, "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-224 streaming" {
var h = Sha3_224.init(.{});
var out: [28]u8 = undefined;
h.final(out[0..]);
try htest.assertEqual("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", out[0..]);
h = Sha3_224.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
h = Sha3_224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
}
test "sha3-256 single" {
try htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", "");
try htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc");
try htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-256 streaming" {
var h = Sha3_256.init(.{});
var out: [32]u8 = undefined;
h.final(out[0..]);
try htest.assertEqual("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", out[0..]);
h = Sha3_256.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
h = Sha3_256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
}
test "sha3-256 aligned final" {
var block = [_]u8{0} ** Sha3_256.block_length;
var out: [Sha3_256.digest_length]u8 = undefined;
var h = Sha3_256.init(.{});
h.update(&block);
h.final(out[0..]);
}
test "sha3-384 single" {
const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004";
try htest.assertEqualHash(Sha3_384, h1, "");
const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25";
try htest.assertEqualHash(Sha3_384, h2, "abc");
const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7";
try htest.assertEqualHash(Sha3_384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-384 streaming" {
var h = Sha3_384.init(.{});
var out: [48]u8 = undefined;
const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25";
h = Sha3_384.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha3_384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha3-512 single" {
const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26";
try htest.assertEqualHash(Sha3_512, h1, "");
const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
try htest.assertEqualHash(Sha3_512, h2, "abc");
const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185";
try htest.assertEqualHash(Sha3_512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-512 streaming" {
var h = Sha3_512.init(.{});
var out: [64]u8 = undefined;
const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
h = Sha3_512.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha3_512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha3-512 aligned final" {
var block = [_]u8{0} ** Sha3_512.block_length;
var out: [Sha3_512.digest_length]u8 = undefined;
var h = Sha3_512.init(.{});
h.update(&block);
h.final(out[0..]);
}
test "keccak-256 single" {
try htest.assertEqualHash(Keccak_256, "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "");
try htest.assertEqualHash(Keccak_256, "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45", "abc");
try htest.assertEqualHash(Keccak_256, "f519747ed599024f3882238e5ab43960132572b7345fbeb9a90769dafd21ad67", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "keccak-512 single" {
try htest.assertEqualHash(Keccak_512, "0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e", "");
try htest.assertEqualHash(Keccak_512, "18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96", "abc");
try htest.assertEqualHash(Keccak_512, "ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/errors.zig | /// MAC verification failed - The tag doesn't verify for the given ciphertext and secret key
pub const AuthenticationError = error{AuthenticationFailed};
/// The requested output length is too long for the chosen algorithm
pub const OutputTooLongError = error{OutputTooLong};
/// Finite field operation returned the identity element
pub const IdentityElementError = error{IdentityElement};
/// Encoded input cannot be decoded
pub const EncodingError = error{InvalidEncoding};
/// The signature does't verify for the given message and public key
pub const SignatureVerificationError = error{SignatureVerificationFailed};
/// Both a public and secret key have been provided, but they are incompatible
pub const KeyMismatchError = error{KeyMismatch};
/// Encoded input is not in canonical form
pub const NonCanonicalError = error{NonCanonical};
/// Square root has no solutions
pub const NotSquareError = error{NotSquare};
/// Verification string doesn't match the provided password and parameters
pub const PasswordVerificationError = error{PasswordVerificationFailed};
/// Parameters would be insecure to use
pub const WeakParametersError = error{WeakParameters};
/// Public key would be insecure to use
pub const WeakPublicKeyError = error{WeakPublicKey};
/// Any error related to cryptography operations
pub const Error = AuthenticationError || OutputTooLongError || IdentityElementError || EncodingError || SignatureVerificationError || KeyMismatchError || NonCanonicalError || NotSquareError || PasswordVerificationError || WeakParametersError || WeakPublicKeyError;
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/tlcsprng.zig | //! Thread-local cryptographically secure pseudo-random number generator.
//! This file has public declarations that are intended to be used internally
//! by the standard library; this namespace is not intended to be exposed
//! directly to standard library users.
const std = @import("std");
const builtin = @import("builtin");
const root = @import("root");
const mem = std.mem;
const os = std.os;
/// We use this as a layer of indirection because global const pointers cannot
/// point to thread-local variables.
pub const interface = std.rand.Random{
.ptr = undefined,
.fillFn = tlsCsprngFill,
};
const os_has_fork = switch (builtin.os.tag) {
.dragonfly,
.freebsd,
.ios,
.kfreebsd,
.linux,
.macos,
.netbsd,
.openbsd,
.solaris,
.tvos,
.watchos,
.haiku,
=> true,
else => false,
};
const os_has_arc4random = builtin.link_libc and @hasDecl(std.c, "arc4random_buf");
const want_fork_safety = os_has_fork and !os_has_arc4random and
(std.meta.globalOption("crypto_fork_safety", bool) orelse true);
const maybe_have_wipe_on_fork = builtin.os.isAtLeast(.linux, .{
.major = 4,
.minor = 14,
}) orelse true;
const Context = struct {
init_state: enum(u8) { uninitialized = 0, initialized, failed },
gimli: std.crypto.core.Gimli,
};
var install_atfork_handler = std.once(struct {
// Install the global handler only once.
// The same handler is shared among threads and is inherinted by fork()-ed
// processes.
fn do() void {
const r = std.c.pthread_atfork(null, null, childAtForkHandler);
std.debug.assert(r == 0);
}
}.do);
threadlocal var wipe_mem: []align(mem.page_size) u8 = &[_]u8{};
fn tlsCsprngFill(_: *anyopaque, buffer: []u8) void {
if (builtin.link_libc and @hasDecl(std.c, "arc4random_buf")) {
// arc4random is already a thread-local CSPRNG.
return std.c.arc4random_buf(buffer.ptr, buffer.len);
}
// Allow applications to decide they would prefer to have every call to
// std.crypto.random always make an OS syscall, rather than rely on an
// application implementation of a CSPRNG.
if (comptime std.meta.globalOption("crypto_always_getrandom", bool) orelse false) {
return fillWithOsEntropy(buffer);
}
if (wipe_mem.len == 0) {
// Not initialized yet.
if (want_fork_safety and maybe_have_wipe_on_fork) {
// Allocate a per-process page, madvise operates with page
// granularity.
wipe_mem = os.mmap(
null,
@sizeOf(Context),
os.PROT.READ | os.PROT.WRITE,
os.MAP.PRIVATE | os.MAP.ANONYMOUS,
-1,
0,
) catch {
// Could not allocate memory for the local state, fall back to
// the OS syscall.
return fillWithOsEntropy(buffer);
};
// The memory is already zero-initialized.
} else {
// Use a static thread-local buffer.
const S = struct {
threadlocal var buf: Context align(mem.page_size) = .{
.init_state = .uninitialized,
.gimli = undefined,
};
};
wipe_mem = mem.asBytes(&S.buf);
}
}
const ctx = @as(*Context, @ptrCast(wipe_mem.ptr));
switch (ctx.init_state) {
.uninitialized => {
if (!want_fork_safety) {
return initAndFill(buffer);
}
if (maybe_have_wipe_on_fork) wof: {
// Qemu user-mode emulation ignores any valid/invalid madvise
// hint and returns success. Check if this is the case by
// passing bogus parameters, we expect EINVAL as result.
if (os.madvise(wipe_mem.ptr, 0, 0xffffffff)) |_| {
break :wof;
} else |_| {}
if (os.madvise(wipe_mem.ptr, wipe_mem.len, os.MADV.WIPEONFORK)) |_| {
return initAndFill(buffer);
} else |_| {}
}
if (std.Thread.use_pthreads) {
return setupPthreadAtforkAndFill(buffer);
}
// Since we failed to set up fork safety, we fall back to always
// calling getrandom every time.
ctx.init_state = .failed;
return fillWithOsEntropy(buffer);
},
.initialized => {
return fillWithCsprng(buffer);
},
.failed => {
if (want_fork_safety) {
return fillWithOsEntropy(buffer);
} else {
unreachable;
}
},
}
}
fn setupPthreadAtforkAndFill(buffer: []u8) void {
install_atfork_handler.call();
return initAndFill(buffer);
}
fn childAtForkHandler() callconv(.C) void {
// The atfork handler is global, this function may be called after
// fork()-ing threads that never initialized the CSPRNG context.
if (wipe_mem.len == 0) return;
std.crypto.utils.secureZero(u8, wipe_mem);
}
fn fillWithCsprng(buffer: []u8) void {
const ctx = @as(*Context, @ptrCast(wipe_mem.ptr));
if (buffer.len != 0) {
ctx.gimli.squeeze(buffer);
} else {
ctx.gimli.permute();
}
mem.set(u8, ctx.gimli.toSlice()[0..std.crypto.core.Gimli.RATE], 0);
}
fn fillWithOsEntropy(buffer: []u8) void {
os.getrandom(buffer) catch @panic("getrandom() failed to provide entropy");
}
fn initAndFill(buffer: []u8) void {
var seed: [std.crypto.core.Gimli.BLOCKBYTES]u8 = undefined;
// Because we panic on getrandom() failing, we provide the opportunity
// to override the default seed function. This also makes
// `std.crypto.random` available on freestanding targets, provided that
// the `cryptoRandomSeed` function is provided.
if (@hasDecl(root, "cryptoRandomSeed")) {
root.cryptoRandomSeed(&seed);
} else {
fillWithOsEntropy(&seed);
}
const ctx = @as(*Context, @ptrCast(wipe_mem.ptr));
ctx.gimli = std.crypto.core.Gimli.init(seed);
// This is at the end so that accidental recursive dependencies result
// in stack overflows instead of invalid random data.
ctx.init_state = .initialized;
return fillWithCsprng(buffer);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/blake2.zig | const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const debug = std.debug;
const htest = @import("test.zig");
const RoundParam = struct {
a: usize,
b: usize,
c: usize,
d: usize,
x: usize,
y: usize,
};
fn roundParam(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam {
return RoundParam{
.a = a,
.b = b,
.c = c,
.d = d,
.x = x,
.y = y,
};
}
/////////////////////
// Blake2s
pub const Blake2s128 = Blake2s(128);
pub const Blake2s160 = Blake2s(160);
pub const Blake2s224 = Blake2s(224);
pub const Blake2s256 = Blake2s(256);
pub fn Blake2s(comptime out_bits: usize) type {
return struct {
const Self = @This();
pub const block_length = 64;
pub const digest_length = out_bits / 8;
pub const key_length_min = 0;
pub const key_length_max = 32;
pub const key_length = 32; // recommended key length
pub const Options = struct { key: ?[]const u8 = null, salt: ?[8]u8 = null, context: ?[8]u8 = null, expected_out_bits: usize = out_bits };
const iv = [8]u32{
0x6A09E667,
0xBB67AE85,
0x3C6EF372,
0xA54FF53A,
0x510E527F,
0x9B05688C,
0x1F83D9AB,
0x5BE0CD19,
};
const sigma = [10][16]u8{
[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
[_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
[_]u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
[_]u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
[_]u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
[_]u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
[_]u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
[_]u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
[_]u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
[_]u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
};
h: [8]u32,
t: u64,
// Streaming cache
buf: [64]u8,
buf_len: u8,
pub fn init(options: Options) Self {
comptime debug.assert(8 <= out_bits and out_bits <= 256);
var d: Self = undefined;
mem.copy(u32, d.h[0..], iv[0..]);
const key_len = if (options.key) |key| key.len else 0;
// default parameters
d.h[0] ^= 0x01010000 ^ @as(u32, @truncate(key_len << 8)) ^ @as(u32, @intCast(options.expected_out_bits >> 3));
d.t = 0;
d.buf_len = 0;
if (options.salt) |salt| {
d.h[4] ^= mem.readIntLittle(u32, salt[0..4]);
d.h[5] ^= mem.readIntLittle(u32, salt[4..8]);
}
if (options.context) |context| {
d.h[6] ^= mem.readIntLittle(u32, context[0..4]);
d.h[7] ^= mem.readIntLittle(u32, context[4..8]);
}
if (key_len > 0) {
mem.set(u8, d.buf[key_len..], 0);
d.update(options.key.?);
d.buf_len = 64;
}
return d;
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Self.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len > 64) {
off += 64 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.t += 64;
d.round(d.buf[0..], false);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 64 < b.len) : (off += 64) {
d.t += 64;
d.round(b[off..][0..64], false);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
mem.set(u8, d.buf[d.buf_len..], 0);
d.t += d.buf_len;
d.round(d.buf[0..], true);
for (d.h) |*x| x.* = mem.nativeToLittle(u32, x.*);
mem.copy(u8, out[0..], @as(*[digest_length]u8, @ptrCast(&d.h)));
}
fn round(d: *Self, b: *const [64]u8, last: bool) void {
var m: [16]u32 = undefined;
var v: [16]u32 = undefined;
for (m, 0..) |*r, i| {
r.* = mem.readIntLittle(u32, b[4 * i ..][0..4]);
}
var k: usize = 0;
while (k < 8) : (k += 1) {
v[k] = d.h[k];
v[k + 8] = iv[k];
}
v[12] ^= @as(u32, @truncate(d.t));
v[13] ^= @as(u32, @intCast(d.t >> 32));
if (last) v[14] = ~v[14];
const rounds = comptime [_]RoundParam{
roundParam(0, 4, 8, 12, 0, 1),
roundParam(1, 5, 9, 13, 2, 3),
roundParam(2, 6, 10, 14, 4, 5),
roundParam(3, 7, 11, 15, 6, 7),
roundParam(0, 5, 10, 15, 8, 9),
roundParam(1, 6, 11, 12, 10, 11),
roundParam(2, 7, 8, 13, 12, 13),
roundParam(3, 4, 9, 14, 14, 15),
};
comptime var j: usize = 0;
inline while (j < 10) : (j += 1) {
inline for (rounds) |r| {
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]];
v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 16));
v[r.c] = v[r.c] +% v[r.d];
v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 12));
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]];
v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 8));
v[r.c] = v[r.c] +% v[r.d];
v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 7));
}
}
for (d.h, 0..) |*r, i| {
r.* ^= v[i] ^ v[i + 8];
}
}
};
}
test "blake2s160 single" {
const h1 = "354c9c33f735962418bdacb9479873429c34916f";
try htest.assertEqualHash(Blake2s160, h1, "");
const h2 = "5ae3b99be29b01834c3b508521ede60438f8de17";
try htest.assertEqualHash(Blake2s160, h2, "abc");
const h3 = "5a604fec9713c369e84b0ed68daed7d7504ef240";
try htest.assertEqualHash(Blake2s160, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "b60c4dc60e2681e58fbc24e77f07e02c69e72ed0";
try htest.assertEqualHash(Blake2s160, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s160 streaming" {
var h = Blake2s160.init(.{});
var out: [20]u8 = undefined;
const h1 = "354c9c33f735962418bdacb9479873429c34916f";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "5ae3b99be29b01834c3b508521ede60438f8de17";
h = Blake2s160.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s160.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "b60c4dc60e2681e58fbc24e77f07e02c69e72ed0";
h = Blake2s160.init(.{});
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s160.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "4667fd60791a7fe41f939bca646b4529e296bd68";
h = Blake2s160.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2s160.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2s160" {
//comptime
{
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2s160.block_length;
var out: [Blake2s160.digest_length]u8 = undefined;
const h1 = "2c56ad9d0b2c8b474aafa93ab307db2f0940105f";
try htest.assertEqualHash(Blake2s160, h1, block[0..]);
var h = Blake2s160.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2s224 single" {
const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4";
try htest.assertEqualHash(Blake2s224, h1, "");
const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55";
try htest.assertEqualHash(Blake2s224, h2, "abc");
const h3 = "e4e5cb6c7cae41982b397bf7b7d2d9d1949823ae78435326e8db4912";
try htest.assertEqualHash(Blake2s224, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01";
try htest.assertEqualHash(Blake2s224, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s224 streaming" {
var h = Blake2s224.init(.{});
var out: [28]u8 = undefined;
const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55";
h = Blake2s224.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01";
h = Blake2s224.init(.{});
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s224.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "a4d6a9d253441b80e5dfd60a04db169ffab77aec56a2855c402828c3";
h = Blake2s224.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2s224.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2s224" {
comptime {
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2s224.block_length;
var out: [Blake2s224.digest_length]u8 = undefined;
const h1 = "86b7611563293f8c73627df7a6d6ba25ca0548c2a6481f7d116ee576";
try htest.assertEqualHash(Blake2s224, h1, block[0..]);
var h = Blake2s224.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2s256 single" {
const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9";
try htest.assertEqualHash(Blake2s256, h1, "");
const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982";
try htest.assertEqualHash(Blake2s256, h2, "abc");
const h3 = "606beeec743ccbeff6cbcdf5d5302aa855c256c29b88c8ed331ea1a6bf3c8812";
try htest.assertEqualHash(Blake2s256, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977";
try htest.assertEqualHash(Blake2s256, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s256 streaming" {
var h = Blake2s256.init(.{});
var out: [32]u8 = undefined;
const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982";
h = Blake2s256.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977";
h = Blake2s256.init(.{});
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s256.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
}
test "blake2s256 keyed" {
var out: [32]u8 = undefined;
const h1 = "10f918da4d74fab3302e48a5d67d03804b1ec95372a62a0f33b7c9fa28ba1ae6";
const key = "secret_key";
Blake2s256.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key });
try htest.assertEqual(h1, out[0..]);
var h = Blake2s256.init(.{ .key = key });
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
h = Blake2s256.init(.{ .key = key });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
test "comptime blake2s256" {
comptime {
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2s256.block_length;
var out: [Blake2s256.digest_length]u8 = undefined;
const h1 = "ae09db7cd54f42b490ef09b6bc541af688e4959bb8c53f359a6f56e38ab454a3";
try htest.assertEqualHash(Blake2s256, h1, block[0..]);
var h = Blake2s256.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
/////////////////////
// Blake2b
pub const Blake2b128 = Blake2b(128);
pub const Blake2b160 = Blake2b(160);
pub const Blake2b256 = Blake2b(256);
pub const Blake2b384 = Blake2b(384);
pub const Blake2b512 = Blake2b(512);
pub fn Blake2b(comptime out_bits: usize) type {
return struct {
const Self = @This();
pub const block_length = 128;
pub const digest_length = out_bits / 8;
pub const key_length_min = 0;
pub const key_length_max = 64;
pub const key_length = 32; // recommended key length
pub const Options = struct { key: ?[]const u8 = null, salt: ?[16]u8 = null, context: ?[16]u8 = null, expected_out_bits: usize = out_bits };
const iv = [8]u64{
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179,
};
const sigma = [12][16]u8{
[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
[_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
[_]u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
[_]u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
[_]u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
[_]u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
[_]u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
[_]u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
[_]u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
[_]u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
[_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
};
h: [8]u64,
t: u128,
// Streaming cache
buf: [128]u8,
buf_len: u8,
pub fn init(options: Options) Self {
comptime debug.assert(8 <= out_bits and out_bits <= 512);
var d: Self = undefined;
mem.copy(u64, d.h[0..], iv[0..]);
const key_len = if (options.key) |key| key.len else 0;
// default parameters
d.h[0] ^= 0x01010000 ^ (key_len << 8) ^ (options.expected_out_bits >> 3);
d.t = 0;
d.buf_len = 0;
if (options.salt) |salt| {
d.h[4] ^= mem.readIntLittle(u64, salt[0..8]);
d.h[5] ^= mem.readIntLittle(u64, salt[8..16]);
}
if (options.context) |context| {
d.h[6] ^= mem.readIntLittle(u64, context[0..8]);
d.h[7] ^= mem.readIntLittle(u64, context[8..16]);
}
if (key_len > 0) {
mem.set(u8, d.buf[key_len..], 0);
d.update(options.key.?);
d.buf_len = 128;
}
return d;
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Self.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len > 128) {
off += 128 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.t += 128;
d.round(d.buf[0..], false);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 128 < b.len) : (off += 128) {
d.t += 128;
d.round(b[off..][0..128], false);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
mem.set(u8, d.buf[d.buf_len..], 0);
d.t += d.buf_len;
d.round(d.buf[0..], true);
for (d.h) |*x| x.* = mem.nativeToLittle(u64, x.*);
mem.copy(u8, out[0..], @as(*[digest_length]u8, @ptrCast(&d.h)));
}
fn round(d: *Self, b: *const [128]u8, last: bool) void {
var m: [16]u64 = undefined;
var v: [16]u64 = undefined;
for (m, 0..) |*r, i| {
r.* = mem.readIntLittle(u64, b[8 * i ..][0..8]);
}
var k: usize = 0;
while (k < 8) : (k += 1) {
v[k] = d.h[k];
v[k + 8] = iv[k];
}
v[12] ^= @as(u64, @truncate(d.t));
v[13] ^= @as(u64, @intCast(d.t >> 64));
if (last) v[14] = ~v[14];
const rounds = comptime [_]RoundParam{
roundParam(0, 4, 8, 12, 0, 1),
roundParam(1, 5, 9, 13, 2, 3),
roundParam(2, 6, 10, 14, 4, 5),
roundParam(3, 7, 11, 15, 6, 7),
roundParam(0, 5, 10, 15, 8, 9),
roundParam(1, 6, 11, 12, 10, 11),
roundParam(2, 7, 8, 13, 12, 13),
roundParam(3, 4, 9, 14, 14, 15),
};
comptime var j: usize = 0;
inline while (j < 12) : (j += 1) {
inline for (rounds) |r| {
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]];
v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 32));
v[r.c] = v[r.c] +% v[r.d];
v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 24));
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]];
v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 16));
v[r.c] = v[r.c] +% v[r.d];
v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 63));
}
}
for (d.h, 0..) |*r, i| {
r.* ^= v[i] ^ v[i + 8];
}
}
};
}
test "blake2b160 single" {
const h1 = "3345524abf6bbe1809449224b5972c41790b6cf2";
try htest.assertEqualHash(Blake2b160, h1, "");
const h2 = "384264f676f39536840523f284921cdc68b6846b";
try htest.assertEqualHash(Blake2b160, h2, "abc");
const h3 = "3c523ed102ab45a37d54f5610d5a983162fde84f";
try htest.assertEqualHash(Blake2b160, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "43758f5de1740f651f1ae39de92260fe8bd5a11f";
try htest.assertEqualHash(Blake2b160, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b160 streaming" {
var h = Blake2b160.init(.{});
var out: [20]u8 = undefined;
const h1 = "3345524abf6bbe1809449224b5972c41790b6cf2";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "384264f676f39536840523f284921cdc68b6846b";
h = Blake2b160.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b160.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "43758f5de1740f651f1ae39de92260fe8bd5a11f";
h = Blake2b160.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b160.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b160.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "72328f8a8200663752fc302d372b5dd9b49dd8dc";
h = Blake2b160.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2b160.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2b160" {
comptime {
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2b160.block_length;
var out: [Blake2b160.digest_length]u8 = undefined;
const h1 = "8d26f158f564e3293b42f5e3d34263cb173aa9c9";
try htest.assertEqualHash(Blake2b160, h1, block[0..]);
var h = Blake2b160.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2b384 single" {
const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100";
try htest.assertEqualHash(Blake2b384, h1, "");
const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4";
try htest.assertEqualHash(Blake2b384, h2, "abc");
const h3 = "b7c81b228b6bd912930e8f0b5387989691c1cee1e65aade4da3b86a3c9f678fc8018f6ed9e2906720c8d2a3aeda9c03d";
try htest.assertEqualHash(Blake2b384, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c";
try htest.assertEqualHash(Blake2b384, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b384 streaming" {
var h = Blake2b384.init(.{});
var out: [48]u8 = undefined;
const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4";
h = Blake2b384.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c";
h = Blake2b384.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b384.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b384.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "934c48fcb197031c71f583d92f98703510805e72142e0b46f5752d1e971bc86c355d556035613ff7a4154b4de09dac5c";
h = Blake2b384.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2b384.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2b384" {
comptime {
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2b384.block_length;
var out: [Blake2b384.digest_length]u8 = undefined;
const h1 = "e8aa1931ea0422e4446fecdd25c16cf35c240b10cb4659dd5c776eddcaa4d922397a589404b46eb2e53d78132d05fd7d";
try htest.assertEqualHash(Blake2b384, h1, block[0..]);
var h = Blake2b384.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2b512 single" {
const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce";
try htest.assertEqualHash(Blake2b512, h1, "");
const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
try htest.assertEqualHash(Blake2b512, h2, "abc");
const h3 = "a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918";
try htest.assertEqualHash(Blake2b512, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920";
try htest.assertEqualHash(Blake2b512, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b512 streaming" {
var h = Blake2b512.init(.{});
var out: [64]u8 = undefined;
const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce";
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
h = Blake2b512.init(.{});
h.update("abc");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920";
h = Blake2b512.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b512.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h3, out[0..]);
}
test "blake2b512 keyed" {
var out: [64]u8 = undefined;
const h1 = "8a978060ccaf582f388f37454363071ac9a67e3a704585fd879fb8a419a447e389c7c6de790faa20a7a7dccf197de736bc5b40b98a930b36df5bee7555750c4d";
const key = "secret_key";
Blake2b512.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key });
try htest.assertEqual(h1, out[0..]);
var h = Blake2b512.init(.{ .key = key });
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
h = Blake2b512.init(.{ .key = key });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
test "comptime blake2b512" {
comptime {
@setEvalBranchQuota(10000);
var block = [_]u8{0} ** Blake2b512.block_length;
var out: [Blake2b512.digest_length]u8 = undefined;
const h1 = "865939e120e6805438478841afb739ae4250cf372653078a065cdcfffca4caf798e6d462b65d658fc165782640eded70963449ae1500fb0f24981d7727e22c41";
try htest.assertEqualHash(Blake2b512, h1, block[0..]);
var h = Blake2b512.init(.{});
h.update(&block);
h.final(out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/hmac.zig | const std = @import("../std.zig");
const crypto = std.crypto;
const debug = std.debug;
const mem = std.mem;
pub const HmacMd5 = Hmac(crypto.hash.Md5);
pub const HmacSha1 = Hmac(crypto.hash.Sha1);
pub const sha2 = struct {
pub const HmacSha224 = Hmac(crypto.hash.sha2.Sha224);
pub const HmacSha256 = Hmac(crypto.hash.sha2.Sha256);
pub const HmacSha384 = Hmac(crypto.hash.sha2.Sha384);
pub const HmacSha512 = Hmac(crypto.hash.sha2.Sha512);
};
pub fn Hmac(comptime Hash: type) type {
return struct {
const Self = @This();
pub const mac_length = Hash.digest_length;
pub const key_length_min = 0;
pub const key_length = 32; // recommended key length
o_key_pad: [Hash.block_length]u8,
hash: Hash,
// HMAC(k, m) = H(o_key_pad || H(i_key_pad || msg)) where || is concatenation
pub fn create(out: *[mac_length]u8, msg: []const u8, key: []const u8) void {
var ctx = Self.init(key);
ctx.update(msg);
ctx.final(out);
}
pub fn init(key: []const u8) Self {
var ctx: Self = undefined;
var scratch: [Hash.block_length]u8 = undefined;
var i_key_pad: [Hash.block_length]u8 = undefined;
// Normalize key length to block size of hash
if (key.len > Hash.block_length) {
Hash.hash(key, scratch[0..mac_length], .{});
mem.set(u8, scratch[mac_length..Hash.block_length], 0);
} else if (key.len < Hash.block_length) {
mem.copy(u8, scratch[0..key.len], key);
mem.set(u8, scratch[key.len..Hash.block_length], 0);
} else {
mem.copy(u8, scratch[0..], key);
}
for (ctx.o_key_pad, 0..) |*b, i| {
b.* = scratch[i] ^ 0x5c;
}
for (i_key_pad, 0..) |*b, i| {
b.* = scratch[i] ^ 0x36;
}
ctx.hash = Hash.init(.{});
ctx.hash.update(&i_key_pad);
return ctx;
}
pub fn update(ctx: *Self, msg: []const u8) void {
ctx.hash.update(msg);
}
pub fn final(ctx: *Self, out: *[mac_length]u8) void {
var scratch: [mac_length]u8 = undefined;
ctx.hash.final(&scratch);
var ohash = Hash.init(.{});
ohash.update(&ctx.o_key_pad);
ohash.update(&scratch);
ohash.final(out);
}
};
}
const htest = @import("test.zig");
test "hmac md5" {
var out: [HmacMd5.mac_length]u8 = undefined;
HmacMd5.create(out[0..], "", "");
try htest.assertEqual("74e6f7298a9c2d168935f58c001bad88", out[0..]);
HmacMd5.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
try htest.assertEqual("80070713463e7749b90c2dc24911e275", out[0..]);
}
test "hmac sha1" {
var out: [HmacSha1.mac_length]u8 = undefined;
HmacSha1.create(out[0..], "", "");
try htest.assertEqual("fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", out[0..]);
HmacSha1.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
try htest.assertEqual("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", out[0..]);
}
test "hmac sha256" {
var out: [sha2.HmacSha256.mac_length]u8 = undefined;
sha2.HmacSha256.create(out[0..], "", "");
try htest.assertEqual("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", out[0..]);
sha2.HmacSha256.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
try htest.assertEqual("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", out[0..]);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/modes.zig | // Based on Go stdlib implementation
const std = @import("../std.zig");
const mem = std.mem;
const debug = std.debug;
/// Counter mode.
///
/// This mode creates a key stream by encrypting an incrementing counter using a block cipher, and adding it to the source material.
///
/// Important: the counter mode doesn't provide authenticated encryption: the ciphertext can be trivially modified without this being detected.
/// As a result, applications should generally never use it directly, but only in a construction that includes a MAC.
pub fn ctr(comptime BlockCipher: anytype, block_cipher: BlockCipher, dst: []u8, src: []const u8, iv: [BlockCipher.block_length]u8, endian: std.builtin.Endian) void {
debug.assert(dst.len >= src.len);
const block_length = BlockCipher.block_length;
var counter: [BlockCipher.block_length]u8 = undefined;
var counterInt = mem.readInt(u128, &iv, endian);
var i: usize = 0;
const parallel_count = BlockCipher.block.parallel.optimal_parallel_blocks;
const wide_block_length = parallel_count * 16;
if (src.len >= wide_block_length) {
var counters: [parallel_count * 16]u8 = undefined;
while (i + wide_block_length <= src.len) : (i += wide_block_length) {
comptime var j = 0;
inline while (j < parallel_count) : (j += 1) {
mem.writeInt(u128, counters[j * 16 .. j * 16 + 16], counterInt, endian);
counterInt +%= 1;
}
block_cipher.xorWide(parallel_count, dst[i .. i + wide_block_length][0..wide_block_length], src[i .. i + wide_block_length][0..wide_block_length], counters);
}
}
while (i + block_length <= src.len) : (i += block_length) {
mem.writeInt(u128, &counter, counterInt, endian);
counterInt +%= 1;
block_cipher.xor(dst[i .. i + block_length][0..block_length], src[i .. i + block_length][0..block_length], counter);
}
if (i < src.len) {
mem.writeInt(u128, &counter, counterInt, endian);
var pad = [_]u8{0} ** block_length;
mem.copy(u8, &pad, src[i..]);
block_cipher.xor(&pad, &pad, counter);
mem.copy(u8, dst[i..], pad[0 .. src.len - i]);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/salsa20.zig | const std = @import("std");
const builtin = @import("builtin");
const crypto = std.crypto;
const debug = std.debug;
const math = std.math;
const mem = std.mem;
const utils = std.crypto.utils;
const Vector = std.meta.Vector;
const Poly1305 = crypto.onetimeauth.Poly1305;
const Blake2b = crypto.hash.blake2.Blake2b;
const X25519 = crypto.dh.X25519;
const AuthenticationError = crypto.errors.AuthenticationError;
const IdentityElementError = crypto.errors.IdentityElementError;
const WeakPublicKeyError = crypto.errors.WeakPublicKeyError;
const Salsa20VecImpl = struct {
const Lane = Vector(4, u32);
const Half = Vector(2, u32);
const BlockVec = [4]Lane;
fn initContext(key: [8]u32, d: [4]u32) BlockVec {
const c = "expand 32-byte k";
const constant_le = comptime [4]u32{
mem.readIntLittle(u32, c[0..4]),
mem.readIntLittle(u32, c[4..8]),
mem.readIntLittle(u32, c[8..12]),
mem.readIntLittle(u32, c[12..16]),
};
return BlockVec{
Lane{ key[0], key[1], key[2], key[3] },
Lane{ key[4], key[5], key[6], key[7] },
Lane{ constant_le[0], constant_le[1], constant_le[2], constant_le[3] },
Lane{ d[0], d[1], d[2], d[3] },
};
}
inline fn salsa20Core(x: *BlockVec, input: BlockVec, comptime feedback: bool) void {
const n1n2n3n0 = Lane{ input[3][1], input[3][2], input[3][3], input[3][0] };
const n1n2 = Half{ n1n2n3n0[0], n1n2n3n0[1] };
const n3n0 = Half{ n1n2n3n0[2], n1n2n3n0[3] };
const k0k1 = Half{ input[0][0], input[0][1] };
const k2k3 = Half{ input[0][2], input[0][3] };
const k4k5 = Half{ input[1][0], input[1][1] };
const k6k7 = Half{ input[1][2], input[1][3] };
const n0k0 = Half{ n3n0[1], k0k1[0] };
const k0n0 = Half{ n0k0[1], n0k0[0] };
const k4k5k0n0 = Lane{ k4k5[0], k4k5[1], k0n0[0], k0n0[1] };
const k1k6 = Half{ k0k1[1], k6k7[0] };
const k6k1 = Half{ k1k6[1], k1k6[0] };
const n1n2k6k1 = Lane{ n1n2[0], n1n2[1], k6k1[0], k6k1[1] };
const k7n3 = Half{ k6k7[1], n3n0[0] };
const n3k7 = Half{ k7n3[1], k7n3[0] };
const k2k3n3k7 = Lane{ k2k3[0], k2k3[1], n3k7[0], n3k7[1] };
var diag0 = input[2];
var diag1 = @shuffle(u32, k4k5k0n0, undefined, [_]i32{ 1, 2, 3, 0 });
var diag2 = @shuffle(u32, n1n2k6k1, undefined, [_]i32{ 1, 2, 3, 0 });
var diag3 = @shuffle(u32, k2k3n3k7, undefined, [_]i32{ 1, 2, 3, 0 });
const start0 = diag0;
const start1 = diag1;
const start2 = diag2;
const start3 = diag3;
var i: usize = 0;
while (i < 20) : (i += 2) {
var a0 = diag1 +% diag0;
diag3 ^= math.rotl(Lane, a0, 7);
var a1 = diag0 +% diag3;
diag2 ^= math.rotl(Lane, a1, 9);
var a2 = diag3 +% diag2;
diag1 ^= math.rotl(Lane, a2, 13);
var a3 = diag2 +% diag1;
diag0 ^= math.rotl(Lane, a3, 18);
var diag3_shift = @shuffle(u32, diag3, undefined, [_]i32{ 3, 0, 1, 2 });
var diag2_shift = @shuffle(u32, diag2, undefined, [_]i32{ 2, 3, 0, 1 });
var diag1_shift = @shuffle(u32, diag1, undefined, [_]i32{ 1, 2, 3, 0 });
diag3 = diag3_shift;
diag2 = diag2_shift;
diag1 = diag1_shift;
a0 = diag3 +% diag0;
diag1 ^= math.rotl(Lane, a0, 7);
a1 = diag0 +% diag1;
diag2 ^= math.rotl(Lane, a1, 9);
a2 = diag1 +% diag2;
diag3 ^= math.rotl(Lane, a2, 13);
a3 = diag2 +% diag3;
diag0 ^= math.rotl(Lane, a3, 18);
diag1_shift = @shuffle(u32, diag1, undefined, [_]i32{ 3, 0, 1, 2 });
diag2_shift = @shuffle(u32, diag2, undefined, [_]i32{ 2, 3, 0, 1 });
diag3_shift = @shuffle(u32, diag3, undefined, [_]i32{ 1, 2, 3, 0 });
diag1 = diag1_shift;
diag2 = diag2_shift;
diag3 = diag3_shift;
}
if (feedback) {
diag0 +%= start0;
diag1 +%= start1;
diag2 +%= start2;
diag3 +%= start3;
}
const x0x1x10x11 = Lane{ diag0[0], diag1[1], diag0[2], diag1[3] };
const x12x13x6x7 = Lane{ diag1[0], diag2[1], diag1[2], diag2[3] };
const x8x9x2x3 = Lane{ diag2[0], diag3[1], diag2[2], diag3[3] };
const x4x5x14x15 = Lane{ diag3[0], diag0[1], diag3[2], diag0[3] };
x[0] = Lane{ x0x1x10x11[0], x0x1x10x11[1], x8x9x2x3[2], x8x9x2x3[3] };
x[1] = Lane{ x4x5x14x15[0], x4x5x14x15[1], x12x13x6x7[2], x12x13x6x7[3] };
x[2] = Lane{ x8x9x2x3[0], x8x9x2x3[1], x0x1x10x11[2], x0x1x10x11[3] };
x[3] = Lane{ x12x13x6x7[0], x12x13x6x7[1], x4x5x14x15[2], x4x5x14x15[3] };
}
fn hashToBytes(out: *[64]u8, x: BlockVec) void {
var i: usize = 0;
while (i < 4) : (i += 1) {
mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i][0]);
mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i][1]);
mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i][2]);
mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i][3]);
}
}
fn salsa20Xor(out: []u8, in: []const u8, key: [8]u32, d: [4]u32) void {
var ctx = initContext(key, d);
var x: BlockVec = undefined;
var buf: [64]u8 = undefined;
var i: usize = 0;
while (i + 64 <= in.len) : (i += 64) {
salsa20Core(x[0..], ctx, true);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < 64) : (j += 1) {
xout[j] = xin[j];
}
j = 0;
while (j < 64) : (j += 1) {
xout[j] ^= buf[j];
}
ctx[3][2] +%= 1;
if (ctx[3][2] == 0) {
ctx[3][3] += 1;
}
}
if (i < in.len) {
salsa20Core(x[0..], ctx, true);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < in.len % 64) : (j += 1) {
xout[j] = xin[j] ^ buf[j];
}
}
}
fn hsalsa20(input: [16]u8, key: [32]u8) [32]u8 {
var c: [4]u32 = undefined;
for (c, 0..) |_, i| {
c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]);
}
const ctx = initContext(keyToWords(key), c);
var x: BlockVec = undefined;
salsa20Core(x[0..], ctx, false);
var out: [32]u8 = undefined;
mem.writeIntLittle(u32, out[0..4], x[0][0]);
mem.writeIntLittle(u32, out[4..8], x[1][1]);
mem.writeIntLittle(u32, out[8..12], x[2][2]);
mem.writeIntLittle(u32, out[12..16], x[3][3]);
mem.writeIntLittle(u32, out[16..20], x[1][2]);
mem.writeIntLittle(u32, out[20..24], x[1][3]);
mem.writeIntLittle(u32, out[24..28], x[2][0]);
mem.writeIntLittle(u32, out[28..32], x[2][1]);
return out;
}
};
const Salsa20NonVecImpl = struct {
const BlockVec = [16]u32;
fn initContext(key: [8]u32, d: [4]u32) BlockVec {
const c = "expand 32-byte k";
const constant_le = comptime [4]u32{
mem.readIntLittle(u32, c[0..4]),
mem.readIntLittle(u32, c[4..8]),
mem.readIntLittle(u32, c[8..12]),
mem.readIntLittle(u32, c[12..16]),
};
return BlockVec{
constant_le[0], key[0], key[1], key[2],
key[3], constant_le[1], d[0], d[1],
d[2], d[3], constant_le[2], key[4],
key[5], key[6], key[7], constant_le[3],
};
}
const QuarterRound = struct {
a: usize,
b: usize,
c: usize,
d: u6,
};
inline fn Rp(a: usize, b: usize, c: usize, d: u6) QuarterRound {
return QuarterRound{
.a = a,
.b = b,
.c = c,
.d = d,
};
}
inline fn salsa20Core(x: *BlockVec, input: BlockVec, comptime feedback: bool) void {
const arx_steps = comptime [_]QuarterRound{
Rp(4, 0, 12, 7), Rp(8, 4, 0, 9), Rp(12, 8, 4, 13), Rp(0, 12, 8, 18),
Rp(9, 5, 1, 7), Rp(13, 9, 5, 9), Rp(1, 13, 9, 13), Rp(5, 1, 13, 18),
Rp(14, 10, 6, 7), Rp(2, 14, 10, 9), Rp(6, 2, 14, 13), Rp(10, 6, 2, 18),
Rp(3, 15, 11, 7), Rp(7, 3, 15, 9), Rp(11, 7, 3, 13), Rp(15, 11, 7, 18),
Rp(1, 0, 3, 7), Rp(2, 1, 0, 9), Rp(3, 2, 1, 13), Rp(0, 3, 2, 18),
Rp(6, 5, 4, 7), Rp(7, 6, 5, 9), Rp(4, 7, 6, 13), Rp(5, 4, 7, 18),
Rp(11, 10, 9, 7), Rp(8, 11, 10, 9), Rp(9, 8, 11, 13), Rp(10, 9, 8, 18),
Rp(12, 15, 14, 7), Rp(13, 12, 15, 9), Rp(14, 13, 12, 13), Rp(15, 14, 13, 18),
};
x.* = input;
var j: usize = 0;
while (j < 20) : (j += 2) {
inline for (arx_steps) |r| {
x[r.a] ^= math.rotl(u32, x[r.b] +% x[r.c], r.d);
}
}
if (feedback) {
j = 0;
while (j < 16) : (j += 1) {
x[j] +%= input[j];
}
}
}
fn hashToBytes(out: *[64]u8, x: BlockVec) void {
for (x, 0..) |w, i| {
mem.writeIntLittle(u32, out[i * 4 ..][0..4], w);
}
}
fn salsa20Xor(out: []u8, in: []const u8, key: [8]u32, d: [4]u32) void {
var ctx = initContext(key, d);
var x: BlockVec = undefined;
var buf: [64]u8 = undefined;
var i: usize = 0;
while (i + 64 <= in.len) : (i += 64) {
salsa20Core(x[0..], ctx, true);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < 64) : (j += 1) {
xout[j] = xin[j];
}
j = 0;
while (j < 64) : (j += 1) {
xout[j] ^= buf[j];
}
ctx[3][2] +%= 1;
if (ctx[3][2] == 0) {
ctx[3][3] += 1;
}
}
if (i < in.len) {
salsa20Core(x[0..], ctx, true);
hashToBytes(buf[0..], x);
var xout = out[i..];
const xin = in[i..];
var j: usize = 0;
while (j < in.len % 64) : (j += 1) {
xout[j] = xin[j] ^ buf[j];
}
}
}
fn hsalsa20(input: [16]u8, key: [32]u8) [32]u8 {
var c: [4]u32 = undefined;
for (c, 0..) |_, i| {
c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]);
}
const ctx = initContext(keyToWords(key), c);
var x: BlockVec = undefined;
salsa20Core(x[0..], ctx, false);
var out: [32]u8 = undefined;
mem.writeIntLittle(u32, out[0..4], x[0]);
mem.writeIntLittle(u32, out[4..8], x[5]);
mem.writeIntLittle(u32, out[8..12], x[10]);
mem.writeIntLittle(u32, out[12..16], x[15]);
mem.writeIntLittle(u32, out[16..20], x[6]);
mem.writeIntLittle(u32, out[20..24], x[7]);
mem.writeIntLittle(u32, out[24..28], x[8]);
mem.writeIntLittle(u32, out[28..32], x[9]);
return out;
}
};
const Salsa20Impl = if (builtin.cpu.arch == .x86_64) Salsa20VecImpl else Salsa20NonVecImpl;
fn keyToWords(key: [32]u8) [8]u32 {
var k: [8]u32 = undefined;
var i: usize = 0;
while (i < 8) : (i += 1) {
k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]);
}
return k;
}
fn extend(key: [32]u8, nonce: [24]u8) struct { key: [32]u8, nonce: [8]u8 } {
return .{
.key = Salsa20Impl.hsalsa20(nonce[0..16].*, key),
.nonce = nonce[16..24].*,
};
}
/// The Salsa20 stream cipher.
pub const Salsa20 = struct {
/// Nonce length in bytes.
pub const nonce_length = 8;
/// Key length in bytes.
pub const key_length = 32;
/// Add the output of the Salsa20 stream cipher to `in` and stores the result into `out`.
/// WARNING: This function doesn't provide authenticated encryption.
/// Using the AEAD or one of the `box` versions is usually preferred.
pub fn xor(out: []u8, in: []const u8, counter: u64, key: [key_length]u8, nonce: [nonce_length]u8) void {
debug.assert(in.len == out.len);
var d: [4]u32 = undefined;
d[0] = mem.readIntLittle(u32, nonce[0..4]);
d[1] = mem.readIntLittle(u32, nonce[4..8]);
d[2] = @as(u32, @truncate(counter));
d[3] = @as(u32, @truncate(counter >> 32));
Salsa20Impl.salsa20Xor(out, in, keyToWords(key), d);
}
};
/// The XSalsa20 stream cipher.
pub const XSalsa20 = struct {
/// Nonce length in bytes.
pub const nonce_length = 24;
/// Key length in bytes.
pub const key_length = 32;
/// Add the output of the XSalsa20 stream cipher to `in` and stores the result into `out`.
/// WARNING: This function doesn't provide authenticated encryption.
/// Using the AEAD or one of the `box` versions is usually preferred.
pub fn xor(out: []u8, in: []const u8, counter: u64, key: [key_length]u8, nonce: [nonce_length]u8) void {
const extended = extend(key, nonce);
Salsa20.xor(out, in, counter, extended.key, extended.nonce);
}
};
/// The XSalsa20 stream cipher, combined with the Poly1305 MAC
pub const XSalsa20Poly1305 = struct {
/// Authentication tag length in bytes.
pub const tag_length = Poly1305.mac_length;
/// Nonce length in bytes.
pub const nonce_length = XSalsa20.nonce_length;
/// Key length in bytes.
pub const key_length = XSalsa20.key_length;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
debug.assert(c.len == m.len);
const extended = extend(k, npub);
var block0 = [_]u8{0} ** 64;
const mlen0 = math.min(32, m.len);
mem.copy(u8, block0[32..][0..mlen0], m[0..mlen0]);
Salsa20.xor(block0[0..], block0[0..], 0, extended.key, extended.nonce);
mem.copy(u8, c[0..mlen0], block0[32..][0..mlen0]);
Salsa20.xor(c[mlen0..], m[mlen0..], 1, extended.key, extended.nonce);
var mac = Poly1305.init(block0[0..32]);
mac.update(ad);
mac.update(c);
mac.final(tag);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
debug.assert(c.len == m.len);
const extended = extend(k, npub);
var block0 = [_]u8{0} ** 64;
const mlen0 = math.min(32, c.len);
mem.copy(u8, block0[32..][0..mlen0], c[0..mlen0]);
Salsa20.xor(block0[0..], block0[0..], 0, extended.key, extended.nonce);
var mac = Poly1305.init(block0[0..32]);
mac.update(ad);
mac.update(c);
var computedTag: [tag_length]u8 = undefined;
mac.final(&computedTag);
var acc: u8 = 0;
for (computedTag, 0..) |_, i| {
acc |= computedTag[i] ^ tag[i];
}
if (acc != 0) {
utils.secureZero(u8, &computedTag);
return error.AuthenticationFailed;
}
mem.copy(u8, m[0..mlen0], block0[32..][0..mlen0]);
Salsa20.xor(m[mlen0..], c[mlen0..], 1, extended.key, extended.nonce);
}
};
/// NaCl-compatible secretbox API.
///
/// A secretbox contains both an encrypted message and an authentication tag to verify that it hasn't been tampered with.
/// A secret key shared by all the recipients must be already known in order to use this API.
///
/// Nonces are 192-bit large and can safely be chosen with a random number generator.
pub const SecretBox = struct {
/// Key length in bytes.
pub const key_length = XSalsa20Poly1305.key_length;
/// Nonce length in bytes.
pub const nonce_length = XSalsa20Poly1305.nonce_length;
/// Authentication tag length in bytes.
pub const tag_length = XSalsa20Poly1305.tag_length;
/// Encrypt and authenticate `m` using a nonce `npub` and a key `k`.
/// `c` must be exactly `tag_length` longer than `m`, as it will store both the ciphertext and the authentication tag.
pub fn seal(c: []u8, m: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
debug.assert(c.len == tag_length + m.len);
XSalsa20Poly1305.encrypt(c[tag_length..], c[0..tag_length], m, "", npub, k);
}
/// Verify and decrypt `c` using a nonce `npub` and a key `k`.
/// `m` must be exactly `tag_length` smaller than `c`, as `c` includes an authentication tag in addition to the encrypted message.
pub fn open(m: []u8, c: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
if (c.len < tag_length) {
return error.AuthenticationFailed;
}
debug.assert(m.len == c.len - tag_length);
return XSalsa20Poly1305.decrypt(m, c[tag_length..], c[0..tag_length].*, "", npub, k);
}
};
/// NaCl-compatible box API.
///
/// A secretbox contains both an encrypted message and an authentication tag to verify that it hasn't been tampered with.
/// This construction uses public-key cryptography. A shared secret doesn't have to be known in advance by both parties.
/// Instead, a message is encrypted using a sender's secret key and a recipient's public key,
/// and is decrypted using the recipient's secret key and the sender's public key.
///
/// Nonces are 192-bit large and can safely be chosen with a random number generator.
pub const Box = struct {
/// Public key length in bytes.
pub const public_length = X25519.public_length;
/// Secret key length in bytes.
pub const secret_length = X25519.secret_length;
/// Shared key length in bytes.
pub const shared_length = XSalsa20Poly1305.key_length;
/// Seed (for key pair creation) length in bytes.
pub const seed_length = X25519.seed_length;
/// Nonce length in bytes.
pub const nonce_length = XSalsa20Poly1305.nonce_length;
/// Authentication tag length in bytes.
pub const tag_length = XSalsa20Poly1305.tag_length;
/// A key pair.
pub const KeyPair = X25519.KeyPair;
/// Compute a secret suitable for `secretbox` given a recipent's public key and a sender's secret key.
pub fn createSharedSecret(public_key: [public_length]u8, secret_key: [secret_length]u8) (IdentityElementError || WeakPublicKeyError)![shared_length]u8 {
const p = try X25519.scalarmult(secret_key, public_key);
const zero = [_]u8{0} ** 16;
return Salsa20Impl.hsalsa20(zero, p);
}
/// Encrypt and authenticate a message using a recipient's public key `public_key` and a sender's `secret_key`.
pub fn seal(c: []u8, m: []const u8, npub: [nonce_length]u8, public_key: [public_length]u8, secret_key: [secret_length]u8) (IdentityElementError || WeakPublicKeyError)!void {
const shared_key = try createSharedSecret(public_key, secret_key);
return SecretBox.seal(c, m, npub, shared_key);
}
/// Verify and decrypt a message using a recipient's secret key `public_key` and a sender's `public_key`.
pub fn open(m: []u8, c: []const u8, npub: [nonce_length]u8, public_key: [public_length]u8, secret_key: [secret_length]u8) (IdentityElementError || WeakPublicKeyError || AuthenticationError)!void {
const shared_key = try createSharedSecret(public_key, secret_key);
return SecretBox.open(m, c, npub, shared_key);
}
};
/// libsodium-compatible sealed boxes
///
/// Sealed boxes are designed to anonymously send messages to a recipient given their public key.
/// Only the recipient can decrypt these messages, using their private key.
/// While the recipient can verify the integrity of the message, it cannot verify the identity of the sender.
///
/// A message is encrypted using an ephemeral key pair, whose secret part is destroyed right after the encryption process.
pub const SealedBox = struct {
pub const public_length = Box.public_length;
pub const secret_length = Box.secret_length;
pub const seed_length = Box.seed_length;
pub const seal_length = Box.public_length + Box.tag_length;
/// A key pair.
pub const KeyPair = Box.KeyPair;
fn createNonce(pk1: [public_length]u8, pk2: [public_length]u8) [Box.nonce_length]u8 {
var hasher = Blake2b(Box.nonce_length * 8).init(.{});
hasher.update(&pk1);
hasher.update(&pk2);
var nonce: [Box.nonce_length]u8 = undefined;
hasher.final(&nonce);
return nonce;
}
/// Encrypt a message `m` for a recipient whose public key is `public_key`.
/// `c` must be `seal_length` bytes larger than `m`, so that the required metadata can be added.
pub fn seal(c: []u8, m: []const u8, public_key: [public_length]u8) (WeakPublicKeyError || IdentityElementError)!void {
debug.assert(c.len == m.len + seal_length);
var ekp = try KeyPair.create(null);
const nonce = createNonce(ekp.public_key, public_key);
mem.copy(u8, c[0..public_length], ekp.public_key[0..]);
try Box.seal(c[Box.public_length..], m, nonce, public_key, ekp.secret_key);
utils.secureZero(u8, ekp.secret_key[0..]);
}
/// Decrypt a message using a key pair.
/// `m` must be exactly `seal_length` bytes smaller than `c`, as `c` also includes metadata.
pub fn open(m: []u8, c: []const u8, keypair: KeyPair) (IdentityElementError || WeakPublicKeyError || AuthenticationError)!void {
if (c.len < seal_length) {
return error.AuthenticationFailed;
}
const epk = c[0..public_length];
const nonce = createNonce(epk.*, keypair.public_key);
return Box.open(m, c[public_length..], nonce, epk.*, keypair.secret_key);
}
};
const htest = @import("test.zig");
test "(x)salsa20" {
const key = [_]u8{0x69} ** 32;
const nonce = [_]u8{0x42} ** 8;
const msg = [_]u8{0} ** 20;
var c: [msg.len]u8 = undefined;
Salsa20.xor(&c, msg[0..], 0, key, nonce);
try htest.assertEqual("30ff9933aa6534ff5207142593cd1fca4b23bdd8", c[0..]);
const extended_nonce = [_]u8{0x42} ** 24;
XSalsa20.xor(&c, msg[0..], 0, key, extended_nonce);
try htest.assertEqual("b4ab7d82e750ec07644fa3281bce6cd91d4243f9", c[0..]);
}
test "xsalsa20poly1305" {
var msg: [100]u8 = undefined;
var msg2: [msg.len]u8 = undefined;
var c: [msg.len]u8 = undefined;
var key: [XSalsa20Poly1305.key_length]u8 = undefined;
var nonce: [XSalsa20Poly1305.nonce_length]u8 = undefined;
var tag: [XSalsa20Poly1305.tag_length]u8 = undefined;
crypto.random.bytes(&msg);
crypto.random.bytes(&key);
crypto.random.bytes(&nonce);
XSalsa20Poly1305.encrypt(c[0..], &tag, msg[0..], "ad", nonce, key);
try XSalsa20Poly1305.decrypt(msg2[0..], c[0..], tag, "ad", nonce, key);
}
test "xsalsa20poly1305 secretbox" {
var msg: [100]u8 = undefined;
var msg2: [msg.len]u8 = undefined;
var key: [XSalsa20Poly1305.key_length]u8 = undefined;
var nonce: [Box.nonce_length]u8 = undefined;
var boxed: [msg.len + Box.tag_length]u8 = undefined;
crypto.random.bytes(&msg);
crypto.random.bytes(&key);
crypto.random.bytes(&nonce);
SecretBox.seal(boxed[0..], msg[0..], nonce, key);
try SecretBox.open(msg2[0..], boxed[0..], nonce, key);
}
test "xsalsa20poly1305 box" {
var msg: [100]u8 = undefined;
var msg2: [msg.len]u8 = undefined;
var nonce: [Box.nonce_length]u8 = undefined;
var boxed: [msg.len + Box.tag_length]u8 = undefined;
crypto.random.bytes(&msg);
crypto.random.bytes(&nonce);
var kp1 = try Box.KeyPair.create(null);
var kp2 = try Box.KeyPair.create(null);
try Box.seal(boxed[0..], msg[0..], nonce, kp1.public_key, kp2.secret_key);
try Box.open(msg2[0..], boxed[0..], nonce, kp2.public_key, kp1.secret_key);
}
test "xsalsa20poly1305 sealedbox" {
var msg: [100]u8 = undefined;
var msg2: [msg.len]u8 = undefined;
var boxed: [msg.len + SealedBox.seal_length]u8 = undefined;
crypto.random.bytes(&msg);
var kp = try Box.KeyPair.create(null);
try SealedBox.seal(boxed[0..], msg[0..], kp.public_key);
try SealedBox.open(msg2[0..], boxed[0..], kp);
}
test "secretbox twoblocks" {
const key = [_]u8{ 0xc9, 0xc9, 0x4d, 0xcf, 0x68, 0xbe, 0x00, 0xe4, 0x7f, 0xe6, 0x13, 0x26, 0xfc, 0xc4, 0x2f, 0xd0, 0xdb, 0x93, 0x91, 0x1c, 0x09, 0x94, 0x89, 0xe1, 0x1b, 0x88, 0x63, 0x18, 0x86, 0x64, 0x8b, 0x7b };
const nonce = [_]u8{ 0xa4, 0x33, 0xe9, 0x0a, 0x07, 0x68, 0x6e, 0x9a, 0x2b, 0x6d, 0xd4, 0x59, 0x04, 0x72, 0x3e, 0xd3, 0x8a, 0x67, 0x55, 0xc7, 0x9e, 0x3e, 0x77, 0xdc };
const msg = [_]u8{'a'} ** 97;
var ciphertext: [msg.len + SecretBox.tag_length]u8 = undefined;
SecretBox.seal(&ciphertext, &msg, nonce, key);
try htest.assertEqual("b05760e217288ba079caa2fd57fd3701784974ffcfda20fe523b89211ad8af065a6eb37cdb29d51aca5bd75dafdd21d18b044c54bb7c526cf576c94ee8900f911ceab0147e82b667a28c52d58ceb29554ff45471224d37b03256b01c119b89ff6d36855de8138d103386dbc9d971f52261", &ciphertext);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes_gcm.zig | const std = @import("std");
const assert = std.debug.assert;
const crypto = std.crypto;
const debug = std.debug;
const Ghash = std.crypto.onetimeauth.Ghash;
const mem = std.mem;
const modes = crypto.core.modes;
const AuthenticationError = crypto.errors.AuthenticationError;
pub const Aes128Gcm = AesGcm(crypto.core.aes.Aes128);
pub const Aes256Gcm = AesGcm(crypto.core.aes.Aes256);
fn AesGcm(comptime Aes: anytype) type {
debug.assert(Aes.block.block_length == 16);
return struct {
pub const tag_length = 16;
pub const nonce_length = 12;
pub const key_length = Aes.key_bits / 8;
const zeros = [_]u8{0} ** 16;
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
debug.assert(c.len == m.len);
debug.assert(m.len <= 16 * ((1 << 32) - 2));
const aes = Aes.initEnc(key);
var h: [16]u8 = undefined;
aes.encrypt(&h, &zeros);
var t: [16]u8 = undefined;
var j: [16]u8 = undefined;
mem.copy(u8, j[0..nonce_length], npub[0..]);
mem.writeIntBig(u32, j[nonce_length..][0..4], 1);
aes.encrypt(&t, &j);
var mac = Ghash.init(&h);
mac.update(ad);
mac.pad();
mem.writeIntBig(u32, j[nonce_length..][0..4], 2);
modes.ctr(@TypeOf(aes), aes, c, m, j, std.builtin.Endian.Big);
mac.update(c[0..m.len][0..]);
mac.pad();
var final_block = h;
mem.writeIntBig(u64, final_block[0..8], ad.len * 8);
mem.writeIntBig(u64, final_block[8..16], m.len * 8);
mac.update(&final_block);
mac.final(tag);
for (t, 0..) |x, i| {
tag[i] ^= x;
}
}
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
const aes = Aes.initEnc(key);
var h: [16]u8 = undefined;
aes.encrypt(&h, &zeros);
var t: [16]u8 = undefined;
var j: [16]u8 = undefined;
mem.copy(u8, j[0..nonce_length], npub[0..]);
mem.writeIntBig(u32, j[nonce_length..][0..4], 1);
aes.encrypt(&t, &j);
var mac = Ghash.init(&h);
mac.update(ad);
mac.pad();
mac.update(c);
mac.pad();
var final_block = h;
mem.writeIntBig(u64, final_block[0..8], ad.len * 8);
mem.writeIntBig(u64, final_block[8..16], m.len * 8);
mac.update(&final_block);
var computed_tag: [Ghash.mac_length]u8 = undefined;
mac.final(&computed_tag);
for (t, 0..) |x, i| {
computed_tag[i] ^= x;
}
var acc: u8 = 0;
for (computed_tag, 0..) |_, p| {
acc |= (computed_tag[p] ^ tag[p]);
}
if (acc != 0) {
mem.set(u8, m, 0xaa);
return error.AuthenticationFailed;
}
mem.writeIntBig(u32, j[nonce_length..][0..4], 2);
modes.ctr(@TypeOf(aes), aes, m, c, j, std.builtin.Endian.Big);
}
};
}
const htest = @import("test.zig");
const testing = std.testing;
test "Aes256Gcm - Empty message and no associated data" {
const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length;
const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length;
const ad = "";
const m = "";
var c: [m.len]u8 = undefined;
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try htest.assertEqual("6b6ff610a16fa4cd59f1fb7903154e92", &tag);
}
test "Aes256Gcm - Associated data only" {
const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length;
const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length;
const m = "";
const ad = "Test with associated data";
var c: [m.len]u8 = undefined;
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try htest.assertEqual("262ed164c2dfb26e080a9d108dd9dd4c", &tag);
}
test "Aes256Gcm - Message only" {
const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length;
const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length;
const m = "Test with message only";
const ad = "";
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key);
try testing.expectEqualSlices(u8, m[0..], m2[0..]);
try htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01d539472f7c", &c);
try htest.assertEqual("07cd7fc9103e2f9e9bf2dfaa319caff4", &tag);
}
test "Aes256Gcm - Message and associated data" {
const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length;
const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length;
const m = "Test with message";
const ad = "Test with associated data";
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key);
try testing.expectEqualSlices(u8, m[0..], m2[0..]);
try htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01", &c);
try htest.assertEqual("64accec679d444e2373bd9f6796c0d2c", &tag);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/bcrypt.zig | const std = @import("std");
const crypto = std.crypto;
const debug = std.debug;
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const pwhash = crypto.pwhash;
const testing = std.testing;
const utils = crypto.utils;
const phc_format = @import("phc_encoding.zig");
const KdfError = pwhash.KdfError;
const HasherError = pwhash.HasherError;
const EncodingError = phc_format.Error;
const Error = pwhash.Error;
const salt_length: usize = 16;
const salt_str_length: usize = 22;
const ct_str_length: usize = 31;
const ct_length: usize = 24;
const dk_length: usize = ct_length - 1;
/// Length (in bytes) of a password hash in crypt encoding
pub const hash_length: usize = 60;
const State = struct {
sboxes: [4][256]u32 = [4][256]u32{
.{ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a },
.{ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 },
.{ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 },
.{ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 },
},
subkeys: [18]u32 = [18]u32{ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b },
fn toWord(data: []const u8, current: *usize) u32 {
var t: u32 = 0;
var j = current.*;
var i: usize = 0;
while (i < 4) : (i += 1) {
if (j >= data.len) j = 0;
t = (t << 8) | data[j];
j += 1;
}
current.* = j;
return t;
}
fn expand0(state: *State, key: []const u8) void {
var i: usize = 0;
var j: usize = 0;
while (i < state.subkeys.len) : (i += 1) {
state.subkeys[i] ^= toWord(key, &j);
}
var halves = Halves{ .l = 0, .r = 0 };
i = 0;
while (i < 18) : (i += 2) {
state.encipher(&halves);
state.subkeys[i] = halves.l;
state.subkeys[i + 1] = halves.r;
}
i = 0;
while (i < 4) : (i += 1) {
var k: usize = 0;
while (k < 256) : (k += 2) {
state.encipher(&halves);
state.sboxes[i][k] = halves.l;
state.sboxes[i][k + 1] = halves.r;
}
}
}
fn expand(state: *State, data: []const u8, key: []const u8) void {
var i: usize = 0;
var j: usize = 0;
while (i < state.subkeys.len) : (i += 1) {
state.subkeys[i] ^= toWord(key, &j);
}
var halves = Halves{ .l = 0, .r = 0 };
i = 0;
j = 0;
while (i < 18) : (i += 2) {
halves.l ^= toWord(data, &j);
halves.r ^= toWord(data, &j);
state.encipher(&halves);
state.subkeys[i] = halves.l;
state.subkeys[i + 1] = halves.r;
}
i = 0;
while (i < 4) : (i += 1) {
var k: usize = 0;
while (k < 256) : (k += 2) {
halves.l ^= toWord(data, &j);
halves.r ^= toWord(data, &j);
state.encipher(&halves);
state.sboxes[i][k] = halves.l;
state.sboxes[i][k + 1] = halves.r;
}
}
}
const Halves = struct { l: u32, r: u32 };
fn feistelF(state: State, x: u32) u32 {
var r = state.sboxes[0][@as(u8, @truncate(x >> 24))];
r +%= state.sboxes[1][@as(u8, @truncate(x >> 16))];
r ^= state.sboxes[2][@as(u8, @truncate(x >> 8))];
r +%= state.sboxes[3][@as(u8, @truncate(x))];
return r;
}
fn halfRound(state: State, i: u32, j: u32, n: usize) u32 {
return i ^ state.feistelF(j) ^ state.subkeys[n];
}
fn encipher(state: State, halves: *Halves) void {
halves.l ^= state.subkeys[0];
var i: usize = 1;
while (i < 16) : (i += 2) {
halves.r = state.halfRound(halves.r, halves.l, i);
halves.l = state.halfRound(halves.l, halves.r, i + 1);
}
const halves_last = Halves{ .l = halves.r ^ state.subkeys[i], .r = halves.l };
halves.* = halves_last;
}
fn encrypt(state: State, data: []u32) void {
debug.assert(data.len % 2 == 0);
var i: usize = 0;
while (i < data.len) : (i += 2) {
var halves = Halves{ .l = data[i], .r = data[i + 1] };
state.encipher(&halves);
data[i] = halves.l;
data[i + 1] = halves.r;
}
}
};
pub const Params = struct {
rounds_log: u6,
};
pub fn bcrypt(
password: []const u8,
salt: [salt_length]u8,
params: Params,
) [dk_length]u8 {
var state = State{};
var password_buf: [73]u8 = undefined;
const trimmed_len = math.min(password.len, password_buf.len - 1);
mem.copy(u8, password_buf[0..], password[0..trimmed_len]);
password_buf[trimmed_len] = 0;
var passwordZ = password_buf[0 .. trimmed_len + 1];
state.expand(salt[0..], passwordZ);
const rounds: u64 = @as(u64, 1) << params.rounds_log;
var k: u64 = 0;
while (k < rounds) : (k += 1) {
state.expand0(passwordZ);
state.expand0(salt[0..]);
}
utils.secureZero(u8, &password_buf);
var cdata = [6]u32{ 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 }; // "OrpheanBeholderScryDoubt"
k = 0;
while (k < 64) : (k += 1) {
state.encrypt(&cdata);
}
var ct: [ct_length]u8 = undefined;
for (cdata, 0..) |c, i| {
mem.writeIntBig(u32, ct[i * 4 ..][0..4], c);
}
return ct[0..dk_length].*;
}
const crypt_format = struct {
/// String prefix for bcrypt
pub const prefix = "$2";
// bcrypt has its own variant of base64, with its own alphabet and no padding
const Codec = struct {
const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
fn encode(b64: []u8, bin: []const u8) void {
var i: usize = 0;
var j: usize = 0;
while (i < bin.len) {
var c1 = bin[i];
i += 1;
b64[j] = alphabet[c1 >> 2];
j += 1;
c1 = (c1 & 3) << 4;
if (i >= bin.len) {
b64[j] = alphabet[c1];
j += 1;
break;
}
var c2 = bin[i];
i += 1;
c1 |= (c2 >> 4) & 0x0f;
b64[j] = alphabet[c1];
j += 1;
c1 = (c2 & 0x0f) << 2;
if (i >= bin.len) {
b64[j] = alphabet[c1];
j += 1;
break;
}
c2 = bin[i];
i += 1;
c1 |= (c2 >> 6) & 3;
b64[j] = alphabet[c1];
b64[j + 1] = alphabet[c2 & 0x3f];
j += 2;
}
debug.assert(j == b64.len);
}
fn decode(bin: []u8, b64: []const u8) EncodingError!void {
var i: usize = 0;
var j: usize = 0;
while (j < bin.len) {
const c1 = @as(u8, @intCast(mem.indexOfScalar(u8, alphabet, b64[i]) orelse
return EncodingError.InvalidEncoding));
const c2 = @as(u8, @intCast(mem.indexOfScalar(u8, alphabet, b64[i + 1]) orelse
return EncodingError.InvalidEncoding));
bin[j] = (c1 << 2) | ((c2 & 0x30) >> 4);
j += 1;
if (j >= bin.len) {
break;
}
const c3 = @as(u8, @intCast(mem.indexOfScalar(u8, alphabet, b64[i + 2]) orelse
return EncodingError.InvalidEncoding));
bin[j] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
j += 1;
if (j >= bin.len) {
break;
}
const c4 = @as(u8, @intCast(mem.indexOfScalar(u8, alphabet, b64[i + 3]) orelse
return EncodingError.InvalidEncoding));
bin[j] = ((c3 & 0x03) << 6) | c4;
j += 1;
i += 4;
}
}
};
fn strHashInternal(
password: []const u8,
salt: [salt_length]u8,
params: Params,
) [hash_length]u8 {
var dk = bcrypt(password, salt, params);
var salt_str: [salt_str_length]u8 = undefined;
Codec.encode(salt_str[0..], salt[0..]);
var ct_str: [ct_str_length]u8 = undefined;
Codec.encode(ct_str[0..], dk[0..]);
var s_buf: [hash_length]u8 = undefined;
const s = fmt.bufPrint(
s_buf[0..],
"{s}b${d}{d}${s}{s}",
.{ prefix, params.rounds_log / 10, params.rounds_log % 10, salt_str, ct_str },
) catch unreachable;
debug.assert(s.len == s_buf.len);
return s_buf;
}
};
/// Hash and verify passwords using the PHC format.
const PhcFormatHasher = struct {
const alg_id = "bcrypt";
const BinValue = phc_format.BinValue;
const HashResult = struct {
alg_id: []const u8,
r: u6,
salt: BinValue(salt_length),
hash: BinValue(dk_length),
};
/// Return a non-deterministic hash of the password encoded as a PHC-format string
pub fn create(
password: []const u8,
params: Params,
buf: []u8,
) HasherError![]const u8 {
var salt: [salt_length]u8 = undefined;
crypto.random.bytes(&salt);
const hash = bcrypt(password, salt, params);
return phc_format.serialize(HashResult{
.alg_id = alg_id,
.r = params.rounds_log,
.salt = try BinValue(salt_length).fromSlice(&salt),
.hash = try BinValue(dk_length).fromSlice(&hash),
}, buf);
}
/// Verify a password against a PHC-format encoded string
pub fn verify(
str: []const u8,
password: []const u8,
) HasherError!void {
const hash_result = try phc_format.deserialize(HashResult, str);
if (!mem.eql(u8, hash_result.alg_id, alg_id)) return HasherError.PasswordVerificationFailed;
if (hash_result.salt.len != salt_length or hash_result.hash.len != dk_length)
return HasherError.InvalidEncoding;
const hash = bcrypt(password, hash_result.salt.buf, .{ .rounds_log = hash_result.r });
const expected_hash = hash_result.hash.constSlice();
if (!mem.eql(u8, &hash, expected_hash)) return HasherError.PasswordVerificationFailed;
}
};
/// Hash and verify passwords using the modular crypt format.
const CryptFormatHasher = struct {
/// Length of a string returned by the create() function
pub const pwhash_str_length: usize = hash_length;
/// Return a non-deterministic hash of the password encoded into the modular crypt format
pub fn create(
password: []const u8,
params: Params,
buf: []u8,
) HasherError![]const u8 {
if (buf.len < pwhash_str_length) return HasherError.NoSpaceLeft;
var salt: [salt_length]u8 = undefined;
crypto.random.bytes(&salt);
const hash = crypt_format.strHashInternal(password, salt, params);
mem.copy(u8, buf, &hash);
return buf[0..pwhash_str_length];
}
/// Verify a password against a string in modular crypt format
pub fn verify(
str: []const u8,
password: []const u8,
) HasherError!void {
if (str.len != pwhash_str_length or str[3] != '$' or str[6] != '$')
return HasherError.InvalidEncoding;
const rounds_log_str = str[4..][0..2];
const rounds_log = fmt.parseInt(u6, rounds_log_str[0..], 10) catch
return HasherError.InvalidEncoding;
const salt_str = str[7..][0..salt_str_length];
var salt: [salt_length]u8 = undefined;
try crypt_format.Codec.decode(salt[0..], salt_str[0..]);
const wanted_s = crypt_format.strHashInternal(password, salt, .{ .rounds_log = rounds_log });
if (!mem.eql(u8, wanted_s[0..], str[0..])) return HasherError.PasswordVerificationFailed;
}
};
/// Options for hashing a password.
pub const HashOptions = struct {
allocator: ?*mem.Allocator = null,
params: Params,
encoding: pwhash.Encoding,
};
/// Compute a hash of a password using 2^rounds_log rounds of the bcrypt key stretching function.
/// bcrypt is a computationally expensive and cache-hard function, explicitly designed to slow down exhaustive searches.
///
/// The function returns a string that includes all the parameters required for verification.
///
/// IMPORTANT: by design, bcrypt silently truncates passwords to 72 bytes.
/// If this is an issue for your application, hash the password first using a function such as SHA-512,
/// and then use the resulting hash as the password parameter for bcrypt.
pub fn strHash(
password: []const u8,
options: HashOptions,
out: []u8,
) Error![]const u8 {
switch (options.encoding) {
.phc => return PhcFormatHasher.create(password, options.params, out),
.crypt => return CryptFormatHasher.create(password, options.params, out),
}
}
/// Options for hash verification.
pub const VerifyOptions = struct {
allocator: ?*mem.Allocator = null,
};
/// Verify that a previously computed hash is valid for a given password.
pub fn strVerify(
str: []const u8,
password: []const u8,
_: VerifyOptions,
) Error!void {
if (mem.startsWith(u8, str, crypt_format.prefix)) {
return CryptFormatHasher.verify(str, password);
} else {
return PhcFormatHasher.verify(str, password);
}
}
test "bcrypt codec" {
var salt: [salt_length]u8 = undefined;
crypto.random.bytes(&salt);
var salt_str: [salt_str_length]u8 = undefined;
crypt_format.Codec.encode(salt_str[0..], salt[0..]);
var salt2: [salt_length]u8 = undefined;
try crypt_format.Codec.decode(salt2[0..], salt_str[0..]);
try testing.expectEqualSlices(u8, salt[0..], salt2[0..]);
}
test "bcrypt crypt format" {
const hash_options = HashOptions{
.params = .{ .rounds_log = 5 },
.encoding = .crypt,
};
const verify_options = VerifyOptions{};
var buf: [hash_length]u8 = undefined;
const s = try strHash("password", hash_options, &buf);
try testing.expect(mem.startsWith(u8, s, crypt_format.prefix));
try strVerify(s, "password", verify_options);
try testing.expectError(
error.PasswordVerificationFailed,
strVerify(s, "invalid password", verify_options),
);
var long_buf: [hash_length]u8 = undefined;
const long_s = try strHash("password" ** 100, hash_options, &long_buf);
try testing.expect(mem.startsWith(u8, long_s, crypt_format.prefix));
try strVerify(long_s, "password" ** 100, verify_options);
try strVerify(long_s, "password" ** 101, verify_options);
try strVerify(
"$2b$08$WUQKyBCaKpziCwUXHiMVvu40dYVjkTxtWJlftl0PpjY2BxWSvFIEe",
"The devil himself",
verify_options,
);
}
test "bcrypt phc format" {
const hash_options = HashOptions{
.params = .{ .rounds_log = 5 },
.encoding = .phc,
};
const verify_options = VerifyOptions{};
const prefix = "$bcrypt$";
var buf: [hash_length * 2]u8 = undefined;
const s = try strHash("password", hash_options, &buf);
try testing.expect(mem.startsWith(u8, s, prefix));
try strVerify(s, "password", verify_options);
try testing.expectError(
error.PasswordVerificationFailed,
strVerify(s, "invalid password", verify_options),
);
var long_buf: [hash_length * 2]u8 = undefined;
const long_s = try strHash("password" ** 100, hash_options, &long_buf);
try testing.expect(mem.startsWith(u8, long_s, prefix));
try strVerify(long_s, "password" ** 100, verify_options);
try strVerify(long_s, "password" ** 101, verify_options);
try strVerify(
"$bcrypt$r=5$2NopntlgE2lX3cTwr4qz8A$r3T7iKYQNnY4hAhGjk9RmuyvgrYJZwc",
"The devil himself",
verify_options,
);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/ghash.zig | //
// Adapted from BearSSL's ctmul64 implementation originally written by Thomas Pornin <[email protected]>
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const utils = std.crypto.utils;
/// GHASH is a universal hash function that features multiplication
/// by a fixed parameter within a Galois field.
///
/// It is not a general purpose hash function - The key must be secret, unpredictable and never reused.
///
/// GHASH is typically used to compute the authentication tag in the AES-GCM construction.
pub const Ghash = struct {
pub const block_length: usize = 16;
pub const mac_length = 16;
pub const key_length = 16;
y0: u64 = 0,
y1: u64 = 0,
h0: u64,
h1: u64,
h2: u64,
h0r: u64,
h1r: u64,
h2r: u64,
hh0: u64 = undefined,
hh1: u64 = undefined,
hh2: u64 = undefined,
hh0r: u64 = undefined,
hh1r: u64 = undefined,
hh2r: u64 = undefined,
leftover: usize = 0,
buf: [block_length]u8 align(16) = undefined,
pub fn init(key: *const [key_length]u8) Ghash {
const h1 = mem.readIntBig(u64, key[0..8]);
const h0 = mem.readIntBig(u64, key[8..16]);
const h1r = @bitReverse(h1);
const h0r = @bitReverse(h0);
const h2 = h0 ^ h1;
const h2r = h0r ^ h1r;
if (builtin.mode == .ReleaseSmall) {
return Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
};
} else {
// Precompute H^2
var hh = Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
};
hh.update(key);
const hh1 = hh.y1;
const hh0 = hh.y0;
const hh1r = @bitReverse(hh1);
const hh0r = @bitReverse(hh0);
const hh2 = hh0 ^ hh1;
const hh2r = hh0r ^ hh1r;
return Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
.hh0 = hh0,
.hh1 = hh1,
.hh2 = hh2,
.hh0r = hh0r,
.hh1r = hh1r,
.hh2r = hh2r,
};
}
}
inline fn clmul_pclmul(x: u64, y: u64) u64 {
const Vector = std.meta.Vector;
const product = asm (
\\ vpclmulqdq $0x00, %[x], %[y], %[out]
: [out] "=x" (-> Vector(2, u64)),
: [x] "x" (@as(Vector(2, u64), @bitCast(@as(u128, x)))),
[y] "x" (@as(Vector(2, u64), @bitCast(@as(u128, y)))),
);
return product[0];
}
inline fn clmul_pmull(x: u64, y: u64) u64 {
const Vector = std.meta.Vector;
const product = asm (
\\ pmull %[out].1q, %[x].1d, %[y].1d
: [out] "=w" (-> Vector(2, u64)),
: [x] "w" (@as(Vector(2, u64), @bitCast(@as(u128, x)))),
[y] "w" (@as(Vector(2, u64), @bitCast(@as(u128, y)))),
);
return product[0];
}
fn clmul_soft(x: u64, y: u64) u64 {
const x0 = x & 0x1111111111111111;
const x1 = x & 0x2222222222222222;
const x2 = x & 0x4444444444444444;
const x3 = x & 0x8888888888888888;
const y0 = y & 0x1111111111111111;
const y1 = y & 0x2222222222222222;
const y2 = y & 0x4444444444444444;
const y3 = y & 0x8888888888888888;
var z0 = (x0 *% y0) ^ (x1 *% y3) ^ (x2 *% y2) ^ (x3 *% y1);
var z1 = (x0 *% y1) ^ (x1 *% y0) ^ (x2 *% y3) ^ (x3 *% y2);
var z2 = (x0 *% y2) ^ (x1 *% y1) ^ (x2 *% y0) ^ (x3 *% y3);
var z3 = (x0 *% y3) ^ (x1 *% y2) ^ (x2 *% y1) ^ (x3 *% y0);
z0 &= 0x1111111111111111;
z1 &= 0x2222222222222222;
z2 &= 0x4444444444444444;
z3 &= 0x8888888888888888;
return z0 | z1 | z2 | z3;
}
const has_pclmul = std.Target.x86.featureSetHas(builtin.cpu.features, .pclmul);
const has_avx = std.Target.x86.featureSetHas(builtin.cpu.features, .avx);
const has_armaes = std.Target.aarch64.featureSetHas(builtin.cpu.features, .aes);
const clmul = if (builtin.cpu.arch == .x86_64 and has_pclmul and has_avx) impl: {
break :impl clmul_pclmul;
} else if (builtin.cpu.arch == .aarch64 and has_armaes) impl: {
break :impl clmul_pmull;
} else impl: {
break :impl clmul_soft;
};
fn blocks(st: *Ghash, msg: []const u8) void {
assert(msg.len % 16 == 0); // GHASH blocks() expects full blocks
var y1 = st.y1;
var y0 = st.y0;
var i: usize = 0;
// 2-blocks aggregated reduction
if (builtin.mode != .ReleaseSmall) {
while (i + 32 <= msg.len) : (i += 32) {
// B0 * H^2 unreduced
y1 ^= mem.readIntBig(u64, msg[i..][0..8]);
y0 ^= mem.readIntBig(u64, msg[i..][8..16]);
const y1r = @bitReverse(y1);
const y0r = @bitReverse(y0);
const y2 = y0 ^ y1;
const y2r = y0r ^ y1r;
var z0 = clmul(y0, st.hh0);
var z1 = clmul(y1, st.hh1);
var z2 = clmul(y2, st.hh2) ^ z0 ^ z1;
var z0h = clmul(y0r, st.hh0r);
var z1h = clmul(y1r, st.hh1r);
var z2h = clmul(y2r, st.hh2r) ^ z0h ^ z1h;
// B1 * H unreduced
const sy1 = mem.readIntBig(u64, msg[i..][16..24]);
const sy0 = mem.readIntBig(u64, msg[i..][24..32]);
const sy1r = @bitReverse(sy1);
const sy0r = @bitReverse(sy0);
const sy2 = sy0 ^ sy1;
const sy2r = sy0r ^ sy1r;
const sz0 = clmul(sy0, st.h0);
const sz1 = clmul(sy1, st.h1);
const sz2 = clmul(sy2, st.h2) ^ sz0 ^ sz1;
const sz0h = clmul(sy0r, st.h0r);
const sz1h = clmul(sy1r, st.h1r);
const sz2h = clmul(sy2r, st.h2r) ^ sz0h ^ sz1h;
// ((B0 * H^2) + B1 * H) (mod M)
z0 ^= sz0;
z1 ^= sz1;
z2 ^= sz2;
z0h ^= sz0h;
z1h ^= sz1h;
z2h ^= sz2h;
z0h = @bitReverse(z0h) >> 1;
z1h = @bitReverse(z1h) >> 1;
z2h = @bitReverse(z2h) >> 1;
var v3 = z1h;
var v2 = z1 ^ z2h;
var v1 = z0h ^ z2;
var v0 = z0;
v3 = (v3 << 1) | (v2 >> 63);
v2 = (v2 << 1) | (v1 >> 63);
v1 = (v1 << 1) | (v0 >> 63);
v0 = (v0 << 1);
v2 ^= v0 ^ (v0 >> 1) ^ (v0 >> 2) ^ (v0 >> 7);
v1 ^= (v0 << 63) ^ (v0 << 62) ^ (v0 << 57);
y1 = v3 ^ v1 ^ (v1 >> 1) ^ (v1 >> 2) ^ (v1 >> 7);
y0 = v2 ^ (v1 << 63) ^ (v1 << 62) ^ (v1 << 57);
}
}
// single block
while (i + 16 <= msg.len) : (i += 16) {
y1 ^= mem.readIntBig(u64, msg[i..][0..8]);
y0 ^= mem.readIntBig(u64, msg[i..][8..16]);
const y1r = @bitReverse(y1);
const y0r = @bitReverse(y0);
const y2 = y0 ^ y1;
const y2r = y0r ^ y1r;
const z0 = clmul(y0, st.h0);
const z1 = clmul(y1, st.h1);
var z2 = clmul(y2, st.h2) ^ z0 ^ z1;
var z0h = clmul(y0r, st.h0r);
var z1h = clmul(y1r, st.h1r);
var z2h = clmul(y2r, st.h2r) ^ z0h ^ z1h;
z0h = @bitReverse(z0h) >> 1;
z1h = @bitReverse(z1h) >> 1;
z2h = @bitReverse(z2h) >> 1;
// shift & reduce
var v3 = z1h;
var v2 = z1 ^ z2h;
var v1 = z0h ^ z2;
var v0 = z0;
v3 = (v3 << 1) | (v2 >> 63);
v2 = (v2 << 1) | (v1 >> 63);
v1 = (v1 << 1) | (v0 >> 63);
v0 = (v0 << 1);
v2 ^= v0 ^ (v0 >> 1) ^ (v0 >> 2) ^ (v0 >> 7);
v1 ^= (v0 << 63) ^ (v0 << 62) ^ (v0 << 57);
y1 = v3 ^ v1 ^ (v1 >> 1) ^ (v1 >> 2) ^ (v1 >> 7);
y0 = v2 ^ (v1 << 63) ^ (v1 << 62) ^ (v1 << 57);
}
st.y1 = y1;
st.y0 = y0;
}
pub fn update(st: *Ghash, m: []const u8) void {
var mb = m;
if (st.leftover > 0) {
const want = math.min(block_length - st.leftover, mb.len);
const mc = mb[0..want];
for (mc, 0..) |x, i| {
st.buf[st.leftover + i] = x;
}
mb = mb[want..];
st.leftover += want;
if (st.leftover < block_length) {
return;
}
st.blocks(&st.buf);
st.leftover = 0;
}
if (mb.len >= block_length) {
const want = mb.len & ~(block_length - 1);
st.blocks(mb[0..want]);
mb = mb[want..];
}
if (mb.len > 0) {
for (mb, 0..) |x, i| {
st.buf[st.leftover + i] = x;
}
st.leftover += mb.len;
}
}
/// Zero-pad to align the next input to the first byte of a block
pub fn pad(st: *Ghash) void {
if (st.leftover == 0) {
return;
}
var i = st.leftover;
while (i < block_length) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf);
st.leftover = 0;
}
pub fn final(st: *Ghash, out: *[mac_length]u8) void {
st.pad();
mem.writeIntBig(u64, out[0..8], st.y1);
mem.writeIntBig(u64, out[8..16], st.y0);
utils.secureZero(u8, @as([*]u8, @ptrCast(st))[0..@sizeOf(Ghash)]);
}
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [key_length]u8) void {
var st = Ghash.init(key);
st.update(msg);
st.final(out);
}
};
const htest = @import("test.zig");
test "ghash" {
const key = [_]u8{0x42} ** 16;
const m = [_]u8{0x69} ** 256;
var st = Ghash.init(&key);
st.update(&m);
var out: [16]u8 = undefined;
st.final(&out);
try htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
st = Ghash.init(&key);
st.update(m[0..100]);
st.update(m[100..]);
st.final(&out);
try htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/poly1305.zig | const std = @import("../std.zig");
const utils = std.crypto.utils;
const mem = std.mem;
pub const Poly1305 = struct {
pub const block_length: usize = 16;
pub const mac_length = 16;
pub const key_length = 32;
// constant multiplier (from the secret key)
r: [3]u64,
// accumulated hash
h: [3]u64 = [_]u64{ 0, 0, 0 },
// random number added at the end (from the secret key)
pad: [2]u64,
// how many bytes are waiting to be processed in a partial block
leftover: usize = 0,
// partial block buffer
buf: [block_length]u8 align(16) = undefined,
pub fn init(key: *const [key_length]u8) Poly1305 {
const t0 = mem.readIntLittle(u64, key[0..8]);
const t1 = mem.readIntLittle(u64, key[8..16]);
return Poly1305{
.r = [_]u64{
t0 & 0xffc0fffffff,
((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff,
((t1 >> 24)) & 0x00ffffffc0f,
},
.pad = [_]u64{
mem.readIntLittle(u64, key[16..24]),
mem.readIntLittle(u64, key[24..32]),
},
};
}
fn blocks(st: *Poly1305, m: []const u8, comptime last: bool) void {
const hibit: u64 = if (last) 0 else 1 << 40;
const r0 = st.r[0];
const r1 = st.r[1];
const r2 = st.r[2];
var h0 = st.h[0];
var h1 = st.h[1];
var h2 = st.h[2];
const s1 = r1 * (5 << 2);
const s2 = r2 * (5 << 2);
var i: usize = 0;
while (i + block_length <= m.len) : (i += block_length) {
// h += m[i]
const t0 = mem.readIntLittle(u64, m[i..][0..8]);
const t1 = mem.readIntLittle(u64, m[i + 8 ..][0..8]);
h0 += @as(u44, @truncate(t0));
h1 += @as(u44, @truncate((t0 >> 44) | (t1 << 20)));
h2 += @as(u42, @truncate(t1 >> 24)) | hibit;
// h *= r
const d0 = @as(u128, h0) * r0 + @as(u128, h1) * s2 + @as(u128, h2) * s1;
var d1 = @as(u128, h0) * r1 + @as(u128, h1) * r0 + @as(u128, h2) * s2;
var d2 = @as(u128, h0) * r2 + @as(u128, h1) * r1 + @as(u128, h2) * r0;
// partial reduction
var carry = @as(u64, @intCast(d0 >> 44));
h0 = @as(u44, @truncate(d0));
d1 += carry;
carry = @as(u64, @intCast(d1 >> 44));
h1 = @as(u44, @truncate(d1));
d2 += carry;
carry = @as(u64, @intCast(d2 >> 42));
h2 = @as(u42, @truncate(d2));
h0 += @as(u64, @truncate(carry)) * 5;
carry = h0 >> 44;
h0 = @as(u44, @truncate(h0));
h1 += carry;
}
st.h = [_]u64{ h0, h1, h2 };
}
pub fn update(st: *Poly1305, m: []const u8) void {
var mb = m;
// handle leftover
if (st.leftover > 0) {
const want = std.math.min(block_length - st.leftover, mb.len);
const mc = mb[0..want];
for (mc, 0..) |x, i| {
st.buf[st.leftover + i] = x;
}
mb = mb[want..];
st.leftover += want;
if (st.leftover < block_length) {
return;
}
st.blocks(&st.buf, false);
st.leftover = 0;
}
// process full blocks
if (mb.len >= block_length) {
const want = mb.len & ~(block_length - 1);
st.blocks(mb[0..want], false);
mb = mb[want..];
}
// store leftover
if (mb.len > 0) {
for (mb, 0..) |x, i| {
st.buf[st.leftover + i] = x;
}
st.leftover += mb.len;
}
}
/// Zero-pad to align the next input to the first byte of a block
pub fn pad(st: *Poly1305) void {
if (st.leftover == 0) {
return;
}
var i = st.leftover;
while (i < block_length) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf);
st.leftover = 0;
}
pub fn final(st: *Poly1305, out: *[mac_length]u8) void {
if (st.leftover > 0) {
var i = st.leftover;
st.buf[i] = 1;
i += 1;
while (i < block_length) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf, true);
}
// fully carry h
var carry = st.h[1] >> 44;
st.h[1] = @as(u44, @truncate(st.h[1]));
st.h[2] += carry;
carry = st.h[2] >> 42;
st.h[2] = @as(u42, @truncate(st.h[2]));
st.h[0] += carry * 5;
carry = st.h[0] >> 44;
st.h[0] = @as(u44, @truncate(st.h[0]));
st.h[1] += carry;
carry = st.h[1] >> 44;
st.h[1] = @as(u44, @truncate(st.h[1]));
st.h[2] += carry;
carry = st.h[2] >> 42;
st.h[2] = @as(u42, @truncate(st.h[2]));
st.h[0] += carry * 5;
carry = st.h[0] >> 44;
st.h[0] = @as(u44, @truncate(st.h[0]));
st.h[1] += carry;
// compute h + -p
var g0 = st.h[0] + 5;
carry = g0 >> 44;
g0 = @as(u44, @truncate(g0));
var g1 = st.h[1] + carry;
carry = g1 >> 44;
g1 = @as(u44, @truncate(g1));
var g2 = st.h[2] + carry -% (1 << 42);
// (hopefully) constant-time select h if h < p, or h + -p if h >= p
const mask = (g2 >> 63) -% 1;
g0 &= mask;
g1 &= mask;
g2 &= mask;
const nmask = ~mask;
st.h[0] = (st.h[0] & nmask) | g0;
st.h[1] = (st.h[1] & nmask) | g1;
st.h[2] = (st.h[2] & nmask) | g2;
// h = (h + pad)
const t0 = st.pad[0];
const t1 = st.pad[1];
st.h[0] += @as(u44, @truncate(t0));
carry = st.h[0] >> 44;
st.h[0] = @as(u44, @truncate(st.h[0]));
st.h[1] += @as(u44, @truncate((t0 >> 44) | (t1 << 20))) + carry;
carry = st.h[1] >> 44;
st.h[1] = @as(u44, @truncate(st.h[1]));
st.h[2] += @as(u42, @truncate(t1 >> 24)) + carry;
st.h[2] = @as(u42, @truncate(st.h[2]));
// mac = h % (2^128)
st.h[0] |= st.h[1] << 44;
st.h[1] = (st.h[1] >> 20) | (st.h[2] << 24);
mem.writeIntLittle(u64, out[0..8], st.h[0]);
mem.writeIntLittle(u64, out[8..16], st.h[1]);
utils.secureZero(u8, @as([*]u8, @ptrCast(st))[0..@sizeOf(Poly1305)]);
}
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [key_length]u8) void {
var st = Poly1305.init(key);
st.update(msg);
st.final(out);
}
};
test "poly1305 rfc7439 vector1" {
const expected_mac = "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9";
const msg = "Cryptographic Forum Research Group";
const key = "\x85\xd6\xbe\x78\x57\x55\x6d\x33\x7f\x44\x52\xfe\x42\xd5\x06\xa8" ++
"\x01\x03\x80\x8a\xfb\x0d\xb2\xfd\x4a\xbf\xf6\xaf\x41\x49\xf5\x1b";
var mac: [16]u8 = undefined;
Poly1305.create(mac[0..], msg, key);
try std.testing.expectEqualSlices(u8, expected_mac, &mac);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/sha1.zig | const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const RoundParam = struct {
a: usize,
b: usize,
c: usize,
d: usize,
e: usize,
i: u32,
};
fn roundParam(a: usize, b: usize, c: usize, d: usize, e: usize, i: u32) RoundParam {
return RoundParam{
.a = a,
.b = b,
.c = c,
.d = d,
.e = e,
.i = i,
};
}
/// The SHA-1 function is now considered cryptographically broken.
/// Namely, it is feasible to find multiple inputs producing the same hash.
/// For a fast-performing, cryptographically secure hash function, see SHA512/256, BLAKE2 or BLAKE3.
pub const Sha1 = struct {
const Self = @This();
pub const block_length = 64;
pub const digest_length = 20;
pub const Options = struct {};
s: [5]u32,
// Streaming Cache
buf: [64]u8 = undefined,
buf_len: u8 = 0,
total_len: u64 = 0,
pub fn init(options: Options) Self {
_ = options;
return Self{
.s = [_]u32{
0x67452301,
0xEFCDAB89,
0x98BADCFE,
0x10325476,
0xC3D2E1F0,
},
};
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Sha1.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len >= 64) {
off += 64 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.round(d.buf[0..]);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 64 <= b.len) : (off += 64) {
d.round(b[off..][0..64]);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @as(u8, @intCast(b[off..].len));
d.total_len += b.len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// The buffer here will never be completely full.
mem.set(u8, d.buf[d.buf_len..], 0);
// Append padding bits.
d.buf[d.buf_len] = 0x80;
d.buf_len += 1;
// > 448 mod 512 so need to add an extra round to wrap around.
if (64 - d.buf_len < 8) {
d.round(d.buf[0..]);
mem.set(u8, d.buf[0..], 0);
}
// Append message length.
var i: usize = 1;
var len = d.total_len >> 5;
d.buf[63] = @as(u8, @intCast(d.total_len & 0x1f)) << 3;
while (i < 8) : (i += 1) {
d.buf[63 - i] = @as(u8, @intCast(len & 0xff));
len >>= 8;
}
d.round(d.buf[0..]);
for (d.s, 0..) |s, j| {
mem.writeIntBig(u32, out[4 * j ..][0..4], s);
}
}
fn round(d: *Self, b: *const [64]u8) void {
var s: [16]u32 = undefined;
var v: [5]u32 = [_]u32{
d.s[0],
d.s[1],
d.s[2],
d.s[3],
d.s[4],
};
const round0a = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 0),
roundParam(4, 0, 1, 2, 3, 1),
roundParam(3, 4, 0, 1, 2, 2),
roundParam(2, 3, 4, 0, 1, 3),
roundParam(1, 2, 3, 4, 0, 4),
roundParam(0, 1, 2, 3, 4, 5),
roundParam(4, 0, 1, 2, 3, 6),
roundParam(3, 4, 0, 1, 2, 7),
roundParam(2, 3, 4, 0, 1, 8),
roundParam(1, 2, 3, 4, 0, 9),
roundParam(0, 1, 2, 3, 4, 10),
roundParam(4, 0, 1, 2, 3, 11),
roundParam(3, 4, 0, 1, 2, 12),
roundParam(2, 3, 4, 0, 1, 13),
roundParam(1, 2, 3, 4, 0, 14),
roundParam(0, 1, 2, 3, 4, 15),
};
inline for (round0a) |r| {
s[r.i] = (@as(u32, b[r.i * 4 + 0]) << 24) | (@as(u32, b[r.i * 4 + 1]) << 16) | (@as(u32, b[r.i * 4 + 2]) << 8) | (@as(u32, b[r.i * 4 + 3]) << 0);
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round0b = comptime [_]RoundParam{
roundParam(4, 0, 1, 2, 3, 16),
roundParam(3, 4, 0, 1, 2, 17),
roundParam(2, 3, 4, 0, 1, 18),
roundParam(1, 2, 3, 4, 0, 19),
};
inline for (round0b) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round1 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 20),
roundParam(4, 0, 1, 2, 3, 21),
roundParam(3, 4, 0, 1, 2, 22),
roundParam(2, 3, 4, 0, 1, 23),
roundParam(1, 2, 3, 4, 0, 24),
roundParam(0, 1, 2, 3, 4, 25),
roundParam(4, 0, 1, 2, 3, 26),
roundParam(3, 4, 0, 1, 2, 27),
roundParam(2, 3, 4, 0, 1, 28),
roundParam(1, 2, 3, 4, 0, 29),
roundParam(0, 1, 2, 3, 4, 30),
roundParam(4, 0, 1, 2, 3, 31),
roundParam(3, 4, 0, 1, 2, 32),
roundParam(2, 3, 4, 0, 1, 33),
roundParam(1, 2, 3, 4, 0, 34),
roundParam(0, 1, 2, 3, 4, 35),
roundParam(4, 0, 1, 2, 3, 36),
roundParam(3, 4, 0, 1, 2, 37),
roundParam(2, 3, 4, 0, 1, 38),
roundParam(1, 2, 3, 4, 0, 39),
};
inline for (round1) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round2 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 40),
roundParam(4, 0, 1, 2, 3, 41),
roundParam(3, 4, 0, 1, 2, 42),
roundParam(2, 3, 4, 0, 1, 43),
roundParam(1, 2, 3, 4, 0, 44),
roundParam(0, 1, 2, 3, 4, 45),
roundParam(4, 0, 1, 2, 3, 46),
roundParam(3, 4, 0, 1, 2, 47),
roundParam(2, 3, 4, 0, 1, 48),
roundParam(1, 2, 3, 4, 0, 49),
roundParam(0, 1, 2, 3, 4, 50),
roundParam(4, 0, 1, 2, 3, 51),
roundParam(3, 4, 0, 1, 2, 52),
roundParam(2, 3, 4, 0, 1, 53),
roundParam(1, 2, 3, 4, 0, 54),
roundParam(0, 1, 2, 3, 4, 55),
roundParam(4, 0, 1, 2, 3, 56),
roundParam(3, 4, 0, 1, 2, 57),
roundParam(2, 3, 4, 0, 1, 58),
roundParam(1, 2, 3, 4, 0, 59),
};
inline for (round2) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x8F1BBCDC +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round3 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 60),
roundParam(4, 0, 1, 2, 3, 61),
roundParam(3, 4, 0, 1, 2, 62),
roundParam(2, 3, 4, 0, 1, 63),
roundParam(1, 2, 3, 4, 0, 64),
roundParam(0, 1, 2, 3, 4, 65),
roundParam(4, 0, 1, 2, 3, 66),
roundParam(3, 4, 0, 1, 2, 67),
roundParam(2, 3, 4, 0, 1, 68),
roundParam(1, 2, 3, 4, 0, 69),
roundParam(0, 1, 2, 3, 4, 70),
roundParam(4, 0, 1, 2, 3, 71),
roundParam(3, 4, 0, 1, 2, 72),
roundParam(2, 3, 4, 0, 1, 73),
roundParam(1, 2, 3, 4, 0, 74),
roundParam(0, 1, 2, 3, 4, 75),
roundParam(4, 0, 1, 2, 3, 76),
roundParam(3, 4, 0, 1, 2, 77),
roundParam(2, 3, 4, 0, 1, 78),
roundParam(1, 2, 3, 4, 0, 79),
};
inline for (round3) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0xCA62C1D6 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
d.s[0] +%= v[0];
d.s[1] +%= v[1];
d.s[2] +%= v[2];
d.s[3] +%= v[3];
d.s[4] +%= v[4];
}
};
const htest = @import("test.zig");
test "sha1 single" {
try htest.assertEqualHash(Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709", "");
try htest.assertEqualHash(Sha1, "a9993e364706816aba3e25717850c26c9cd0d89d", "abc");
try htest.assertEqualHash(Sha1, "a49b2446a02c645bf419f995b67091253a04a259", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha1 streaming" {
var h = Sha1.init(.{});
var out: [20]u8 = undefined;
h.final(&out);
try htest.assertEqual("da39a3ee5e6b4b0d3255bfef95601890afd80709", out[0..]);
h = Sha1.init(.{});
h.update("abc");
h.final(&out);
try htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
h = Sha1.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(&out);
try htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
}
test "sha1 aligned final" {
var block = [_]u8{0} ** Sha1.block_length;
var out: [Sha1.digest_length]u8 = undefined;
var h = Sha1.init(.{});
h.update(&block);
h.final(out[0..]);
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/gimli.zig | //! Gimli is a 384-bit permutation designed to achieve high security with high
//! performance across a broad range of platforms, including 64-bit Intel/AMD
//! server CPUs, 64-bit and 32-bit ARM smartphone CPUs, 32-bit ARM
//! microcontrollers, 8-bit AVR microcontrollers, FPGAs, ASICs without
//! side-channel protection, and ASICs with side-channel protection.
//!
//! https://gimli.cr.yp.to/
//! https://csrc.nist.gov/CSRC/media/Projects/Lightweight-Cryptography/documents/round-1/spec-doc/gimli-spec.pdf
const std = @import("../std.zig");
const builtin = @import("builtin");
const mem = std.mem;
const math = std.math;
const debug = std.debug;
const assert = std.debug.assert;
const testing = std.testing;
const htest = @import("test.zig");
const Vector = std.meta.Vector;
const AuthenticationError = std.crypto.errors.AuthenticationError;
pub const State = struct {
pub const BLOCKBYTES = 48;
pub const RATE = 16;
data: [BLOCKBYTES / 4]u32 align(16),
const Self = @This();
pub fn init(initial_state: [State.BLOCKBYTES]u8) Self {
var data: [BLOCKBYTES / 4]u32 = undefined;
var i: usize = 0;
while (i < State.BLOCKBYTES) : (i += 4) {
data[i / 4] = mem.readIntNative(u32, initial_state[i..][0..4]);
}
return Self{ .data = data };
}
/// TODO follow the span() convention instead of having this and `toSliceConst`
pub fn toSlice(self: *Self) *[BLOCKBYTES]u8 {
return mem.asBytes(&self.data);
}
/// TODO follow the span() convention instead of having this and `toSlice`
pub fn toSliceConst(self: *const Self) *const [BLOCKBYTES]u8 {
return mem.asBytes(&self.data);
}
inline fn endianSwap(self: *Self) void {
for (self.data) |*w| {
w.* = mem.littleToNative(u32, w.*);
}
}
fn permute_unrolled(self: *Self) void {
self.endianSwap();
const state = &self.data;
comptime var round = @as(u32, 24);
inline while (round > 0) : (round -= 1) {
var column = @as(usize, 0);
while (column < 4) : (column += 1) {
const x = math.rotl(u32, state[column], 24);
const y = math.rotl(u32, state[4 + column], 9);
const z = state[8 + column];
state[8 + column] = ((x ^ (z << 1)) ^ ((y & z) << 2));
state[4 + column] = ((y ^ x) ^ ((x | z) << 1));
state[column] = ((z ^ y) ^ ((x & y) << 3));
}
switch (round & 3) {
0 => {
mem.swap(u32, &state[0], &state[1]);
mem.swap(u32, &state[2], &state[3]);
state[0] ^= round | 0x9e377900;
},
2 => {
mem.swap(u32, &state[0], &state[2]);
mem.swap(u32, &state[1], &state[3]);
},
else => {},
}
}
self.endianSwap();
}
fn permute_small(self: *Self) void {
self.endianSwap();
const state = &self.data;
var round = @as(u32, 24);
while (round > 0) : (round -= 1) {
var column = @as(usize, 0);
while (column < 4) : (column += 1) {
const x = math.rotl(u32, state[column], 24);
const y = math.rotl(u32, state[4 + column], 9);
const z = state[8 + column];
state[8 + column] = ((x ^ (z << 1)) ^ ((y & z) << 2));
state[4 + column] = ((y ^ x) ^ ((x | z) << 1));
state[column] = ((z ^ y) ^ ((x & y) << 3));
}
switch (round & 3) {
0 => {
mem.swap(u32, &state[0], &state[1]);
mem.swap(u32, &state[2], &state[3]);
state[0] ^= round | 0x9e377900;
},
2 => {
mem.swap(u32, &state[0], &state[2]);
mem.swap(u32, &state[1], &state[3]);
},
else => {},
}
}
self.endianSwap();
}
const Lane = Vector(4, u32);
inline fn shift(x: Lane, comptime n: comptime_int) Lane {
return x << @splat(n);
}
fn permute_vectorized(self: *Self) void {
self.endianSwap();
const state = &self.data;
var x = Lane{ state[0], state[1], state[2], state[3] };
var y = Lane{ state[4], state[5], state[6], state[7] };
var z = Lane{ state[8], state[9], state[10], state[11] };
var round = @as(u32, 24);
while (round > 0) : (round -= 1) {
x = math.rotl(Lane, x, 24);
y = math.rotl(Lane, y, 9);
const newz = x ^ shift(z, 1) ^ shift(y & z, 2);
const newy = y ^ x ^ shift(x | z, 1);
const newx = z ^ y ^ shift(x & y, 3);
x = newx;
y = newy;
z = newz;
switch (round & 3) {
0 => {
x = @shuffle(u32, x, undefined, [_]i32{ 1, 0, 3, 2 });
x[0] ^= round | 0x9e377900;
},
2 => {
x = @shuffle(u32, x, undefined, [_]i32{ 2, 3, 0, 1 });
},
else => {},
}
}
comptime var i: usize = 0;
inline while (i < 4) : (i += 1) {
state[0 + i] = x[i];
state[4 + i] = y[i];
state[8 + i] = z[i];
}
self.endianSwap();
}
pub const permute = if (builtin.cpu.arch == .x86_64) impl: {
break :impl permute_vectorized;
} else if (builtin.mode == .ReleaseSmall) impl: {
break :impl permute_small;
} else impl: {
break :impl permute_unrolled;
};
pub fn squeeze(self: *Self, out: []u8) void {
var i = @as(usize, 0);
while (i + RATE <= out.len) : (i += RATE) {
self.permute();
mem.copy(u8, out[i..], self.toSliceConst()[0..RATE]);
}
const leftover = out.len - i;
if (leftover != 0) {
self.permute();
mem.copy(u8, out[i..], self.toSliceConst()[0..leftover]);
}
}
};
test "permute" {
// test vector from gimli-20170627
const tv_input = [3][4]u32{
[4]u32{ 0x00000000, 0x9e3779ba, 0x3c6ef37a, 0xdaa66d46 },
[4]u32{ 0x78dde724, 0x1715611a, 0xb54cdb2e, 0x53845566 },
[4]u32{ 0xf1bbcfc8, 0x8ff34a5a, 0x2e2ac522, 0xcc624026 },
};
var input: [48]u8 = undefined;
var i: usize = 0;
while (i < 12) : (i += 1) {
mem.writeIntLittle(u32, input[i * 4 ..][0..4], tv_input[i / 4][i % 4]);
}
var state = State.init(input);
state.permute();
const tv_output = [3][4]u32{
[4]u32{ 0xba11c85a, 0x91bad119, 0x380ce880, 0xd24c2c68 },
[4]u32{ 0x3eceffea, 0x277a921c, 0x4f73a0bd, 0xda5a9cd8 },
[4]u32{ 0x84b673f0, 0x34e52ff7, 0x9e2bef49, 0xf41bb8d6 },
};
var expected_output: [48]u8 = undefined;
i = 0;
while (i < 12) : (i += 1) {
mem.writeIntLittle(u32, expected_output[i * 4 ..][0..4], tv_output[i / 4][i % 4]);
}
try testing.expectEqualSlices(u8, state.toSliceConst(), expected_output[0..]);
}
pub const Hash = struct {
state: State,
buf_off: usize,
pub const block_length = State.RATE;
pub const digest_length = 32;
pub const Options = struct {};
const Self = @This();
pub fn init(options: Options) Self {
_ = options;
return Self{
.state = State{ .data = [_]u32{0} ** (State.BLOCKBYTES / 4) },
.buf_off = 0,
};
}
/// Also known as 'absorb'
pub fn update(self: *Self, data: []const u8) void {
const buf = self.state.toSlice();
var in = data;
while (in.len > 0) {
const left = State.RATE - self.buf_off;
const ps = math.min(in.len, left);
for (buf[self.buf_off .. self.buf_off + ps], 0..) |*p, i| {
p.* ^= in[i];
}
self.buf_off += ps;
in = in[ps..];
if (self.buf_off == State.RATE) {
self.state.permute();
self.buf_off = 0;
}
}
}
/// Finish the current hashing operation, writing the hash to `out`
///
/// From 4.9 "Application to hashing"
/// By default, Gimli-Hash provides a fixed-length output of 32 bytes
/// (the concatenation of two 16-byte blocks). However, Gimli-Hash can
/// be used as an “extendable one-way function” (XOF).
pub fn final(self: *Self, out: []u8) void {
const buf = self.state.toSlice();
// XOR 1 into the next byte of the state
buf[self.buf_off] ^= 1;
// XOR 1 into the last byte of the state, position 47.
buf[buf.len - 1] ^= 1;
self.state.squeeze(out);
}
};
pub fn hash(out: []u8, in: []const u8, options: Hash.Options) void {
var st = Hash.init(options);
st.update(in);
st.final(out);
}
test "hash" {
// a test vector (30) from NIST KAT submission.
var msg: [58 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
try htest.assertEqual("1C9A03DC6A5DDC5444CFC6F4B154CFF5CF081633B2CEA4D7D0AE7CCFED5AAA44", &md);
}
test "hash test vector 17" {
var msg: [32 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
try htest.assertEqual("404C130AF1B9023A7908200919F690FFBB756D5176E056FFDE320016A37C7282", &md);
}
test "hash test vector 33" {
var msg: [32]u8 = undefined;
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
try htest.assertEqual("A8F4FA28708BDA7EFB4C1914CA4AFA9E475B82D588D36504F87DBB0ED9AB3C4B", &md);
}
pub const Aead = struct {
pub const tag_length = State.RATE;
pub const nonce_length = 16;
pub const key_length = 32;
/// ad: Associated Data
/// npub: public nonce
/// k: private key
fn init(ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) State {
var state = State{
.data = undefined,
};
const buf = state.toSlice();
// Gimli-Cipher initializes a 48-byte Gimli state to a 16-byte nonce
// followed by a 32-byte key.
assert(npub.len + k.len == State.BLOCKBYTES);
std.mem.copy(u8, buf[0..npub.len], &npub);
std.mem.copy(u8, buf[npub.len .. npub.len + k.len], &k);
// It then applies the Gimli permutation.
state.permute();
{
// Gimli-Cipher then handles each block of associated data, including
// exactly one final non-full block, in the same way as Gimli-Hash.
var data = ad;
while (data.len >= State.RATE) : (data = data[State.RATE..]) {
for (buf[0..State.RATE], 0..) |*p, i| {
p.* ^= data[i];
}
state.permute();
}
for (buf[0..data.len], 0..) |*p, i| {
p.* ^= data[i];
}
// XOR 1 into the next byte of the state
buf[data.len] ^= 1;
// XOR 1 into the last byte of the state, position 47.
buf[buf.len - 1] ^= 1;
state.permute();
}
return state;
}
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
assert(c.len == m.len);
var state = Aead.init(ad, npub, k);
const buf = state.toSlice();
// Gimli-Cipher then handles each block of plaintext, including
// exactly one final non-full block, in the same way as Gimli-Hash.
// Whenever a plaintext byte is XORed into a state byte, the new state
// byte is output as ciphertext.
var in = m;
var out = c;
while (in.len >= State.RATE) : ({
in = in[State.RATE..];
out = out[State.RATE..];
}) {
for (in[0..State.RATE], 0..) |v, i| {
buf[i] ^= v;
}
mem.copy(u8, out[0..State.RATE], buf[0..State.RATE]);
state.permute();
}
for (in[0..], 0..) |v, i| {
buf[i] ^= v;
out[i] = buf[i];
}
// XOR 1 into the next byte of the state
buf[in.len] ^= 1;
// XOR 1 into the last byte of the state, position 47.
buf[buf.len - 1] ^= 1;
state.permute();
// After the final non-full block of plaintext, the first 16 bytes
// of the state are output as an authentication tag.
std.mem.copy(u8, tag, buf[0..State.RATE]);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
/// NOTE: the check of the authentication tag is currently not done in constant time
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
assert(c.len == m.len);
var state = Aead.init(ad, npub, k);
const buf = state.toSlice();
var in = c;
var out = m;
while (in.len >= State.RATE) : ({
in = in[State.RATE..];
out = out[State.RATE..];
}) {
const d = in[0..State.RATE].*;
for (d, 0..) |v, i| {
out[i] = buf[i] ^ v;
}
mem.copy(u8, buf[0..State.RATE], d[0..State.RATE]);
state.permute();
}
for (buf[0..in.len], 0..) |*p, i| {
const d = in[i];
out[i] = p.* ^ d;
p.* = d;
}
// XOR 1 into the next byte of the state
buf[in.len] ^= 1;
// XOR 1 into the last byte of the state, position 47.
buf[buf.len - 1] ^= 1;
state.permute();
// After the final non-full block of plaintext, the first 16 bytes
// of the state are the authentication tag.
// TODO: use a constant-time equality check here, see https://github.com/ziglang/zig/issues/1776
if (!mem.eql(u8, buf[0..State.RATE], &tag)) {
@memset(m[0..], undefined);
return error.AuthenticationFailed;
}
}
};
test "cipher" {
var key: [32]u8 = undefined;
_ = try std.fmt.hexToBytes(&key, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
var nonce: [16]u8 = undefined;
_ = try std.fmt.hexToBytes(&nonce, "000102030405060708090A0B0C0D0E0F");
{ // test vector (1) from NIST KAT submission.
const ad: [0]u8 = undefined;
const pt: [0]u8 = undefined;
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
try htest.assertEqual("", &ct);
try htest.assertEqual("14DA9BB7120BF58B985A8E00FDEBA15B", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (34) from NIST KAT submission.
const ad: [0]u8 = undefined;
var pt: [2 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&pt, "00");
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
try htest.assertEqual("7F", &ct);
try htest.assertEqual("80492C317B1CD58A1EDC3A0D3E9876FC", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (106) from NIST KAT submission.
var ad: [12 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&ad, "000102030405");
var pt: [6 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&pt, "000102");
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
try htest.assertEqual("484D35", &ct);
try htest.assertEqual("030BBEA23B61C00CED60A923BDCF9147", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (790) from NIST KAT submission.
var ad: [60 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&ad, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D");
var pt: [46 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&pt, "000102030405060708090A0B0C0D0E0F10111213141516");
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
try htest.assertEqual("6815B4A0ECDAD01596EAD87D9E690697475D234C6A13D1", &ct);
try htest.assertEqual("DFE23F1642508290D68245279558B2FB", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (1057) from NIST KAT submission.
const ad: [0]u8 = undefined;
var pt: [64 / 2]u8 = undefined;
_ = try std.fmt.hexToBytes(&pt, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
try htest.assertEqual("7F8A2CF4F52AA4D6B2E74105C30A2777B9D0C8AEFDD555DE35861BD3011F652F", &ct);
try htest.assertEqual("7256456FA935AC34BBF55AE135F33257", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
}
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes/soft.zig | // Based on Go stdlib implementation
const std = @import("../../std.zig");
const mem = std.mem;
const BlockVec = [4]u32;
/// A single AES block.
pub const Block = struct {
pub const block_length: usize = 16;
/// Internal representation of a block.
repr: BlockVec align(16),
/// Convert a byte sequence into an internal representation.
pub inline fn fromBytes(bytes: *const [16]u8) Block {
const s0 = mem.readIntBig(u32, bytes[0..4]);
const s1 = mem.readIntBig(u32, bytes[4..8]);
const s2 = mem.readIntBig(u32, bytes[8..12]);
const s3 = mem.readIntBig(u32, bytes[12..16]);
return Block{ .repr = BlockVec{ s0, s1, s2, s3 } };
}
/// Convert the internal representation of a block into a byte sequence.
pub inline fn toBytes(block: Block) [16]u8 {
var bytes: [16]u8 = undefined;
mem.writeIntBig(u32, bytes[0..4], block.repr[0]);
mem.writeIntBig(u32, bytes[4..8], block.repr[1]);
mem.writeIntBig(u32, bytes[8..12], block.repr[2]);
mem.writeIntBig(u32, bytes[12..16], block.repr[3]);
return bytes;
}
/// XOR the block with a byte sequence.
pub inline fn xorBytes(block: Block, bytes: *const [16]u8) [16]u8 {
const block_bytes = block.toBytes();
var x: [16]u8 = undefined;
comptime var i: usize = 0;
inline while (i < 16) : (i += 1) {
x[i] = block_bytes[i] ^ bytes[i];
}
return x;
}
/// Encrypt a block with a round key.
pub inline fn encrypt(block: Block, round_key: Block) Block {
const s0 = block.repr[0];
const s1 = block.repr[1];
const s2 = block.repr[2];
const s3 = block.repr[3];
const t0 = round_key.repr[0] ^ te0[@as(u8, @truncate(s0 >> 24))] ^ te1[@as(u8, @truncate(s1 >> 16))] ^ te2[@as(u8, @truncate(s2 >> 8))] ^ te3[@as(u8, @truncate(s3))];
const t1 = round_key.repr[1] ^ te0[@as(u8, @truncate(s1 >> 24))] ^ te1[@as(u8, @truncate(s2 >> 16))] ^ te2[@as(u8, @truncate(s3 >> 8))] ^ te3[@as(u8, @truncate(s0))];
const t2 = round_key.repr[2] ^ te0[@as(u8, @truncate(s2 >> 24))] ^ te1[@as(u8, @truncate(s3 >> 16))] ^ te2[@as(u8, @truncate(s0 >> 8))] ^ te3[@as(u8, @truncate(s1))];
const t3 = round_key.repr[3] ^ te0[@as(u8, @truncate(s3 >> 24))] ^ te1[@as(u8, @truncate(s0 >> 16))] ^ te2[@as(u8, @truncate(s1 >> 8))] ^ te3[@as(u8, @truncate(s2))];
return Block{ .repr = BlockVec{ t0, t1, t2, t3 } };
}
/// Encrypt a block with the last round key.
pub inline fn encryptLast(block: Block, round_key: Block) Block {
const t0 = block.repr[0];
const t1 = block.repr[1];
const t2 = block.repr[2];
const t3 = block.repr[3];
// Last round uses s-box directly and XORs to produce output.
var s0 = @as(u32, sbox0[t0 >> 24]) << 24 | @as(u32, sbox0[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t3 & 0xff]);
var s1 = @as(u32, sbox0[t1 >> 24]) << 24 | @as(u32, sbox0[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t0 & 0xff]);
var s2 = @as(u32, sbox0[t2 >> 24]) << 24 | @as(u32, sbox0[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t1 & 0xff]);
var s3 = @as(u32, sbox0[t3 >> 24]) << 24 | @as(u32, sbox0[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t2 & 0xff]);
s0 ^= round_key.repr[0];
s1 ^= round_key.repr[1];
s2 ^= round_key.repr[2];
s3 ^= round_key.repr[3];
return Block{ .repr = BlockVec{ s0, s1, s2, s3 } };
}
/// Decrypt a block with a round key.
pub inline fn decrypt(block: Block, round_key: Block) Block {
const s0 = block.repr[0];
const s1 = block.repr[1];
const s2 = block.repr[2];
const s3 = block.repr[3];
const t0 = round_key.repr[0] ^ td0[@as(u8, @truncate(s0 >> 24))] ^ td1[@as(u8, @truncate(s3 >> 16))] ^ td2[@as(u8, @truncate(s2 >> 8))] ^ td3[@as(u8, @truncate(s1))];
const t1 = round_key.repr[1] ^ td0[@as(u8, @truncate(s1 >> 24))] ^ td1[@as(u8, @truncate(s0 >> 16))] ^ td2[@as(u8, @truncate(s3 >> 8))] ^ td3[@as(u8, @truncate(s2))];
const t2 = round_key.repr[2] ^ td0[@as(u8, @truncate(s2 >> 24))] ^ td1[@as(u8, @truncate(s1 >> 16))] ^ td2[@as(u8, @truncate(s0 >> 8))] ^ td3[@as(u8, @truncate(s3))];
const t3 = round_key.repr[3] ^ td0[@as(u8, @truncate(s3 >> 24))] ^ td1[@as(u8, @truncate(s2 >> 16))] ^ td2[@as(u8, @truncate(s1 >> 8))] ^ td3[@as(u8, @truncate(s0))];
return Block{ .repr = BlockVec{ t0, t1, t2, t3 } };
}
/// Decrypt a block with the last round key.
pub inline fn decryptLast(block: Block, round_key: Block) Block {
const t0 = block.repr[0];
const t1 = block.repr[1];
const t2 = block.repr[2];
const t3 = block.repr[3];
// Last round uses s-box directly and XORs to produce output.
var s0 = @as(u32, sbox1[t0 >> 24]) << 24 | @as(u32, sbox1[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t1 & 0xff]);
var s1 = @as(u32, sbox1[t1 >> 24]) << 24 | @as(u32, sbox1[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t2 & 0xff]);
var s2 = @as(u32, sbox1[t2 >> 24]) << 24 | @as(u32, sbox1[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t3 & 0xff]);
var s3 = @as(u32, sbox1[t3 >> 24]) << 24 | @as(u32, sbox1[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t0 & 0xff]);
s0 ^= round_key.repr[0];
s1 ^= round_key.repr[1];
s2 ^= round_key.repr[2];
s3 ^= round_key.repr[3];
return Block{ .repr = BlockVec{ s0, s1, s2, s3 } };
}
/// Apply the bitwise XOR operation to the content of two blocks.
pub inline fn xorBlocks(block1: Block, block2: Block) Block {
var x: BlockVec = undefined;
comptime var i = 0;
inline while (i < 4) : (i += 1) {
x[i] = block1.repr[i] ^ block2.repr[i];
}
return Block{ .repr = x };
}
/// Apply the bitwise AND operation to the content of two blocks.
pub inline fn andBlocks(block1: Block, block2: Block) Block {
var x: BlockVec = undefined;
comptime var i = 0;
inline while (i < 4) : (i += 1) {
x[i] = block1.repr[i] & block2.repr[i];
}
return Block{ .repr = x };
}
/// Apply the bitwise OR operation to the content of two blocks.
pub inline fn orBlocks(block1: Block, block2: Block) Block {
var x: BlockVec = undefined;
comptime var i = 0;
inline while (i < 4) : (i += 1) {
x[i] = block1.repr[i] | block2.repr[i];
}
return Block{ .repr = x };
}
/// Perform operations on multiple blocks in parallel.
pub const parallel = struct {
/// The recommended number of AES encryption/decryption to perform in parallel for the chosen implementation.
pub const optimal_parallel_blocks = 1;
/// Encrypt multiple blocks in parallel, each their own round key.
pub fn encryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].encrypt(round_keys[i]);
}
return out;
}
/// Decrypt multiple blocks in parallel, each their own round key.
pub fn decryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].decrypt(round_keys[i]);
}
return out;
}
/// Encrypt multiple blocks in parallel with the same round key.
pub fn encryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].encrypt(round_key);
}
return out;
}
/// Decrypt multiple blocks in parallel with the same round key.
pub fn decryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].decrypt(round_key);
}
return out;
}
/// Encrypt multiple blocks in parallel with the same last round key.
pub fn encryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].encryptLast(round_key);
}
return out;
}
/// Decrypt multiple blocks in parallel with the same last round key.
pub fn decryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
var i = 0;
var out: [count]Block = undefined;
while (i < count) : (i += 1) {
out[i] = blocks[i].decryptLast(round_key);
}
return out;
}
};
};
fn KeySchedule(comptime Aes: type) type {
std.debug.assert(Aes.rounds == 10 or Aes.rounds == 14);
const key_length = Aes.key_bits / 8;
const rounds = Aes.rounds;
return struct {
const Self = @This();
const words_in_key = key_length / 4;
round_keys: [rounds + 1]Block,
// Key expansion algorithm. See FIPS-197, Figure 11.
fn expandKey(key: [key_length]u8) Self {
const subw = struct {
// Apply sbox0 to each byte in w.
fn func(w: u32) u32 {
return @as(u32, sbox0[w >> 24]) << 24 | @as(u32, sbox0[w >> 16 & 0xff]) << 16 | @as(u32, sbox0[w >> 8 & 0xff]) << 8 | @as(u32, sbox0[w & 0xff]);
}
}.func;
var round_keys: [rounds + 1]Block = undefined;
comptime var i: usize = 0;
inline while (i < words_in_key) : (i += 1) {
round_keys[i / 4].repr[i % 4] = mem.readIntBig(u32, key[4 * i ..][0..4]);
}
inline while (i < round_keys.len * 4) : (i += 1) {
var t = round_keys[(i - 1) / 4].repr[(i - 1) % 4];
if (i % words_in_key == 0) {
t = subw(std.math.rotl(u32, t, 8)) ^ (@as(u32, powx[i / words_in_key - 1]) << 24);
} else if (words_in_key > 6 and i % words_in_key == 4) {
t = subw(t);
}
round_keys[i / 4].repr[i % 4] = round_keys[(i - words_in_key) / 4].repr[(i - words_in_key) % 4] ^ t;
}
return Self{ .round_keys = round_keys };
}
/// Invert the key schedule.
pub fn invert(key_schedule: Self) Self {
const round_keys = &key_schedule.round_keys;
var inv_round_keys: [rounds + 1]Block = undefined;
const total_words = 4 * round_keys.len;
var i: usize = 0;
while (i < total_words) : (i += 4) {
const ei = total_words - i - 4;
comptime var j: usize = 0;
inline while (j < 4) : (j += 1) {
var x = round_keys[(ei + j) / 4].repr[(ei + j) % 4];
if (i > 0 and i + 4 < total_words) {
x = td0[sbox0[x >> 24]] ^ td1[sbox0[x >> 16 & 0xff]] ^ td2[sbox0[x >> 8 & 0xff]] ^ td3[sbox0[x & 0xff]];
}
inv_round_keys[(i + j) / 4].repr[(i + j) % 4] = x;
}
}
return Self{ .round_keys = inv_round_keys };
}
};
}
/// A context to perform encryption using the standard AES key schedule.
pub fn AesEncryptCtx(comptime Aes: type) type {
std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256);
const rounds = Aes.rounds;
return struct {
const Self = @This();
pub const block = Aes.block;
pub const block_length = block.block_length;
key_schedule: KeySchedule(Aes),
/// Create a new encryption context with the given key.
pub fn init(key: [Aes.key_bits / 8]u8) Self {
const key_schedule = KeySchedule(Aes).expandKey(key);
return Self{
.key_schedule = key_schedule,
};
}
/// Encrypt a single block.
pub fn encrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(src).xorBlocks(round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.encrypt(round_keys[i]);
}
t = t.encryptLast(round_keys[rounds]);
dst.* = t.toBytes();
}
/// Encrypt+XOR a single block.
pub fn xor(ctx: Self, dst: *[16]u8, src: *const [16]u8, counter: [16]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(&counter).xorBlocks(round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.encrypt(round_keys[i]);
}
t = t.encryptLast(round_keys[rounds]);
dst.* = t.xorBytes(src);
}
/// Encrypt multiple blocks, possibly leveraging parallelization.
pub fn encryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void {
var i: usize = 0;
while (i < count) : (i += 1) {
ctx.encrypt(dst[16 * i .. 16 * i + 16][0..16], src[16 * i .. 16 * i + 16][0..16]);
}
}
/// Encrypt+XOR multiple blocks, possibly leveraging parallelization.
pub fn xorWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8, counters: [16 * count]u8) void {
var i: usize = 0;
while (i < count) : (i += 1) {
ctx.xor(dst[16 * i .. 16 * i + 16][0..16], src[16 * i .. 16 * i + 16][0..16], counters[16 * i .. 16 * i + 16][0..16].*);
}
}
};
}
/// A context to perform decryption using the standard AES key schedule.
pub fn AesDecryptCtx(comptime Aes: type) type {
std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256);
const rounds = Aes.rounds;
return struct {
const Self = @This();
pub const block = Aes.block;
pub const block_length = block.block_length;
key_schedule: KeySchedule(Aes),
/// Create a decryption context from an existing encryption context.
pub fn initFromEnc(ctx: AesEncryptCtx(Aes)) Self {
return Self{
.key_schedule = ctx.key_schedule.invert(),
};
}
/// Create a new decryption context with the given key.
pub fn init(key: [Aes.key_bits / 8]u8) Self {
const enc_ctx = AesEncryptCtx(Aes).init(key);
return initFromEnc(enc_ctx);
}
/// Decrypt a single block.
pub fn decrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void {
const inv_round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(src).xorBlocks(inv_round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.decrypt(inv_round_keys[i]);
}
t = t.decryptLast(inv_round_keys[rounds]);
dst.* = t.toBytes();
}
/// Decrypt multiple blocks, possibly leveraging parallelization.
pub fn decryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void {
var i: usize = 0;
while (i < count) : (i += 1) {
ctx.decrypt(dst[16 * i .. 16 * i + 16][0..16], src[16 * i .. 16 * i + 16][0..16]);
}
}
};
}
/// AES-128 with the standard key schedule.
pub const Aes128 = struct {
pub const key_bits: usize = 128;
pub const rounds = ((key_bits - 64) / 32 + 8);
pub const block = Block;
/// Create a new context for encryption.
pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes128) {
return AesEncryptCtx(Aes128).init(key);
}
/// Create a new context for decryption.
pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes128) {
return AesDecryptCtx(Aes128).init(key);
}
};
/// AES-256 with the standard key schedule.
pub const Aes256 = struct {
pub const key_bits: usize = 256;
pub const rounds = ((key_bits - 64) / 32 + 8);
pub const block = Block;
/// Create a new context for encryption.
pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes256) {
return AesEncryptCtx(Aes256).init(key);
}
/// Create a new context for decryption.
pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes256) {
return AesDecryptCtx(Aes256).init(key);
}
};
// constants
const powx = [16]u8{
0x01,
0x02,
0x04,
0x08,
0x10,
0x20,
0x40,
0x80,
0x1b,
0x36,
0x6c,
0xd8,
0xab,
0x4d,
0x9a,
0x2f,
};
const sbox0 align(64) = [256]u8{
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
};
const sbox1 align(64) = [256]u8{
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
};
const te0 align(64) = [256]u32{
0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554,
0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a,
0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b,
0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b,
0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f,
0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f,
0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5,
0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f,
0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb,
0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497,
0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed,
0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a,
0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594,
0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3,
0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504,
0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d,
0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739,
0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395,
0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883,
0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76,
0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4,
0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b,
0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0,
0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818,
0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651,
0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85,
0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12,
0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9,
0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7,
0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a,
0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8,
0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a,
};
const te1 align(64) = [256]u32{
0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5,
0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676,
0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0,
0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0,
0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc,
0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515,
0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a,
0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575,
0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0,
0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484,
0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b,
0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf,
0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585,
0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8,
0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5,
0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2,
0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717,
0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373,
0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888,
0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb,
0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c,
0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979,
0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9,
0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808,
0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6,
0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a,
0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e,
0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e,
0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494,
0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf,
0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868,
0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616,
};
const te2 align(64) = [256]u32{
0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5,
0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76,
0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0,
0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0,
0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc,
0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15,
0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a,
0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75,
0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0,
0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384,
0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b,
0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf,
0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185,
0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8,
0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5,
0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2,
0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17,
0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673,
0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88,
0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb,
0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c,
0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279,
0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9,
0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008,
0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6,
0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a,
0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e,
0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e,
0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394,
0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df,
0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068,
0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16,
};
const te3 align(64) = [256]u32{
0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491,
0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec,
0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb,
0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b,
0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83,
0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a,
0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f,
0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea,
0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b,
0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713,
0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6,
0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85,
0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411,
0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b,
0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1,
0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf,
0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e,
0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6,
0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b,
0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad,
0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8,
0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2,
0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049,
0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810,
0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197,
0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f,
0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c,
0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927,
0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733,
0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5,
0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0,
0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c,
};
const td0 align(64) = [256]u32{
0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393,
0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f,
0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6,
0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844,
0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4,
0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94,
0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a,
0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c,
0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a,
0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051,
0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff,
0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb,
0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e,
0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a,
0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16,
0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8,
0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34,
0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120,
0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0,
0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef,
0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4,
0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5,
0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b,
0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6,
0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0,
0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f,
0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f,
0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713,
0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c,
0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86,
0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541,
0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742,
};
const td1 align(64) = [256]u32{
0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303,
0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3,
0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9,
0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8,
0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a,
0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b,
0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab,
0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682,
0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe,
0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10,
0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015,
0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee,
0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72,
0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e,
0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a,
0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9,
0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e,
0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611,
0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3,
0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390,
0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf,
0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af,
0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb,
0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8,
0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266,
0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6,
0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551,
0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647,
0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1,
0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db,
0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95,
0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857,
};
const td2 align(64) = [256]u32{
0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3,
0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562,
0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3,
0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9,
0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce,
0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908,
0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655,
0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16,
0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6,
0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e,
0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050,
0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8,
0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a,
0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436,
0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12,
0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e,
0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb,
0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6,
0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1,
0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233,
0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad,
0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3,
0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b,
0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15,
0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2,
0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791,
0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665,
0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6,
0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47,
0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844,
0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d,
0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8,
};
const td3 align(64) = [256]u32{
0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b,
0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5,
0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b,
0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e,
0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d,
0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9,
0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66,
0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced,
0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4,
0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd,
0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60,
0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79,
0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c,
0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24,
0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c,
0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814,
0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b,
0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084,
0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077,
0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22,
0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f,
0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582,
0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb,
0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef,
0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035,
0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17,
0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46,
0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d,
0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a,
0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678,
0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff,
0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0,
};
|
0 | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto | repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes/armcrypto.zig | const std = @import("../../std.zig");
const mem = std.mem;
const debug = std.debug;
const Vector = std.meta.Vector;
const BlockVec = Vector(2, u64);
/// A single AES block.
pub const Block = struct {
pub const block_length: usize = 16;
/// Internal representation of a block.
repr: BlockVec,
/// Convert a byte sequence into an internal representation.
pub inline fn fromBytes(bytes: *const [16]u8) Block {
const repr = mem.bytesToValue(BlockVec, bytes);
return Block{ .repr = repr };
}
/// Convert the internal representation of a block into a byte sequence.
pub inline fn toBytes(block: Block) [16]u8 {
return mem.toBytes(block.repr);
}
/// XOR the block with a byte sequence.
pub inline fn xorBytes(block: Block, bytes: *const [16]u8) [16]u8 {
const x = block.repr ^ fromBytes(bytes).repr;
return mem.toBytes(x);
}
const zero = Vector(2, u64){ 0, 0 };
/// Encrypt a block with a round key.
pub inline fn encrypt(block: Block, round_key: Block) Block {
return Block{
.repr = asm (
\\ mov %[out].16b, %[in].16b
\\ aese %[out].16b, %[zero].16b
\\ aesmc %[out].16b, %[out].16b
\\ eor %[out].16b, %[out].16b, %[rk].16b
: [out] "=&x" (-> BlockVec),
: [in] "x" (block.repr),
[rk] "x" (round_key.repr),
[zero] "x" (zero),
),
};
}
/// Encrypt a block with the last round key.
pub inline fn encryptLast(block: Block, round_key: Block) Block {
return Block{
.repr = asm (
\\ mov %[out].16b, %[in].16b
\\ aese %[out].16b, %[zero].16b
\\ eor %[out].16b, %[out].16b, %[rk].16b
: [out] "=&x" (-> BlockVec),
: [in] "x" (block.repr),
[rk] "x" (round_key.repr),
[zero] "x" (zero),
),
};
}
/// Decrypt a block with a round key.
pub inline fn decrypt(block: Block, inv_round_key: Block) Block {
return Block{
.repr = asm (
\\ mov %[out].16b, %[in].16b
\\ aesd %[out].16b, %[zero].16b
\\ aesimc %[out].16b, %[out].16b
\\ eor %[out].16b, %[out].16b, %[rk].16b
: [out] "=&x" (-> BlockVec),
: [in] "x" (block.repr),
[rk] "x" (inv_round_key.repr),
[zero] "x" (zero),
),
};
}
/// Decrypt a block with the last round key.
pub inline fn decryptLast(block: Block, inv_round_key: Block) Block {
return Block{
.repr = asm (
\\ mov %[out].16b, %[in].16b
\\ aesd %[out].16b, %[zero].16b
\\ eor %[out].16b, %[out].16b, %[rk].16b
: [out] "=&x" (-> BlockVec),
: [in] "x" (block.repr),
[rk] "x" (inv_round_key.repr),
[zero] "x" (zero),
),
};
}
/// Apply the bitwise XOR operation to the content of two blocks.
pub inline fn xorBlocks(block1: Block, block2: Block) Block {
return Block{ .repr = block1.repr ^ block2.repr };
}
/// Apply the bitwise AND operation to the content of two blocks.
pub inline fn andBlocks(block1: Block, block2: Block) Block {
return Block{ .repr = block1.repr & block2.repr };
}
/// Apply the bitwise OR operation to the content of two blocks.
pub inline fn orBlocks(block1: Block, block2: Block) Block {
return Block{ .repr = block1.repr | block2.repr };
}
/// Perform operations on multiple blocks in parallel.
pub const parallel = struct {
/// The recommended number of AES encryption/decryption to perform in parallel for the chosen implementation.
pub const optimal_parallel_blocks = 8;
/// Encrypt multiple blocks in parallel, each their own round key.
pub inline fn encryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].encrypt(round_keys[i]);
}
return out;
}
/// Decrypt multiple blocks in parallel, each their own round key.
pub inline fn decryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].decrypt(round_keys[i]);
}
return out;
}
/// Encrypt multiple blocks in parallel with the same round key.
pub inline fn encryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].encrypt(round_key);
}
return out;
}
/// Decrypt multiple blocks in parallel with the same round key.
pub inline fn decryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].decrypt(round_key);
}
return out;
}
/// Encrypt multiple blocks in parallel with the same last round key.
pub inline fn encryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].encryptLast(round_key);
}
return out;
}
/// Decrypt multiple blocks in parallel with the same last round key.
pub inline fn decryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block {
comptime var i = 0;
var out: [count]Block = undefined;
inline while (i < count) : (i += 1) {
out[i] = blocks[i].decryptLast(round_key);
}
return out;
}
};
};
fn KeySchedule(comptime Aes: type) type {
std.debug.assert(Aes.rounds == 10 or Aes.rounds == 14);
const rounds = Aes.rounds;
return struct {
const Self = @This();
const zero = Vector(2, u64){ 0, 0 };
const mask1 = @Vector(16, u8){ 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12 };
const mask2 = @Vector(16, u8){ 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15 };
round_keys: [rounds + 1]Block,
fn drc128(comptime rc: u8, t: BlockVec) BlockVec {
var v1: BlockVec = undefined;
var v2: BlockVec = undefined;
var v3: BlockVec = undefined;
var v4: BlockVec = undefined;
return asm (
\\ movi %[v2].4s, %[rc]
\\ tbl %[v4].16b, {%[t].16b}, %[mask].16b
\\ ext %[r].16b, %[zero].16b, %[t].16b, #12
\\ aese %[v4].16b, %[zero].16b
\\ eor %[v2].16b, %[r].16b, %[v2].16b
\\ ext %[r].16b, %[zero].16b, %[r].16b, #12
\\ eor %[v1].16b, %[v2].16b, %[t].16b
\\ ext %[v3].16b, %[zero].16b, %[r].16b, #12
\\ eor %[v1].16b, %[v1].16b, %[r].16b
\\ eor %[r].16b, %[v1].16b, %[v3].16b
\\ eor %[r].16b, %[r].16b, %[v4].16b
: [r] "=&x" (-> BlockVec),
[v1] "=&x" (v1),
[v2] "=&x" (v2),
[v3] "=&x" (v3),
[v4] "=&x" (v4),
: [rc] "N" (rc),
[t] "x" (t),
[zero] "x" (zero),
[mask] "x" (mask1),
);
}
fn drc256(comptime second: bool, comptime rc: u8, t: BlockVec, tx: BlockVec) BlockVec {
var v1: BlockVec = undefined;
var v2: BlockVec = undefined;
var v3: BlockVec = undefined;
var v4: BlockVec = undefined;
return asm (
\\ movi %[v2].4s, %[rc]
\\ tbl %[v4].16b, {%[t].16b}, %[mask].16b
\\ ext %[r].16b, %[zero].16b, %[tx].16b, #12
\\ aese %[v4].16b, %[zero].16b
\\ eor %[v1].16b, %[tx].16b, %[r].16b
\\ ext %[r].16b, %[zero].16b, %[r].16b, #12
\\ eor %[v1].16b, %[v1].16b, %[r].16b
\\ ext %[v3].16b, %[zero].16b, %[r].16b, #12
\\ eor %[v1].16b, %[v1].16b, %[v2].16b
\\ eor %[v1].16b, %[v1].16b, %[v3].16b
\\ eor %[r].16b, %[v1].16b, %[v4].16b
: [r] "=&x" (-> BlockVec),
[v1] "=&x" (v1),
[v2] "=&x" (v2),
[v3] "=&x" (v3),
[v4] "=&x" (v4),
: [rc] "N" (if (second) @as(u8, 0) else rc),
[t] "x" (t),
[tx] "x" (tx),
[zero] "x" (zero),
[mask] "x" (if (second) mask2 else mask1),
);
}
fn expand128(t1: *Block) Self {
var round_keys: [11]Block = undefined;
const rcs = [_]u8{ 1, 2, 4, 8, 16, 32, 64, 128, 27, 54 };
inline for (rcs, 0..) |rc, round| {
round_keys[round] = t1.*;
t1.repr = drc128(rc, t1.repr);
}
round_keys[rcs.len] = t1.*;
return Self{ .round_keys = round_keys };
}
fn expand256(t1: *Block, t2: *Block) Self {
var round_keys: [15]Block = undefined;
const rcs = [_]u8{ 1, 2, 4, 8, 16, 32 };
round_keys[0] = t1.*;
inline for (rcs, 0..) |rc, round| {
round_keys[round * 2 + 1] = t2.*;
t1.repr = drc256(false, rc, t2.repr, t1.repr);
round_keys[round * 2 + 2] = t1.*;
t2.repr = drc256(true, rc, t1.repr, t2.repr);
}
round_keys[rcs.len * 2 + 1] = t2.*;
t1.repr = drc256(false, 64, t2.repr, t1.repr);
round_keys[rcs.len * 2 + 2] = t1.*;
return Self{ .round_keys = round_keys };
}
/// Invert the key schedule.
pub fn invert(key_schedule: Self) Self {
const round_keys = &key_schedule.round_keys;
var inv_round_keys: [rounds + 1]Block = undefined;
inv_round_keys[0] = round_keys[rounds];
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
inv_round_keys[i] = Block{
.repr = asm (
\\ aesimc %[inv_rk].16b, %[rk].16b
: [inv_rk] "=x" (-> BlockVec),
: [rk] "x" (round_keys[rounds - i].repr),
),
};
}
inv_round_keys[rounds] = round_keys[0];
return Self{ .round_keys = inv_round_keys };
}
};
}
/// A context to perform encryption using the standard AES key schedule.
pub fn AesEncryptCtx(comptime Aes: type) type {
std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256);
const rounds = Aes.rounds;
return struct {
const Self = @This();
pub const block = Aes.block;
pub const block_length = block.block_length;
key_schedule: KeySchedule(Aes),
/// Create a new encryption context with the given key.
pub fn init(key: [Aes.key_bits / 8]u8) Self {
var t1 = Block.fromBytes(key[0..16]);
const key_schedule = if (Aes.key_bits == 128) ks: {
break :ks KeySchedule(Aes).expand128(&t1);
} else ks: {
var t2 = Block.fromBytes(key[16..32]);
break :ks KeySchedule(Aes).expand256(&t1, &t2);
};
return Self{
.key_schedule = key_schedule,
};
}
/// Encrypt a single block.
pub fn encrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(src).xorBlocks(round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.encrypt(round_keys[i]);
}
t = t.encryptLast(round_keys[rounds]);
dst.* = t.toBytes();
}
/// Encrypt+XOR a single block.
pub fn xor(ctx: Self, dst: *[16]u8, src: *const [16]u8, counter: [16]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(&counter).xorBlocks(round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.encrypt(round_keys[i]);
}
t = t.encryptLast(round_keys[rounds]);
dst.* = t.xorBytes(src);
}
/// Encrypt multiple blocks, possibly leveraging parallelization.
pub fn encryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var ts: [count]Block = undefined;
comptime var j = 0;
inline while (j < count) : (j += 1) {
ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xorBlocks(round_keys[0]);
}
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
ts = Block.parallel.encryptWide(count, ts, round_keys[i]);
}
ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]);
j = 0;
inline while (j < count) : (j += 1) {
dst[16 * j .. 16 * j + 16].* = ts[j].toBytes();
}
}
/// Encrypt+XOR multiple blocks, possibly leveraging parallelization.
pub fn xorWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8, counters: [16 * count]u8) void {
const round_keys = ctx.key_schedule.round_keys;
var ts: [count]Block = undefined;
comptime var j = 0;
inline while (j < count) : (j += 1) {
ts[j] = Block.fromBytes(counters[j * 16 .. j * 16 + 16][0..16]).xorBlocks(round_keys[0]);
}
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
ts = Block.parallel.encryptWide(count, ts, round_keys[i]);
}
ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]);
j = 0;
inline while (j < count) : (j += 1) {
dst[16 * j .. 16 * j + 16].* = ts[j].xorBytes(src[16 * j .. 16 * j + 16]);
}
}
};
}
/// A context to perform decryption using the standard AES key schedule.
pub fn AesDecryptCtx(comptime Aes: type) type {
std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256);
const rounds = Aes.rounds;
return struct {
const Self = @This();
pub const block = Aes.block;
pub const block_length = block.block_length;
key_schedule: KeySchedule(Aes),
/// Create a decryption context from an existing encryption context.
pub fn initFromEnc(ctx: AesEncryptCtx(Aes)) Self {
return Self{
.key_schedule = ctx.key_schedule.invert(),
};
}
/// Create a new decryption context with the given key.
pub fn init(key: [Aes.key_bits / 8]u8) Self {
const enc_ctx = AesEncryptCtx(Aes).init(key);
return initFromEnc(enc_ctx);
}
/// Decrypt a single block.
pub fn decrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void {
const inv_round_keys = ctx.key_schedule.round_keys;
var t = Block.fromBytes(src).xorBlocks(inv_round_keys[0]);
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
t = t.decrypt(inv_round_keys[i]);
}
t = t.decryptLast(inv_round_keys[rounds]);
dst.* = t.toBytes();
}
/// Decrypt multiple blocks, possibly leveraging parallelization.
pub fn decryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void {
const inv_round_keys = ctx.key_schedule.round_keys;
var ts: [count]Block = undefined;
comptime var j = 0;
inline while (j < count) : (j += 1) {
ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xorBlocks(inv_round_keys[0]);
}
comptime var i = 1;
inline while (i < rounds) : (i += 1) {
ts = Block.parallel.decryptWide(count, ts, inv_round_keys[i]);
}
ts = Block.parallel.decryptLastWide(count, ts, inv_round_keys[i]);
j = 0;
inline while (j < count) : (j += 1) {
dst[16 * j .. 16 * j + 16].* = ts[j].toBytes();
}
}
};
}
/// AES-128 with the standard key schedule.
pub const Aes128 = struct {
pub const key_bits: usize = 128;
pub const rounds = ((key_bits - 64) / 32 + 8);
pub const block = Block;
/// Create a new context for encryption.
pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes128) {
return AesEncryptCtx(Aes128).init(key);
}
/// Create a new context for decryption.
pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes128) {
return AesDecryptCtx(Aes128).init(key);
}
};
/// AES-256 with the standard key schedule.
pub const Aes256 = struct {
pub const key_bits: usize = 256;
pub const rounds = ((key_bits - 64) / 32 + 8);
pub const block = Block;
/// Create a new context for encryption.
pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes256) {
return AesEncryptCtx(Aes256).init(key);
}
/// Create a new context for decryption.
pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes256) {
return AesDecryptCtx(Aes256).init(key);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.