code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const StringHashMap = std.StringHashMap; pub fn buildNamedCharacterReferenceTable(allocator: *std.mem.Allocator) StringHashMap(u21) { @setEvalBranchQuota(3000); const pairs = .{ .{ "Aacute;", 0x000C1 }, .{ "Aacute", 0x000C1 }, .{ "aacute;", 0x000E1 }, .{ "aacute", 0x000E1 }, .{ "Abreve;", 0x00102 }, .{ "abreve;", 0x00103 }, .{ "ac;", 0x0223E }, .{ "acd;", 0x0223F }, .{ "acE;", 0x0223E }, .{ "Acirc;", 0x000C2 }, .{ "Acirc", 0x000C2 }, .{ "acirc;", 0x000E2 }, .{ "acirc", 0x000E2 }, .{ "acute;", 0x000B4 }, .{ "acute", 0x000B4 }, .{ "Acy;", 0x00410 }, .{ "acy;", 0x00430 }, .{ "AElig;", 0x000C6 }, .{ "AElig", 0x000C6 }, .{ "aelig;", 0x000E6 }, .{ "aelig", 0x000E6 }, .{ "af;", 0x02061 }, .{ "Afr;", 0x1D504 }, .{ "afr;", 0x1D51E }, .{ "Agrave;", 0x000C0 }, .{ "Agrave", 0x000C0 }, .{ "agrave;", 0x000E0 }, .{ "agrave", 0x000E0 }, .{ "alefsym;", 0x02135 }, .{ "aleph;", 0x02135 }, .{ "Alpha;", 0x00391 }, .{ "alpha;", 0x003B1 }, .{ "Amacr;", 0x00100 }, .{ "amacr;", 0x00101 }, .{ "amalg;", 0x02A3F }, .{ "AMP;", 0x00026 }, .{ "AMP", 0x00026 }, .{ "amp;", 0x00026 }, .{ "amp", 0x00026 }, .{ "And;", 0x02A53 }, .{ "and;", 0x02227 }, .{ "andand;", 0x02A55 }, .{ "andd;", 0x02A5C }, .{ "andslope;", 0x02A58 }, .{ "andv;", 0x02A5A }, .{ "ang;", 0x02220 }, .{ "ange;", 0x029A4 }, .{ "angle;", 0x02220 }, .{ "angmsd;", 0x02221 }, .{ "angmsdaa;", 0x029A8 }, .{ "angmsdab;", 0x029A9 }, .{ "angmsdac;", 0x029AA }, .{ "angmsdad;", 0x029AB }, .{ "angmsdae;", 0x029AC }, .{ "angmsdaf;", 0x029AD }, .{ "angmsdag;", 0x029AE }, .{ "angmsdah;", 0x029AF }, .{ "angrt;", 0x0221F }, .{ "angrtvb;", 0x022BE }, .{ "angrtvbd;", 0x0299D }, .{ "angsph;", 0x02222 }, .{ "angst;", 0x000C5 }, .{ "angzarr;", 0x0237C }, .{ "Aogon;", 0x00104 }, .{ "aogon;", 0x00105 }, .{ "Aopf;", 0x1D538 }, .{ "aopf;", 0x1D552 }, .{ "ap;", 0x02248 }, .{ "apacir;", 0x02A6F }, .{ "apE;", 0x02A70 }, .{ "ape;", 0x0224A }, .{ "apid;", 0x0224B }, .{ "apos;", 0x00027 }, .{ "ApplyFunction;", 0x02061 }, .{ "approx;", 0x02248 }, .{ "approxeq;", 0x0224A }, .{ "Aring;", 0x000C5 }, .{ "Aring", 0x000C5 }, .{ "aring;", 0x000E5 }, .{ "aring", 0x000E5 }, .{ "Ascr;", 0x1D49C }, .{ "ascr;", 0x1D4B6 }, .{ "Assign;", 0x02254 }, .{ "ast;", 0x0002A }, .{ "asymp;", 0x02248 }, .{ "asympeq;", 0x0224D }, .{ "Atilde;", 0x000C3 }, .{ "Atilde", 0x000C3 }, .{ "atilde;", 0x000E3 }, .{ "atilde", 0x000E3 }, .{ "Auml;", 0x000C4 }, .{ "Auml", 0x000C4 }, .{ "auml;", 0x000E4 }, .{ "auml", 0x000E4 }, .{ "awconint;", 0x02233 }, .{ "awint;", 0x02A11 }, .{ "backcong;", 0x0224C }, .{ "backepsilon;", 0x003F6 }, .{ "backprime;", 0x02035 }, .{ "backsim;", 0x0223D }, .{ "backsimeq;", 0x022CD }, .{ "Backslash;", 0x02216 }, .{ "Barv;", 0x02AE7 }, .{ "barvee;", 0x022BD }, .{ "Barwed;", 0x02306 }, .{ "barwed;", 0x02305 }, .{ "barwedge;", 0x02305 }, .{ "bbrk;", 0x023B5 }, .{ "bbrktbrk;", 0x023B6 }, .{ "bcong;", 0x0224C }, .{ "Bcy;", 0x00411 }, .{ "bcy;", 0x00431 }, .{ "bdquo;", 0x0201E }, .{ "becaus;", 0x02235 }, .{ "Because;", 0x02235 }, .{ "because;", 0x02235 }, .{ "bemptyv;", 0x029B0 }, .{ "bepsi;", 0x003F6 }, .{ "bernou;", 0x0212C }, .{ "Bernoullis;", 0x0212C }, .{ "Beta;", 0x00392 }, .{ "beta;", 0x003B2 }, .{ "beth;", 0x02136 }, .{ "between;", 0x0226C }, .{ "Bfr;", 0x1D505 }, .{ "bfr;", 0x1D51F }, .{ "bigcap;", 0x022C2 }, .{ "bigcirc;", 0x025EF }, .{ "bigcup;", 0x022C3 }, .{ "bigodot;", 0x02A00 }, .{ "bigoplus;", 0x02A01 }, .{ "bigotimes;", 0x02A02 }, .{ "bigsqcup;", 0x02A06 }, .{ "bigstar;", 0x02605 }, .{ "bigtriangledown;", 0x025BD }, .{ "bigtriangleup;", 0x025B3 }, .{ "biguplus;", 0x02A04 }, .{ "bigvee;", 0x022C1 }, .{ "bigwedge;", 0x022C0 }, .{ "bkarow;", 0x0290D }, .{ "blacklozenge;", 0x029EB }, .{ "blacksquare;", 0x025AA }, .{ "blacktriangle;", 0x025B4 }, .{ "blacktriangledown;", 0x025BE }, .{ "blacktriangleleft;", 0x025C2 }, .{ "blacktriangleright;", 0x025B8 }, .{ "blank;", 0x02423 }, .{ "blk12;", 0x02592 }, .{ "blk14;", 0x02591 }, .{ "blk34;", 0x02593 }, .{ "block;", 0x02588 }, .{ "bne;", 0x0003D }, .{ "bnequiv;", 0x02261 }, .{ "bNot;", 0x02AED }, .{ "bnot;", 0x02310 }, .{ "Bopf;", 0x1D539 }, .{ "bopf;", 0x1D553 }, .{ "bot;", 0x022A5 }, .{ "bottom;", 0x022A5 }, .{ "bowtie;", 0x022C8 }, .{ "boxbox;", 0x029C9 }, .{ "boxDL;", 0x02557 }, .{ "boxDl;", 0x02556 }, .{ "boxdL;", 0x02555 }, .{ "boxdl;", 0x02510 }, .{ "boxDR;", 0x02554 }, .{ "boxDr;", 0x02553 }, .{ "boxdR;", 0x02552 }, .{ "boxdr;", 0x0250C }, .{ "boxH;", 0x02550 }, .{ "boxh;", 0x02500 }, .{ "boxHD;", 0x02566 }, .{ "boxHd;", 0x02564 }, .{ "boxhD;", 0x02565 }, .{ "boxhd;", 0x0252C }, .{ "boxHU;", 0x02569 }, .{ "boxHu;", 0x02567 }, .{ "boxhU;", 0x02568 }, .{ "boxhu;", 0x02534 }, .{ "boxminus;", 0x0229F }, .{ "boxplus;", 0x0229E }, .{ "boxtimes;", 0x022A0 }, .{ "boxUL;", 0x0255D }, .{ "boxUl;", 0x0255C }, .{ "boxuL;", 0x0255B }, .{ "boxul;", 0x02518 }, .{ "boxUR;", 0x0255A }, .{ "boxUr;", 0x02559 }, .{ "boxuR;", 0x02558 }, .{ "boxur;", 0x02514 }, .{ "boxV;", 0x02551 }, .{ "boxv;", 0x02502 }, .{ "boxVH;", 0x0256C }, .{ "boxVh;", 0x0256B }, .{ "boxvH;", 0x0256A }, .{ "boxvh;", 0x0253C }, .{ "boxVL;", 0x02563 }, .{ "boxVl;", 0x02562 }, .{ "boxvL;", 0x02561 }, .{ "boxvl;", 0x02524 }, .{ "boxVR;", 0x02560 }, .{ "boxVr;", 0x0255F }, .{ "boxvR;", 0x0255E }, .{ "boxvr;", 0x0251C }, .{ "bprime;", 0x02035 }, .{ "Breve;", 0x002D8 }, .{ "breve;", 0x002D8 }, .{ "brvbar;", 0x000A6 }, .{ "brvbar", 0x000A6 }, .{ "Bscr;", 0x0212C }, .{ "bscr;", 0x1D4B7 }, .{ "bsemi;", 0x0204F }, .{ "bsim;", 0x0223D }, .{ "bsime;", 0x022CD }, .{ "bsol;", 0x0005C }, .{ "bsolb;", 0x029C5 }, .{ "bsolhsub;", 0x027C8 }, .{ "bull;", 0x02022 }, .{ "bullet;", 0x02022 }, .{ "bump;", 0x0224E }, .{ "bumpE;", 0x02AAE }, .{ "bumpe;", 0x0224F }, .{ "Bumpeq;", 0x0224E }, .{ "bumpeq;", 0x0224F }, .{ "Cacute;", 0x00106 }, .{ "cacute;", 0x00107 }, .{ "Cap;", 0x022D2 }, .{ "cap;", 0x02229 }, .{ "capand;", 0x02A44 }, .{ "capbrcup;", 0x02A49 }, .{ "capcap;", 0x02A4B }, .{ "capcup;", 0x02A47 }, .{ "capdot;", 0x02A40 }, .{ "CapitalDifferentialD;", 0x02145 }, .{ "caps;", 0x02229 }, .{ "caret;", 0x02041 }, .{ "caron;", 0x002C7 }, .{ "Cayleys;", 0x0212D }, .{ "ccaps;", 0x02A4D }, .{ "Ccaron;", 0x0010C }, .{ "ccaron;", 0x0010D }, .{ "Ccedil;", 0x000C7 }, .{ "Ccedil", 0x000C7 }, .{ "ccedil;", 0x000E7 }, .{ "ccedil", 0x000E7 }, .{ "Ccirc;", 0x00108 }, .{ "ccirc;", 0x00109 }, .{ "Cconint;", 0x02230 }, .{ "ccups;", 0x02A4C }, .{ "ccupssm;", 0x02A50 }, .{ "Cdot;", 0x0010A }, .{ "cdot;", 0x0010B }, .{ "cedil;", 0x000B8 }, .{ "cedil", 0x000B8 }, .{ "Cedilla;", 0x000B8 }, .{ "cemptyv;", 0x029B2 }, .{ "cent;", 0x000A2 }, .{ "cent", 0x000A2 }, .{ "CenterDot;", 0x000B7 }, .{ "centerdot;", 0x000B7 }, .{ "Cfr;", 0x0212D }, .{ "cfr;", 0x1D520 }, .{ "CHcy;", 0x00427 }, .{ "chcy;", 0x00447 }, .{ "check;", 0x02713 }, .{ "checkmark;", 0x02713 }, .{ "Chi;", 0x003A7 }, .{ "chi;", 0x003C7 }, .{ "cir;", 0x025CB }, .{ "circ;", 0x002C6 }, .{ "circeq;", 0x02257 }, .{ "circlearrowleft;", 0x021BA }, .{ "circlearrowright;", 0x021BB }, .{ "circledast;", 0x0229B }, .{ "circledcirc;", 0x0229A }, .{ "circleddash;", 0x0229D }, .{ "CircleDot;", 0x02299 }, .{ "circledR;", 0x000AE }, .{ "circledS;", 0x024C8 }, .{ "CircleMinus;", 0x02296 }, .{ "CirclePlus;", 0x02295 }, .{ "CircleTimes;", 0x02297 }, .{ "cirE;", 0x029C3 }, .{ "cire;", 0x02257 }, .{ "cirfnint;", 0x02A10 }, .{ "cirmid;", 0x02AEF }, .{ "cirscir;", 0x029C2 }, .{ "ClockwiseContourIntegral;", 0x02232 }, .{ "CloseCurlyDoubleQuote;", 0x0201D }, .{ "CloseCurlyQuote;", 0x02019 }, .{ "clubs;", 0x02663 }, .{ "clubsuit;", 0x02663 }, .{ "Colon;", 0x02237 }, .{ "colon;", 0x0003A }, .{ "Colone;", 0x02A74 }, .{ "colone;", 0x02254 }, .{ "coloneq;", 0x02254 }, .{ "comma;", 0x0002C }, .{ "commat;", 0x00040 }, .{ "comp;", 0x02201 }, .{ "compfn;", 0x02218 }, .{ "complement;", 0x02201 }, .{ "complexes;", 0x02102 }, .{ "cong;", 0x02245 }, .{ "congdot;", 0x02A6D }, .{ "Congruent;", 0x02261 }, .{ "Conint;", 0x0222F }, .{ "conint;", 0x0222E }, .{ "ContourIntegral;", 0x0222E }, .{ "Copf;", 0x02102 }, .{ "copf;", 0x1D554 }, .{ "coprod;", 0x02210 }, .{ "Coproduct;", 0x02210 }, .{ "COPY;", 0x000A9 }, .{ "COPY", 0x000A9 }, .{ "copy;", 0x000A9 }, .{ "copy", 0x000A9 }, .{ "copysr;", 0x02117 }, .{ "CounterClockwiseContourIntegral;", 0x02233 }, .{ "crarr;", 0x021B5 }, .{ "Cross;", 0x02A2F }, .{ "cross;", 0x02717 }, .{ "Cscr;", 0x1D49E }, .{ "cscr;", 0x1D4B8 }, .{ "csub;", 0x02ACF }, .{ "csube;", 0x02AD1 }, .{ "csup;", 0x02AD0 }, .{ "csupe;", 0x02AD2 }, .{ "ctdot;", 0x022EF }, .{ "cudarrl;", 0x02938 }, .{ "cudarrr;", 0x02935 }, .{ "cuepr;", 0x022DE }, .{ "cuesc;", 0x022DF }, .{ "cularr;", 0x021B6 }, .{ "cularrp;", 0x0293D }, .{ "Cup;", 0x022D3 }, .{ "cup;", 0x0222A }, .{ "cupbrcap;", 0x02A48 }, .{ "CupCap;", 0x0224D }, .{ "cupcap;", 0x02A46 }, .{ "cupcup;", 0x02A4A }, .{ "cupdot;", 0x0228D }, .{ "cupor;", 0x02A45 }, .{ "cups;", 0x0222A }, .{ "curarr;", 0x021B7 }, .{ "curarrm;", 0x0293C }, .{ "curlyeqprec;", 0x022DE }, .{ "curlyeqsucc;", 0x022DF }, .{ "curlyvee;", 0x022CE }, .{ "curlywedge;", 0x022CF }, .{ "curren;", 0x000A4 }, .{ "curren", 0x000A4 }, .{ "curvearrowleft;", 0x021B6 }, .{ "curvearrowright;", 0x021B7 }, .{ "cuvee;", 0x022CE }, .{ "cuwed;", 0x022CF }, .{ "cwconint;", 0x02232 }, .{ "cwint;", 0x02231 }, .{ "cylcty;", 0x0232D }, .{ "Dagger;", 0x02021 }, .{ "dagger;", 0x02020 }, .{ "daleth;", 0x02138 }, .{ "Darr;", 0x021A1 }, .{ "dArr;", 0x021D3 }, .{ "darr;", 0x02193 }, .{ "dash;", 0x02010 }, .{ "Dashv;", 0x02AE4 }, .{ "dashv;", 0x022A3 }, .{ "dbkarow;", 0x0290F }, .{ "dblac;", 0x002DD }, .{ "Dcaron;", 0x0010E }, .{ "dcaron;", 0x0010F }, .{ "Dcy;", 0x00414 }, .{ "dcy;", 0x00434 }, .{ "DD;", 0x02145 }, .{ "dd;", 0x02146 }, .{ "ddagger;", 0x02021 }, .{ "ddarr;", 0x021CA }, .{ "DDotrahd;", 0x02911 }, .{ "ddotseq;", 0x02A77 }, .{ "deg;", 0x000B0 }, .{ "deg", 0x000B0 }, .{ "Del;", 0x02207 }, .{ "Delta;", 0x00394 }, .{ "delta;", 0x003B4 }, .{ "demptyv;", 0x029B1 }, .{ "dfisht;", 0x0297F }, .{ "Dfr;", 0x1D507 }, .{ "dfr;", 0x1D521 }, .{ "dHar;", 0x02965 }, .{ "dharl;", 0x021C3 }, .{ "dharr;", 0x021C2 }, .{ "DiacriticalAcute;", 0x000B4 }, .{ "DiacriticalDot;", 0x002D9 }, .{ "DiacriticalDoubleAcute;", 0x002DD }, .{ "DiacriticalGrave;", 0x00060 }, .{ "DiacriticalTilde;", 0x002DC }, .{ "diam;", 0x022C4 }, .{ "Diamond;", 0x022C4 }, .{ "diamond;", 0x022C4 }, .{ "diamondsuit;", 0x02666 }, .{ "diams;", 0x02666 }, .{ "die;", 0x000A8 }, .{ "DifferentialD;", 0x02146 }, .{ "digamma;", 0x003DD }, .{ "disin;", 0x022F2 }, .{ "div;", 0x000F7 }, .{ "divide;", 0x000F7 }, .{ "divide", 0x000F7 }, .{ "divideontimes;", 0x022C7 }, .{ "divonx;", 0x022C7 }, .{ "DJcy;", 0x00402 }, .{ "djcy;", 0x00452 }, .{ "dlcorn;", 0x0231E }, .{ "dlcrop;", 0x0230D }, .{ "dollar;", 0x00024 }, .{ "Dopf;", 0x1D53B }, .{ "dopf;", 0x1D555 }, .{ "Dot;", 0x000A8 }, .{ "dot;", 0x002D9 }, .{ "DotDot;", 0x020DC }, .{ "doteq;", 0x02250 }, .{ "doteqdot;", 0x02251 }, .{ "DotEqual;", 0x02250 }, .{ "dotminus;", 0x02238 }, .{ "dotplus;", 0x02214 }, .{ "dotsquare;", 0x022A1 }, .{ "doublebarwedge;", 0x02306 }, .{ "DoubleContourIntegral;", 0x0222F }, .{ "DoubleDot;", 0x000A8 }, .{ "DoubleDownArrow;", 0x021D3 }, .{ "DoubleLeftArrow;", 0x021D0 }, .{ "DoubleLeftRightArrow;", 0x021D4 }, .{ "DoubleLeftTee;", 0x02AE4 }, .{ "DoubleLongLeftArrow;", 0x027F8 }, .{ "DoubleLongLeftRightArrow;", 0x027FA }, .{ "DoubleLongRightArrow;", 0x027F9 }, .{ "DoubleRightArrow;", 0x021D2 }, .{ "DoubleRightTee;", 0x022A8 }, .{ "DoubleUpArrow;", 0x021D1 }, .{ "DoubleUpDownArrow;", 0x021D5 }, .{ "DoubleVerticalBar;", 0x02225 }, .{ "DownArrow;", 0x02193 }, .{ "Downarrow;", 0x021D3 }, .{ "downarrow;", 0x02193 }, .{ "DownArrowBar;", 0x02913 }, .{ "DownArrowUpArrow;", 0x021F5 }, .{ "DownBreve;", 0x00311 }, .{ "downdownarrows;", 0x021CA }, .{ "downharpoonleft;", 0x021C3 }, .{ "downharpoonright;", 0x021C2 }, .{ "DownLeftRightVector;", 0x02950 }, .{ "DownLeftTeeVector;", 0x0295E }, .{ "DownLeftVector;", 0x021BD }, .{ "DownLeftVectorBar;", 0x02956 }, .{ "DownRightTeeVector;", 0x0295F }, .{ "DownRightVector;", 0x021C1 }, .{ "DownRightVectorBar;", 0x02957 }, .{ "DownTee;", 0x022A4 }, .{ "DownTeeArrow;", 0x021A7 }, .{ "drbkarow;", 0x02910 }, .{ "drcorn;", 0x0231F }, .{ "drcrop;", 0x0230C }, .{ "Dscr;", 0x1D49F }, .{ "dscr;", 0x1D4B9 }, .{ "DScy;", 0x00405 }, .{ "dscy;", 0x00455 }, .{ "dsol;", 0x029F6 }, .{ "Dstrok;", 0x00110 }, .{ "dstrok;", 0x00111 }, .{ "dtdot;", 0x022F1 }, .{ "dtri;", 0x025BF }, .{ "dtrif;", 0x025BE }, .{ "duarr;", 0x021F5 }, .{ "duhar;", 0x0296F }, .{ "dwangle;", 0x029A6 }, .{ "DZcy;", 0x0040F }, .{ "dzcy;", 0x0045F }, .{ "dzigrarr;", 0x027FF }, .{ "Eacute;", 0x000C9 }, .{ "Eacute", 0x000C9 }, .{ "eacute;", 0x000E9 }, .{ "eacute", 0x000E9 }, .{ "easter;", 0x02A6E }, .{ "Ecaron;", 0x0011A }, .{ "ecaron;", 0x0011B }, .{ "ecir;", 0x02256 }, .{ "Ecirc;", 0x000CA }, .{ "Ecirc", 0x000CA }, .{ "ecirc;", 0x000EA }, .{ "ecirc", 0x000EA }, .{ "ecolon;", 0x02255 }, .{ "Ecy;", 0x0042D }, .{ "ecy;", 0x0044D }, .{ "eDDot;", 0x02A77 }, .{ "Edot;", 0x00116 }, .{ "eDot;", 0x02251 }, .{ "edot;", 0x00117 }, .{ "ee;", 0x02147 }, .{ "efDot;", 0x02252 }, .{ "Efr;", 0x1D508 }, .{ "efr;", 0x1D522 }, .{ "eg;", 0x02A9A }, .{ "Egrave;", 0x000C8 }, .{ "Egrave", 0x000C8 }, .{ "egrave;", 0x000E8 }, .{ "egrave", 0x000E8 }, .{ "egs;", 0x02A96 }, .{ "egsdot;", 0x02A98 }, .{ "el;", 0x02A99 }, .{ "Element;", 0x02208 }, .{ "elinters;", 0x023E7 }, .{ "ell;", 0x02113 }, .{ "els;", 0x02A95 }, .{ "elsdot;", 0x02A97 }, .{ "Emacr;", 0x00112 }, .{ "emacr;", 0x00113 }, .{ "empty;", 0x02205 }, .{ "emptyset;", 0x02205 }, .{ "EmptySmallSquare;", 0x025FB }, .{ "emptyv;", 0x02205 }, .{ "EmptyVerySmallSquare;", 0x025AB }, .{ "emsp;", 0x02003 }, .{ "emsp13;", 0x02004 }, .{ "emsp14;", 0x02005 }, .{ "ENG;", 0x0014A }, .{ "eng;", 0x0014B }, .{ "ensp;", 0x02002 }, .{ "Eogon;", 0x00118 }, .{ "eogon;", 0x00119 }, .{ "Eopf;", 0x1D53C }, .{ "eopf;", 0x1D556 }, .{ "epar;", 0x022D5 }, .{ "eparsl;", 0x029E3 }, .{ "eplus;", 0x02A71 }, .{ "epsi;", 0x003B5 }, .{ "Epsilon;", 0x00395 }, .{ "epsilon;", 0x003B5 }, .{ "epsiv;", 0x003F5 }, .{ "eqcirc;", 0x02256 }, .{ "eqcolon;", 0x02255 }, .{ "eqsim;", 0x02242 }, .{ "eqslantgtr;", 0x02A96 }, .{ "eqslantless;", 0x02A95 }, .{ "Equal;", 0x02A75 }, .{ "equals;", 0x0003D }, .{ "EqualTilde;", 0x02242 }, .{ "equest;", 0x0225F }, .{ "Equilibrium;", 0x021CC }, .{ "equiv;", 0x02261 }, .{ "equivDD;", 0x02A78 }, .{ "eqvparsl;", 0x029E5 }, .{ "erarr;", 0x02971 }, .{ "erDot;", 0x02253 }, .{ "Escr;", 0x02130 }, .{ "escr;", 0x0212F }, .{ "esdot;", 0x02250 }, .{ "Esim;", 0x02A73 }, .{ "esim;", 0x02242 }, .{ "Eta;", 0x00397 }, .{ "eta;", 0x003B7 }, .{ "ETH;", 0x000D0 }, .{ "ETH", 0x000D0 }, .{ "eth;", 0x000F0 }, .{ "eth", 0x000F0 }, .{ "Euml;", 0x000CB }, .{ "Euml", 0x000CB }, .{ "euml;", 0x000EB }, .{ "euml", 0x000EB }, .{ "euro;", 0x020AC }, .{ "excl;", 0x00021 }, .{ "exist;", 0x02203 }, .{ "Exists;", 0x02203 }, .{ "expectation;", 0x02130 }, .{ "ExponentialE;", 0x02147 }, .{ "exponentiale;", 0x02147 }, .{ "fallingdotseq;", 0x02252 }, .{ "Fcy;", 0x00424 }, .{ "fcy;", 0x00444 }, .{ "female;", 0x02640 }, .{ "ffilig;", 0x0FB03 }, .{ "fflig;", 0x0FB00 }, .{ "ffllig;", 0x0FB04 }, .{ "Ffr;", 0x1D509 }, .{ "ffr;", 0x1D523 }, .{ "filig;", 0x0FB01 }, .{ "FilledSmallSquare;", 0x025FC }, .{ "FilledVerySmallSquare;", 0x025AA }, .{ "fjlig;", 0x00066 }, .{ "flat;", 0x0266D }, .{ "fllig;", 0x0FB02 }, .{ "fltns;", 0x025B1 }, .{ "fnof;", 0x00192 }, .{ "Fopf;", 0x1D53D }, .{ "fopf;", 0x1D557 }, .{ "ForAll;", 0x02200 }, .{ "forall;", 0x02200 }, .{ "fork;", 0x022D4 }, .{ "forkv;", 0x02AD9 }, .{ "Fouriertrf;", 0x02131 }, .{ "fpartint;", 0x02A0D }, .{ "frac12;", 0x000BD }, .{ "frac12", 0x000BD }, .{ "frac13;", 0x02153 }, .{ "frac14;", 0x000BC }, .{ "frac14", 0x000BC }, .{ "frac15;", 0x02155 }, .{ "frac16;", 0x02159 }, .{ "frac18;", 0x0215B }, .{ "frac23;", 0x02154 }, .{ "frac25;", 0x02156 }, .{ "frac34;", 0x000BE }, .{ "frac34", 0x000BE }, .{ "frac35;", 0x02157 }, .{ "frac38;", 0x0215C }, .{ "frac45;", 0x02158 }, .{ "frac56;", 0x0215A }, .{ "frac58;", 0x0215D }, .{ "frac78;", 0x0215E }, .{ "frasl;", 0x02044 }, .{ "frown;", 0x02322 }, .{ "Fscr;", 0x02131 }, .{ "fscr;", 0x1D4BB }, .{ "gacute;", 0x001F5 }, .{ "Gamma;", 0x00393 }, .{ "gamma;", 0x003B3 }, .{ "Gammad;", 0x003DC }, .{ "gammad;", 0x003DD }, .{ "gap;", 0x02A86 }, .{ "Gbreve;", 0x0011E }, .{ "gbreve;", 0x0011F }, .{ "Gcedil;", 0x00122 }, .{ "Gcirc;", 0x0011C }, .{ "gcirc;", 0x0011D }, .{ "Gcy;", 0x00413 }, .{ "gcy;", 0x00433 }, .{ "Gdot;", 0x00120 }, .{ "gdot;", 0x00121 }, .{ "gE;", 0x02267 }, .{ "ge;", 0x02265 }, .{ "gEl;", 0x02A8C }, .{ "gel;", 0x022DB }, .{ "geq;", 0x02265 }, .{ "geqq;", 0x02267 }, .{ "geqslant;", 0x02A7E }, .{ "ges;", 0x02A7E }, .{ "gescc;", 0x02AA9 }, .{ "gesdot;", 0x02A80 }, .{ "gesdoto;", 0x02A82 }, .{ "gesdotol;", 0x02A84 }, .{ "gesl;", 0x022DB }, .{ "gesles;", 0x02A94 }, .{ "Gfr;", 0x1D50A }, .{ "gfr;", 0x1D524 }, .{ "Gg;", 0x022D9 }, .{ "gg;", 0x0226B }, .{ "ggg;", 0x022D9 }, .{ "gimel;", 0x02137 }, .{ "GJcy;", 0x00403 }, .{ "gjcy;", 0x00453 }, .{ "gl;", 0x02277 }, .{ "gla;", 0x02AA5 }, .{ "glE;", 0x02A92 }, .{ "glj;", 0x02AA4 }, .{ "gnap;", 0x02A8A }, .{ "gnapprox;", 0x02A8A }, .{ "gnE;", 0x02269 }, .{ "gne;", 0x02A88 }, .{ "gneq;", 0x02A88 }, .{ "gneqq;", 0x02269 }, .{ "gnsim;", 0x022E7 }, .{ "Gopf;", 0x1D53E }, .{ "gopf;", 0x1D558 }, .{ "grave;", 0x00060 }, .{ "GreaterEqual;", 0x02265 }, .{ "GreaterEqualLess;", 0x022DB }, .{ "GreaterFullEqual;", 0x02267 }, .{ "GreaterGreater;", 0x02AA2 }, .{ "GreaterLess;", 0x02277 }, .{ "GreaterSlantEqual;", 0x02A7E }, .{ "GreaterTilde;", 0x02273 }, .{ "Gscr;", 0x1D4A2 }, .{ "gscr;", 0x0210A }, .{ "gsim;", 0x02273 }, .{ "gsime;", 0x02A8E }, .{ "gsiml;", 0x02A90 }, .{ "GT;", 0x0003E }, .{ "GT", 0x0003E }, .{ "Gt;", 0x0226B }, .{ "gt;", 0x0003E }, .{ "gt", 0x0003E }, .{ "gtcc;", 0x02AA7 }, .{ "gtcir;", 0x02A7A }, .{ "gtdot;", 0x022D7 }, .{ "gtlPar;", 0x02995 }, .{ "gtquest;", 0x02A7C }, .{ "gtrapprox;", 0x02A86 }, .{ "gtrarr;", 0x02978 }, .{ "gtrdot;", 0x022D7 }, .{ "gtreqless;", 0x022DB }, .{ "gtreqqless;", 0x02A8C }, .{ "gtrless;", 0x02277 }, .{ "gtrsim;", 0x02273 }, .{ "gvertneqq;", 0x02269 }, .{ "gvnE;", 0x02269 }, .{ "Hacek;", 0x002C7 }, .{ "hairsp;", 0x0200A }, .{ "half;", 0x000BD }, .{ "hamilt;", 0x0210B }, .{ "HARDcy;", 0x0042A }, .{ "hardcy;", 0x0044A }, .{ "hArr;", 0x021D4 }, .{ "harr;", 0x02194 }, .{ "harrcir;", 0x02948 }, .{ "harrw;", 0x021AD }, .{ "Hat;", 0x0005E }, .{ "hbar;", 0x0210F }, .{ "Hcirc;", 0x00124 }, .{ "hcirc;", 0x00125 }, .{ "hearts;", 0x02665 }, .{ "heartsuit;", 0x02665 }, .{ "hellip;", 0x02026 }, .{ "hercon;", 0x022B9 }, .{ "Hfr;", 0x0210C }, .{ "hfr;", 0x1D525 }, .{ "HilbertSpace;", 0x0210B }, .{ "hksearow;", 0x02925 }, .{ "hkswarow;", 0x02926 }, .{ "hoarr;", 0x021FF }, .{ "homtht;", 0x0223B }, .{ "hookleftarrow;", 0x021A9 }, .{ "hookrightarrow;", 0x021AA }, .{ "Hopf;", 0x0210D }, .{ "hopf;", 0x1D559 }, .{ "horbar;", 0x02015 }, .{ "HorizontalLine;", 0x02500 }, .{ "Hscr;", 0x0210B }, .{ "hscr;", 0x1D4BD }, .{ "hslash;", 0x0210F }, .{ "Hstrok;", 0x00126 }, .{ "hstrok;", 0x00127 }, .{ "HumpDownHump;", 0x0224E }, .{ "HumpEqual;", 0x0224F }, .{ "hybull;", 0x02043 }, .{ "hyphen;", 0x02010 }, .{ "Iacute;", 0x000CD }, .{ "Iacute", 0x000CD }, .{ "iacute;", 0x000ED }, .{ "iacute", 0x000ED }, .{ "ic;", 0x02063 }, .{ "Icirc;", 0x000CE }, .{ "Icirc", 0x000CE }, .{ "icirc;", 0x000EE }, .{ "icirc", 0x000EE }, .{ "Icy;", 0x00418 }, .{ "icy;", 0x00438 }, .{ "Idot;", 0x00130 }, .{ "IEcy;", 0x00415 }, .{ "iecy;", 0x00435 }, .{ "iexcl;", 0x000A1 }, .{ "iexcl", 0x000A1 }, .{ "iff;", 0x021D4 }, .{ "Ifr;", 0x02111 }, .{ "ifr;", 0x1D526 }, .{ "Igrave;", 0x000CC }, .{ "Igrave", 0x000CC }, .{ "igrave;", 0x000EC }, .{ "igrave", 0x000EC }, .{ "ii;", 0x02148 }, .{ "iiiint;", 0x02A0C }, .{ "iiint;", 0x0222D }, .{ "iinfin;", 0x029DC }, .{ "iiota;", 0x02129 }, .{ "IJlig;", 0x00132 }, .{ "ijlig;", 0x00133 }, .{ "Im;", 0x02111 }, .{ "Imacr;", 0x0012A }, .{ "imacr;", 0x0012B }, .{ "image;", 0x02111 }, .{ "ImaginaryI;", 0x02148 }, .{ "imagline;", 0x02110 }, .{ "imagpart;", 0x02111 }, .{ "imath;", 0x00131 }, .{ "imof;", 0x022B7 }, .{ "imped;", 0x001B5 }, .{ "Implies;", 0x021D2 }, .{ "in;", 0x02208 }, .{ "incare;", 0x02105 }, .{ "infin;", 0x0221E }, .{ "infintie;", 0x029DD }, .{ "inodot;", 0x00131 }, .{ "Int;", 0x0222C }, .{ "int;", 0x0222B }, .{ "intcal;", 0x022BA }, .{ "integers;", 0x02124 }, .{ "Integral;", 0x0222B }, .{ "intercal;", 0x022BA }, .{ "Intersection;", 0x022C2 }, .{ "intlarhk;", 0x02A17 }, .{ "intprod;", 0x02A3C }, .{ "InvisibleComma;", 0x02063 }, .{ "InvisibleTimes;", 0x02062 }, .{ "IOcy;", 0x00401 }, .{ "iocy;", 0x00451 }, .{ "Iogon;", 0x0012E }, .{ "iogon;", 0x0012F }, .{ "Iopf;", 0x1D540 }, .{ "iopf;", 0x1D55A }, .{ "Iota;", 0x00399 }, .{ "iota;", 0x003B9 }, .{ "iprod;", 0x02A3C }, .{ "iquest;", 0x000BF }, .{ "iquest", 0x000BF }, .{ "Iscr;", 0x02110 }, .{ "iscr;", 0x1D4BE }, .{ "isin;", 0x02208 }, .{ "isindot;", 0x022F5 }, .{ "isinE;", 0x022F9 }, .{ "isins;", 0x022F4 }, .{ "isinsv;", 0x022F3 }, .{ "isinv;", 0x02208 }, .{ "it;", 0x02062 }, .{ "Itilde;", 0x00128 }, .{ "itilde;", 0x00129 }, .{ "Iukcy;", 0x00406 }, .{ "iukcy;", 0x00456 }, .{ "Iuml;", 0x000CF }, .{ "Iuml", 0x000CF }, .{ "iuml;", 0x000EF }, .{ "iuml", 0x000EF }, .{ "Jcirc;", 0x00134 }, .{ "jcirc;", 0x00135 }, .{ "Jcy;", 0x00419 }, .{ "jcy;", 0x00439 }, .{ "Jfr;", 0x1D50D }, .{ "jfr;", 0x1D527 }, .{ "jmath;", 0x00237 }, .{ "Jopf;", 0x1D541 }, .{ "jopf;", 0x1D55B }, .{ "Jscr;", 0x1D4A5 }, .{ "jscr;", 0x1D4BF }, .{ "Jsercy;", 0x00408 }, .{ "jsercy;", 0x00458 }, .{ "Jukcy;", 0x00404 }, .{ "jukcy;", 0x00454 }, .{ "Kappa;", 0x0039A }, .{ "kappa;", 0x003BA }, .{ "kappav;", 0x003F0 }, .{ "Kcedil;", 0x00136 }, .{ "kcedil;", 0x00137 }, .{ "Kcy;", 0x0041A }, .{ "kcy;", 0x0043A }, .{ "Kfr;", 0x1D50E }, .{ "kfr;", 0x1D528 }, .{ "kgreen;", 0x00138 }, .{ "KHcy;", 0x00425 }, .{ "khcy;", 0x00445 }, .{ "KJcy;", 0x0040C }, .{ "kjcy;", 0x0045C }, .{ "Kopf;", 0x1D542 }, .{ "kopf;", 0x1D55C }, .{ "Kscr;", 0x1D4A6 }, .{ "kscr;", 0x1D4C0 }, .{ "lAarr;", 0x021DA }, .{ "Lacute;", 0x00139 }, .{ "lacute;", 0x0013A }, .{ "laemptyv;", 0x029B4 }, .{ "lagran;", 0x02112 }, .{ "Lambda;", 0x0039B }, .{ "lambda;", 0x003BB }, .{ "Lang;", 0x027EA }, .{ "lang;", 0x027E8 }, .{ "langd;", 0x02991 }, .{ "langle;", 0x027E8 }, .{ "lap;", 0x02A85 }, .{ "Laplacetrf;", 0x02112 }, .{ "laquo;", 0x000AB }, .{ "laquo", 0x000AB }, .{ "Larr;", 0x0219E }, .{ "lArr;", 0x021D0 }, .{ "larr;", 0x02190 }, .{ "larrb;", 0x021E4 }, .{ "larrbfs;", 0x0291F }, .{ "larrfs;", 0x0291D }, .{ "larrhk;", 0x021A9 }, .{ "larrlp;", 0x021AB }, .{ "larrpl;", 0x02939 }, .{ "larrsim;", 0x02973 }, .{ "larrtl;", 0x021A2 }, .{ "lat;", 0x02AAB }, .{ "lAtail;", 0x0291B }, .{ "latail;", 0x02919 }, .{ "late;", 0x02AAD }, .{ "lates;", 0x02AAD }, .{ "lBarr;", 0x0290E }, .{ "lbarr;", 0x0290C }, .{ "lbbrk;", 0x02772 }, .{ "lbrace;", 0x0007B }, .{ "lbrack;", 0x0005B }, .{ "lbrke;", 0x0298B }, .{ "lbrksld;", 0x0298F }, .{ "lbrkslu;", 0x0298D }, .{ "Lcaron;", 0x0013D }, .{ "lcaron;", 0x0013E }, .{ "Lcedil;", 0x0013B }, .{ "lcedil;", 0x0013C }, .{ "lceil;", 0x02308 }, .{ "lcub;", 0x0007B }, .{ "Lcy;", 0x0041B }, .{ "lcy;", 0x0043B }, .{ "ldca;", 0x02936 }, .{ "ldquo;", 0x0201C }, .{ "ldquor;", 0x0201E }, .{ "ldrdhar;", 0x02967 }, .{ "ldrushar;", 0x0294B }, .{ "ldsh;", 0x021B2 }, .{ "lE;", 0x02266 }, .{ "le;", 0x02264 }, .{ "LeftAngleBracket;", 0x027E8 }, .{ "LeftArrow;", 0x02190 }, .{ "Leftarrow;", 0x021D0 }, .{ "leftarrow;", 0x02190 }, .{ "LeftArrowBar;", 0x021E4 }, .{ "LeftArrowRightArrow;", 0x021C6 }, .{ "leftarrowtail;", 0x021A2 }, .{ "LeftCeiling;", 0x02308 }, .{ "LeftDoubleBracket;", 0x027E6 }, .{ "LeftDownTeeVector;", 0x02961 }, .{ "LeftDownVector;", 0x021C3 }, .{ "LeftDownVectorBar;", 0x02959 }, .{ "LeftFloor;", 0x0230A }, .{ "leftharpoondown;", 0x021BD }, .{ "leftharpoonup;", 0x021BC }, .{ "leftleftarrows;", 0x021C7 }, .{ "LeftRightArrow;", 0x02194 }, .{ "Leftrightarrow;", 0x021D4 }, .{ "leftrightarrow;", 0x02194 }, .{ "leftrightarrows;", 0x021C6 }, .{ "leftrightharpoons;", 0x021CB }, .{ "leftrightsquigarrow;", 0x021AD }, .{ "LeftRightVector;", 0x0294E }, .{ "LeftTee;", 0x022A3 }, .{ "LeftTeeArrow;", 0x021A4 }, .{ "LeftTeeVector;", 0x0295A }, .{ "leftthreetimes;", 0x022CB }, .{ "LeftTriangle;", 0x022B2 }, .{ "LeftTriangleBar;", 0x029CF }, .{ "LeftTriangleEqual;", 0x022B4 }, .{ "LeftUpDownVector;", 0x02951 }, .{ "LeftUpTeeVector;", 0x02960 }, .{ "LeftUpVector;", 0x021BF }, .{ "LeftUpVectorBar;", 0x02958 }, .{ "LeftVector;", 0x021BC }, .{ "LeftVectorBar;", 0x02952 }, .{ "lEg;", 0x02A8B }, .{ "leg;", 0x022DA }, .{ "leq;", 0x02264 }, .{ "leqq;", 0x02266 }, .{ "leqslant;", 0x02A7D }, .{ "les;", 0x02A7D }, .{ "lescc;", 0x02AA8 }, .{ "lesdot;", 0x02A7F }, .{ "lesdoto;", 0x02A81 }, .{ "lesdotor;", 0x02A83 }, .{ "lesg;", 0x022DA }, .{ "lesges;", 0x02A93 }, .{ "lessapprox;", 0x02A85 }, .{ "lessdot;", 0x022D6 }, .{ "lesseqgtr;", 0x022DA }, .{ "lesseqqgtr;", 0x02A8B }, .{ "LessEqualGreater;", 0x022DA }, .{ "LessFullEqual;", 0x02266 }, .{ "LessGreater;", 0x02276 }, .{ "lessgtr;", 0x02276 }, .{ "LessLess;", 0x02AA1 }, .{ "lesssim;", 0x02272 }, .{ "LessSlantEqual;", 0x02A7D }, .{ "LessTilde;", 0x02272 }, .{ "lfisht;", 0x0297C }, .{ "lfloor;", 0x0230A }, .{ "Lfr;", 0x1D50F }, .{ "lfr;", 0x1D529 }, .{ "lg;", 0x02276 }, .{ "lgE;", 0x02A91 }, .{ "lHar;", 0x02962 }, .{ "lhard;", 0x021BD }, .{ "lharu;", 0x021BC }, .{ "lharul;", 0x0296A }, .{ "lhblk;", 0x02584 }, .{ "LJcy;", 0x00409 }, .{ "ljcy;", 0x00459 }, .{ "Ll;", 0x022D8 }, .{ "ll;", 0x0226A }, .{ "llarr;", 0x021C7 }, .{ "llcorner;", 0x0231E }, .{ "Lleftarrow;", 0x021DA }, .{ "llhard;", 0x0296B }, .{ "lltri;", 0x025FA }, .{ "Lmidot;", 0x0013F }, .{ "lmidot;", 0x00140 }, .{ "lmoust;", 0x023B0 }, .{ "lmoustache;", 0x023B0 }, .{ "lnap;", 0x02A89 }, .{ "lnapprox;", 0x02A89 }, .{ "lnE;", 0x02268 }, .{ "lne;", 0x02A87 }, .{ "lneq;", 0x02A87 }, .{ "lneqq;", 0x02268 }, .{ "lnsim;", 0x022E6 }, .{ "loang;", 0x027EC }, .{ "loarr;", 0x021FD }, .{ "lobrk;", 0x027E6 }, .{ "LongLeftArrow;", 0x027F5 }, .{ "Longleftarrow;", 0x027F8 }, .{ "longleftarrow;", 0x027F5 }, .{ "LongLeftRightArrow;", 0x027F7 }, .{ "Longleftrightarrow;", 0x027FA }, .{ "longleftrightarrow;", 0x027F7 }, .{ "longmapsto;", 0x027FC }, .{ "LongRightArrow;", 0x027F6 }, .{ "Longrightarrow;", 0x027F9 }, .{ "longrightarrow;", 0x027F6 }, .{ "looparrowleft;", 0x021AB }, .{ "looparrowright;", 0x021AC }, .{ "lopar;", 0x02985 }, .{ "Lopf;", 0x1D543 }, .{ "lopf;", 0x1D55D }, .{ "loplus;", 0x02A2D }, .{ "lotimes;", 0x02A34 }, .{ "lowast;", 0x02217 }, .{ "lowbar;", 0x0005F }, .{ "LowerLeftArrow;", 0x02199 }, .{ "LowerRightArrow;", 0x02198 }, .{ "loz;", 0x025CA }, .{ "lozenge;", 0x025CA }, .{ "lozf;", 0x029EB }, .{ "lpar;", 0x00028 }, .{ "lparlt;", 0x02993 }, .{ "lrarr;", 0x021C6 }, .{ "lrcorner;", 0x0231F }, .{ "lrhar;", 0x021CB }, .{ "lrhard;", 0x0296D }, .{ "lrm;", 0x0200E }, .{ "lrtri;", 0x022BF }, .{ "lsaquo;", 0x02039 }, .{ "Lscr;", 0x02112 }, .{ "lscr;", 0x1D4C1 }, .{ "Lsh;", 0x021B0 }, .{ "lsh;", 0x021B0 }, .{ "lsim;", 0x02272 }, .{ "lsime;", 0x02A8D }, .{ "lsimg;", 0x02A8F }, .{ "lsqb;", 0x0005B }, .{ "lsquo;", 0x02018 }, .{ "lsquor;", 0x0201A }, .{ "Lstrok;", 0x00141 }, .{ "lstrok;", 0x00142 }, .{ "LT;", 0x0003C }, .{ "LT", 0x0003C }, .{ "Lt;", 0x0226A }, .{ "lt;", 0x0003C }, .{ "lt", 0x0003C }, .{ "ltcc;", 0x02AA6 }, .{ "ltcir;", 0x02A79 }, .{ "ltdot;", 0x022D6 }, .{ "lthree;", 0x022CB }, .{ "ltimes;", 0x022C9 }, .{ "ltlarr;", 0x02976 }, .{ "ltquest;", 0x02A7B }, .{ "ltri;", 0x025C3 }, .{ "ltrie;", 0x022B4 }, .{ "ltrif;", 0x025C2 }, .{ "ltrPar;", 0x02996 }, .{ "lurdshar;", 0x0294A }, .{ "luruhar;", 0x02966 }, .{ "lvertneqq;", 0x02268 }, .{ "lvnE;", 0x02268 }, .{ "macr;", 0x000AF }, .{ "macr", 0x000AF }, .{ "male;", 0x02642 }, .{ "malt;", 0x02720 }, .{ "maltese;", 0x02720 }, .{ "Map;", 0x02905 }, .{ "map;", 0x021A6 }, .{ "mapsto;", 0x021A6 }, .{ "mapstodown;", 0x021A7 }, .{ "mapstoleft;", 0x021A4 }, .{ "mapstoup;", 0x021A5 }, .{ "marker;", 0x025AE }, .{ "mcomma;", 0x02A29 }, .{ "Mcy;", 0x0041C }, .{ "mcy;", 0x0043C }, .{ "mdash;", 0x02014 }, .{ "mDDot;", 0x0223A }, .{ "measuredangle;", 0x02221 }, .{ "MediumSpace;", 0x0205F }, .{ "Mellintrf;", 0x02133 }, .{ "Mfr;", 0x1D510 }, .{ "mfr;", 0x1D52A }, .{ "mho;", 0x02127 }, .{ "micro;", 0x000B5 }, .{ "micro", 0x000B5 }, .{ "mid;", 0x02223 }, .{ "midast;", 0x0002A }, .{ "midcir;", 0x02AF0 }, .{ "middot;", 0x000B7 }, .{ "middot", 0x000B7 }, .{ "minus;", 0x02212 }, .{ "minusb;", 0x0229F }, .{ "minusd;", 0x02238 }, .{ "minusdu;", 0x02A2A }, .{ "MinusPlus;", 0x02213 }, .{ "mlcp;", 0x02ADB }, .{ "mldr;", 0x02026 }, .{ "mnplus;", 0x02213 }, .{ "models;", 0x022A7 }, .{ "Mopf;", 0x1D544 }, .{ "mopf;", 0x1D55E }, .{ "mp;", 0x02213 }, .{ "Mscr;", 0x02133 }, .{ "mscr;", 0x1D4C2 }, .{ "mstpos;", 0x0223E }, .{ "Mu;", 0x0039C }, .{ "mu;", 0x003BC }, .{ "multimap;", 0x022B8 }, .{ "mumap;", 0x022B8 }, .{ "nabla;", 0x02207 }, .{ "Nacute;", 0x00143 }, .{ "nacute;", 0x00144 }, .{ "nang;", 0x02220 }, .{ "nap;", 0x02249 }, .{ "napE;", 0x02A70 }, .{ "napid;", 0x0224B }, .{ "napos;", 0x00149 }, .{ "napprox;", 0x02249 }, .{ "natur;", 0x0266E }, .{ "natural;", 0x0266E }, .{ "naturals;", 0x02115 }, .{ "nbsp;", 0x000A0 }, .{ "nbsp", 0x000A0 }, .{ "nbump;", 0x0224E }, .{ "nbumpe;", 0x0224F }, .{ "ncap;", 0x02A43 }, .{ "Ncaron;", 0x00147 }, .{ "ncaron;", 0x00148 }, .{ "Ncedil;", 0x00145 }, .{ "ncedil;", 0x00146 }, .{ "ncong;", 0x02247 }, .{ "ncongdot;", 0x02A6D }, .{ "ncup;", 0x02A42 }, .{ "Ncy;", 0x0041D }, .{ "ncy;", 0x0043D }, .{ "ndash;", 0x02013 }, .{ "ne;", 0x02260 }, .{ "nearhk;", 0x02924 }, .{ "neArr;", 0x021D7 }, .{ "nearr;", 0x02197 }, .{ "nearrow;", 0x02197 }, .{ "nedot;", 0x02250 }, .{ "NegativeMediumSpace;", 0x0200B }, .{ "NegativeThickSpace;", 0x0200B }, .{ "NegativeThinSpace;", 0x0200B }, .{ "NegativeVeryThinSpace;", 0x0200B }, .{ "nequiv;", 0x02262 }, .{ "nesear;", 0x02928 }, .{ "nesim;", 0x02242 }, .{ "NestedGreaterGreater;", 0x0226B }, .{ "NestedLessLess;", 0x0226A }, .{ "NewLine;", 0x0000A }, .{ "nexist;", 0x02204 }, .{ "nexists;", 0x02204 }, .{ "Nfr;", 0x1D511 }, .{ "nfr;", 0x1D52B }, .{ "ngE;", 0x02267 }, .{ "nge;", 0x02271 }, .{ "ngeq;", 0x02271 }, .{ "ngeqq;", 0x02267 }, .{ "ngeqslant;", 0x02A7E }, .{ "nges;", 0x02A7E }, .{ "nGg;", 0x022D9 }, .{ "ngsim;", 0x02275 }, .{ "nGt;", 0x0226B }, .{ "ngt;", 0x0226F }, .{ "ngtr;", 0x0226F }, .{ "nGtv;", 0x0226B }, .{ "nhArr;", 0x021CE }, .{ "nharr;", 0x021AE }, .{ "nhpar;", 0x02AF2 }, .{ "ni;", 0x0220B }, .{ "nis;", 0x022FC }, .{ "nisd;", 0x022FA }, .{ "niv;", 0x0220B }, .{ "NJcy;", 0x0040A }, .{ "njcy;", 0x0045A }, .{ "nlArr;", 0x021CD }, .{ "nlarr;", 0x0219A }, .{ "nldr;", 0x02025 }, .{ "nlE;", 0x02266 }, .{ "nle;", 0x02270 }, .{ "nLeftarrow;", 0x021CD }, .{ "nleftarrow;", 0x0219A }, .{ "nLeftrightarrow;", 0x021CE }, .{ "nleftrightarrow;", 0x021AE }, .{ "nleq;", 0x02270 }, .{ "nleqq;", 0x02266 }, .{ "nleqslant;", 0x02A7D }, .{ "nles;", 0x02A7D }, .{ "nless;", 0x0226E }, .{ "nLl;", 0x022D8 }, .{ "nlsim;", 0x02274 }, .{ "nLt;", 0x0226A }, .{ "nlt;", 0x0226E }, .{ "nltri;", 0x022EA }, .{ "nltrie;", 0x022EC }, .{ "nLtv;", 0x0226A }, .{ "nmid;", 0x02224 }, .{ "NoBreak;", 0x02060 }, .{ "NonBreakingSpace;", 0x000A0 }, .{ "Nopf;", 0x02115 }, .{ "nopf;", 0x1D55F }, .{ "Not;", 0x02AEC }, .{ "not;", 0x000AC }, .{ "not", 0x000AC }, .{ "NotCongruent;", 0x02262 }, .{ "NotCupCap;", 0x0226D }, .{ "NotDoubleVerticalBar;", 0x02226 }, .{ "NotElement;", 0x02209 }, .{ "NotEqual;", 0x02260 }, .{ "NotEqualTilde;", 0x02242 }, .{ "NotExists;", 0x02204 }, .{ "NotGreater;", 0x0226F }, .{ "NotGreaterEqual;", 0x02271 }, .{ "NotGreaterFullEqual;", 0x02267 }, .{ "NotGreaterGreater;", 0x0226B }, .{ "NotGreaterLess;", 0x02279 }, .{ "NotGreaterSlantEqual;", 0x02A7E }, .{ "NotGreaterTilde;", 0x02275 }, .{ "NotHumpDownHump;", 0x0224E }, .{ "NotHumpEqual;", 0x0224F }, .{ "notin;", 0x02209 }, .{ "notindot;", 0x022F5 }, .{ "notinE;", 0x022F9 }, .{ "notinva;", 0x02209 }, .{ "notinvb;", 0x022F7 }, .{ "notinvc;", 0x022F6 }, .{ "NotLeftTriangle;", 0x022EA }, .{ "NotLeftTriangleBar;", 0x029CF }, .{ "NotLeftTriangleEqual;", 0x022EC }, .{ "NotLess;", 0x0226E }, .{ "NotLessEqual;", 0x02270 }, .{ "NotLessGreater;", 0x02278 }, .{ "NotLessLess;", 0x0226A }, .{ "NotLessSlantEqual;", 0x02A7D }, .{ "NotLessTilde;", 0x02274 }, .{ "NotNestedGreaterGreater;", 0x02AA2 }, .{ "NotNestedLessLess;", 0x02AA1 }, .{ "notni;", 0x0220C }, .{ "notniva;", 0x0220C }, .{ "notnivb;", 0x022FE }, .{ "notnivc;", 0x022FD }, .{ "NotPrecedes;", 0x02280 }, .{ "NotPrecedesEqual;", 0x02AAF }, .{ "NotPrecedesSlantEqual;", 0x022E0 }, .{ "NotReverseElement;", 0x0220C }, .{ "NotRightTriangle;", 0x022EB }, .{ "NotRightTriangleBar;", 0x029D0 }, .{ "NotRightTriangleEqual;", 0x022ED }, .{ "NotSquareSubset;", 0x0228F }, .{ "NotSquareSubsetEqual;", 0x022E2 }, .{ "NotSquareSuperset;", 0x02290 }, .{ "NotSquareSupersetEqual;", 0x022E3 }, .{ "NotSubset;", 0x02282 }, .{ "NotSubsetEqual;", 0x02288 }, .{ "NotSucceeds;", 0x02281 }, .{ "NotSucceedsEqual;", 0x02AB0 }, .{ "NotSucceedsSlantEqual;", 0x022E1 }, .{ "NotSucceedsTilde;", 0x0227F }, .{ "NotSuperset;", 0x02283 }, .{ "NotSupersetEqual;", 0x02289 }, .{ "NotTilde;", 0x02241 }, .{ "NotTildeEqual;", 0x02244 }, .{ "NotTildeFullEqual;", 0x02247 }, .{ "NotTildeTilde;", 0x02249 }, .{ "NotVerticalBar;", 0x02224 }, .{ "npar;", 0x02226 }, .{ "nparallel;", 0x02226 }, .{ "nparsl;", 0x02AFD }, .{ "npart;", 0x02202 }, .{ "npolint;", 0x02A14 }, .{ "npr;", 0x02280 }, .{ "nprcue;", 0x022E0 }, .{ "npre;", 0x02AAF }, .{ "nprec;", 0x02280 }, .{ "npreceq;", 0x02AAF }, .{ "nrArr;", 0x021CF }, .{ "nrarr;", 0x0219B }, .{ "nrarrc;", 0x02933 }, .{ "nrarrw;", 0x0219D }, .{ "nRightarrow;", 0x021CF }, .{ "nrightarrow;", 0x0219B }, .{ "nrtri;", 0x022EB }, .{ "nrtrie;", 0x022ED }, .{ "nsc;", 0x02281 }, .{ "nsccue;", 0x022E1 }, .{ "nsce;", 0x02AB0 }, .{ "Nscr;", 0x1D4A9 }, .{ "nscr;", 0x1D4C3 }, .{ "nshortmid;", 0x02224 }, .{ "nshortparallel;", 0x02226 }, .{ "nsim;", 0x02241 }, .{ "nsime;", 0x02244 }, .{ "nsimeq;", 0x02244 }, .{ "nsmid;", 0x02224 }, .{ "nspar;", 0x02226 }, .{ "nsqsube;", 0x022E2 }, .{ "nsqsupe;", 0x022E3 }, .{ "nsub;", 0x02284 }, .{ "nsubE;", 0x02AC5 }, .{ "nsube;", 0x02288 }, .{ "nsubset;", 0x02282 }, .{ "nsubseteq;", 0x02288 }, .{ "nsubseteqq;", 0x02AC5 }, .{ "nsucc;", 0x02281 }, .{ "nsucceq;", 0x02AB0 }, .{ "nsup;", 0x02285 }, .{ "nsupE;", 0x02AC6 }, .{ "nsupe;", 0x02289 }, .{ "nsupset;", 0x02283 }, .{ "nsupseteq;", 0x02289 }, .{ "nsupseteqq;", 0x02AC6 }, .{ "ntgl;", 0x02279 }, .{ "Ntilde;", 0x000D1 }, .{ "Ntilde", 0x000D1 }, .{ "ntilde;", 0x000F1 }, .{ "ntilde", 0x000F1 }, .{ "ntlg;", 0x02278 }, .{ "ntriangleleft;", 0x022EA }, .{ "ntrianglelefteq;", 0x022EC }, .{ "ntriangleright;", 0x022EB }, .{ "ntrianglerighteq;", 0x022ED }, .{ "Nu;", 0x0039D }, .{ "nu;", 0x003BD }, .{ "num;", 0x00023 }, .{ "numero;", 0x02116 }, .{ "numsp;", 0x02007 }, .{ "nvap;", 0x0224D }, .{ "nVDash;", 0x022AF }, .{ "nVdash;", 0x022AE }, .{ "nvDash;", 0x022AD }, .{ "nvdash;", 0x022AC }, .{ "nvge;", 0x02265 }, .{ "nvgt;", 0x0003E }, .{ "nvHarr;", 0x02904 }, .{ "nvinfin;", 0x029DE }, .{ "nvlArr;", 0x02902 }, .{ "nvle;", 0x02264 }, .{ "nvlt;", 0x0003C }, .{ "nvltrie;", 0x022B4 }, .{ "nvrArr;", 0x02903 }, .{ "nvrtrie;", 0x022B5 }, .{ "nvsim;", 0x0223C }, .{ "nwarhk;", 0x02923 }, .{ "nwArr;", 0x021D6 }, .{ "nwarr;", 0x02196 }, .{ "nwarrow;", 0x02196 }, .{ "nwnear;", 0x02927 }, .{ "Oacute;", 0x000D3 }, .{ "Oacute", 0x000D3 }, .{ "oacute;", 0x000F3 }, .{ "oacute", 0x000F3 }, .{ "oast;", 0x0229B }, .{ "ocir;", 0x0229A }, .{ "Ocirc;", 0x000D4 }, .{ "Ocirc", 0x000D4 }, .{ "ocirc;", 0x000F4 }, .{ "ocirc", 0x000F4 }, .{ "Ocy;", 0x0041E }, .{ "ocy;", 0x0043E }, .{ "odash;", 0x0229D }, .{ "Odblac;", 0x00150 }, .{ "odblac;", 0x00151 }, .{ "odiv;", 0x02A38 }, .{ "odot;", 0x02299 }, .{ "odsold;", 0x029BC }, .{ "OElig;", 0x00152 }, .{ "oelig;", 0x00153 }, .{ "ofcir;", 0x029BF }, .{ "Ofr;", 0x1D512 }, .{ "ofr;", 0x1D52C }, .{ "ogon;", 0x002DB }, .{ "Ograve;", 0x000D2 }, .{ "Ograve", 0x000D2 }, .{ "ograve;", 0x000F2 }, .{ "ograve", 0x000F2 }, .{ "ogt;", 0x029C1 }, .{ "ohbar;", 0x029B5 }, .{ "ohm;", 0x003A9 }, .{ "oint;", 0x0222E }, .{ "olarr;", 0x021BA }, .{ "olcir;", 0x029BE }, .{ "olcross;", 0x029BB }, .{ "oline;", 0x0203E }, .{ "olt;", 0x029C0 }, .{ "Omacr;", 0x0014C }, .{ "omacr;", 0x0014D }, .{ "Omega;", 0x003A9 }, .{ "omega;", 0x003C9 }, .{ "Omicron;", 0x0039F }, .{ "omicron;", 0x003BF }, .{ "omid;", 0x029B6 }, .{ "ominus;", 0x02296 }, .{ "Oopf;", 0x1D546 }, .{ "oopf;", 0x1D560 }, .{ "opar;", 0x029B7 }, .{ "OpenCurlyDoubleQuote;", 0x0201C }, .{ "OpenCurlyQuote;", 0x02018 }, .{ "operp;", 0x029B9 }, .{ "oplus;", 0x02295 }, .{ "Or;", 0x02A54 }, .{ "or;", 0x02228 }, .{ "orarr;", 0x021BB }, .{ "ord;", 0x02A5D }, .{ "order;", 0x02134 }, .{ "orderof;", 0x02134 }, .{ "ordf;", 0x000AA }, .{ "ordf", 0x000AA }, .{ "ordm;", 0x000BA }, .{ "ordm", 0x000BA }, .{ "origof;", 0x022B6 }, .{ "oror;", 0x02A56 }, .{ "orslope;", 0x02A57 }, .{ "orv;", 0x02A5B }, .{ "oS;", 0x024C8 }, .{ "Oscr;", 0x1D4AA }, .{ "oscr;", 0x02134 }, .{ "Oslash;", 0x000D8 }, .{ "Oslash", 0x000D8 }, .{ "oslash;", 0x000F8 }, .{ "oslash", 0x000F8 }, .{ "osol;", 0x02298 }, .{ "Otilde;", 0x000D5 }, .{ "Otilde", 0x000D5 }, .{ "otilde;", 0x000F5 }, .{ "otilde", 0x000F5 }, .{ "Otimes;", 0x02A37 }, .{ "otimes;", 0x02297 }, .{ "otimesas;", 0x02A36 }, .{ "Ouml;", 0x000D6 }, .{ "Ouml", 0x000D6 }, .{ "ouml;", 0x000F6 }, .{ "ouml", 0x000F6 }, .{ "ovbar;", 0x0233D }, .{ "OverBar;", 0x0203E }, .{ "OverBrace;", 0x023DE }, .{ "OverBracket;", 0x023B4 }, .{ "OverParenthesis;", 0x023DC }, .{ "par;", 0x02225 }, .{ "para;", 0x000B6 }, .{ "para", 0x000B6 }, .{ "parallel;", 0x02225 }, .{ "parsim;", 0x02AF3 }, .{ "parsl;", 0x02AFD }, .{ "part;", 0x02202 }, .{ "PartialD;", 0x02202 }, .{ "Pcy;", 0x0041F }, .{ "pcy;", 0x0043F }, .{ "percnt;", 0x00025 }, .{ "period;", 0x0002E }, .{ "permil;", 0x02030 }, .{ "perp;", 0x022A5 }, .{ "pertenk;", 0x02031 }, .{ "Pfr;", 0x1D513 }, .{ "pfr;", 0x1D52D }, .{ "Phi;", 0x003A6 }, .{ "phi;", 0x003C6 }, .{ "phiv;", 0x003D5 }, .{ "phmmat;", 0x02133 }, .{ "phone;", 0x0260E }, .{ "Pi;", 0x003A0 }, .{ "pi;", 0x003C0 }, .{ "pitchfork;", 0x022D4 }, .{ "piv;", 0x003D6 }, .{ "planck;", 0x0210F }, .{ "planckh;", 0x0210E }, .{ "plankv;", 0x0210F }, .{ "plus;", 0x0002B }, .{ "plusacir;", 0x02A23 }, .{ "plusb;", 0x0229E }, .{ "pluscir;", 0x02A22 }, .{ "plusdo;", 0x02214 }, .{ "plusdu;", 0x02A25 }, .{ "pluse;", 0x02A72 }, .{ "PlusMinus;", 0x000B1 }, .{ "plusmn;", 0x000B1 }, .{ "plusmn", 0x000B1 }, .{ "plussim;", 0x02A26 }, .{ "plustwo;", 0x02A27 }, .{ "pm;", 0x000B1 }, .{ "Poincareplane;", 0x0210C }, .{ "pointint;", 0x02A15 }, .{ "Popf;", 0x02119 }, .{ "popf;", 0x1D561 }, .{ "pound;", 0x000A3 }, .{ "pound", 0x000A3 }, .{ "Pr;", 0x02ABB }, .{ "pr;", 0x0227A }, .{ "prap;", 0x02AB7 }, .{ "prcue;", 0x0227C }, .{ "prE;", 0x02AB3 }, .{ "pre;", 0x02AAF }, .{ "prec;", 0x0227A }, .{ "precapprox;", 0x02AB7 }, .{ "preccurlyeq;", 0x0227C }, .{ "Precedes;", 0x0227A }, .{ "PrecedesEqual;", 0x02AAF }, .{ "PrecedesSlantEqual;", 0x0227C }, .{ "PrecedesTilde;", 0x0227E }, .{ "preceq;", 0x02AAF }, .{ "precnapprox;", 0x02AB9 }, .{ "precneqq;", 0x02AB5 }, .{ "precnsim;", 0x022E8 }, .{ "precsim;", 0x0227E }, .{ "Prime;", 0x02033 }, .{ "prime;", 0x02032 }, .{ "primes;", 0x02119 }, .{ "prnap;", 0x02AB9 }, .{ "prnE;", 0x02AB5 }, .{ "prnsim;", 0x022E8 }, .{ "prod;", 0x0220F }, .{ "Product;", 0x0220F }, .{ "profalar;", 0x0232E }, .{ "profline;", 0x02312 }, .{ "profsurf;", 0x02313 }, .{ "prop;", 0x0221D }, .{ "Proportion;", 0x02237 }, .{ "Proportional;", 0x0221D }, .{ "propto;", 0x0221D }, .{ "prsim;", 0x0227E }, .{ "prurel;", 0x022B0 }, .{ "Pscr;", 0x1D4AB }, .{ "pscr;", 0x1D4C5 }, .{ "Psi;", 0x003A8 }, .{ "psi;", 0x003C8 }, .{ "puncsp;", 0x02008 }, .{ "Qfr;", 0x1D514 }, .{ "qfr;", 0x1D52E }, .{ "qint;", 0x02A0C }, .{ "Qopf;", 0x0211A }, .{ "qopf;", 0x1D562 }, .{ "qprime;", 0x02057 }, .{ "Qscr;", 0x1D4AC }, .{ "qscr;", 0x1D4C6 }, .{ "quaternions;", 0x0210D }, .{ "quatint;", 0x02A16 }, .{ "quest;", 0x0003F }, .{ "questeq;", 0x0225F }, .{ "QUOT;", 0x00022 }, .{ "QUOT", 0x00022 }, .{ "quot;", 0x00022 }, .{ "quot", 0x00022 }, .{ "rAarr;", 0x021DB }, .{ "race;", 0x0223D }, .{ "Racute;", 0x00154 }, .{ "racute;", 0x00155 }, .{ "radic;", 0x0221A }, .{ "raemptyv;", 0x029B3 }, .{ "Rang;", 0x027EB }, .{ "rang;", 0x027E9 }, .{ "rangd;", 0x02992 }, .{ "range;", 0x029A5 }, .{ "rangle;", 0x027E9 }, .{ "raquo;", 0x000BB }, .{ "raquo", 0x000BB }, .{ "Rarr;", 0x021A0 }, .{ "rArr;", 0x021D2 }, .{ "rarr;", 0x02192 }, .{ "rarrap;", 0x02975 }, .{ "rarrb;", 0x021E5 }, .{ "rarrbfs;", 0x02920 }, .{ "rarrc;", 0x02933 }, .{ "rarrfs;", 0x0291E }, .{ "rarrhk;", 0x021AA }, .{ "rarrlp;", 0x021AC }, .{ "rarrpl;", 0x02945 }, .{ "rarrsim;", 0x02974 }, .{ "Rarrtl;", 0x02916 }, .{ "rarrtl;", 0x021A3 }, .{ "rarrw;", 0x0219D }, .{ "rAtail;", 0x0291C }, .{ "ratail;", 0x0291A }, .{ "ratio;", 0x02236 }, .{ "rationals;", 0x0211A }, .{ "RBarr;", 0x02910 }, .{ "rBarr;", 0x0290F }, .{ "rbarr;", 0x0290D }, .{ "rbbrk;", 0x02773 }, .{ "rbrace;", 0x0007D }, .{ "rbrack;", 0x0005D }, .{ "rbrke;", 0x0298C }, .{ "rbrksld;", 0x0298E }, .{ "rbrkslu;", 0x02990 }, .{ "Rcaron;", 0x00158 }, .{ "rcaron;", 0x00159 }, .{ "Rcedil;", 0x00156 }, .{ "rcedil;", 0x00157 }, .{ "rceil;", 0x02309 }, .{ "rcub;", 0x0007D }, .{ "Rcy;", 0x00420 }, .{ "rcy;", 0x00440 }, .{ "rdca;", 0x02937 }, .{ "rdldhar;", 0x02969 }, .{ "rdquo;", 0x0201D }, .{ "rdquor;", 0x0201D }, .{ "rdsh;", 0x021B3 }, .{ "Re;", 0x0211C }, .{ "real;", 0x0211C }, .{ "realine;", 0x0211B }, .{ "realpart;", 0x0211C }, .{ "reals;", 0x0211D }, .{ "rect;", 0x025AD }, .{ "REG;", 0x000AE }, .{ "REG", 0x000AE }, .{ "reg;", 0x000AE }, .{ "reg", 0x000AE }, .{ "ReverseElement;", 0x0220B }, .{ "ReverseEquilibrium;", 0x021CB }, .{ "ReverseUpEquilibrium;", 0x0296F }, .{ "rfisht;", 0x0297D }, .{ "rfloor;", 0x0230B }, .{ "Rfr;", 0x0211C }, .{ "rfr;", 0x1D52F }, .{ "rHar;", 0x02964 }, .{ "rhard;", 0x021C1 }, .{ "rharu;", 0x021C0 }, .{ "rharul;", 0x0296C }, .{ "Rho;", 0x003A1 }, .{ "rho;", 0x003C1 }, .{ "rhov;", 0x003F1 }, .{ "RightAngleBracket;", 0x027E9 }, .{ "RightArrow;", 0x02192 }, .{ "Rightarrow;", 0x021D2 }, .{ "rightarrow;", 0x02192 }, .{ "RightArrowBar;", 0x021E5 }, .{ "RightArrowLeftArrow;", 0x021C4 }, .{ "rightarrowtail;", 0x021A3 }, .{ "RightCeiling;", 0x02309 }, .{ "RightDoubleBracket;", 0x027E7 }, .{ "RightDownTeeVector;", 0x0295D }, .{ "RightDownVector;", 0x021C2 }, .{ "RightDownVectorBar;", 0x02955 }, .{ "RightFloor;", 0x0230B }, .{ "rightharpoondown;", 0x021C1 }, .{ "rightharpoonup;", 0x021C0 }, .{ "rightleftarrows;", 0x021C4 }, .{ "rightleftharpoons;", 0x021CC }, .{ "rightrightarrows;", 0x021C9 }, .{ "rightsquigarrow;", 0x0219D }, .{ "RightTee;", 0x022A2 }, .{ "RightTeeArrow;", 0x021A6 }, .{ "RightTeeVector;", 0x0295B }, .{ "rightthreetimes;", 0x022CC }, .{ "RightTriangle;", 0x022B3 }, .{ "RightTriangleBar;", 0x029D0 }, .{ "RightTriangleEqual;", 0x022B5 }, .{ "RightUpDownVector;", 0x0294F }, .{ "RightUpTeeVector;", 0x0295C }, .{ "RightUpVector;", 0x021BE }, .{ "RightUpVectorBar;", 0x02954 }, .{ "RightVector;", 0x021C0 }, .{ "RightVectorBar;", 0x02953 }, .{ "ring;", 0x002DA }, .{ "risingdotseq;", 0x02253 }, .{ "rlarr;", 0x021C4 }, .{ "rlhar;", 0x021CC }, .{ "rlm;", 0x0200F }, .{ "rmoust;", 0x023B1 }, .{ "rmoustache;", 0x023B1 }, .{ "rnmid;", 0x02AEE }, .{ "roang;", 0x027ED }, .{ "roarr;", 0x021FE }, .{ "robrk;", 0x027E7 }, .{ "ropar;", 0x02986 }, .{ "Ropf;", 0x0211D }, .{ "ropf;", 0x1D563 }, .{ "roplus;", 0x02A2E }, .{ "rotimes;", 0x02A35 }, .{ "RoundImplies;", 0x02970 }, .{ "rpar;", 0x00029 }, .{ "rpargt;", 0x02994 }, .{ "rppolint;", 0x02A12 }, .{ "rrarr;", 0x021C9 }, .{ "Rrightarrow;", 0x021DB }, .{ "rsaquo;", 0x0203A }, .{ "Rscr;", 0x0211B }, .{ "rscr;", 0x1D4C7 }, .{ "Rsh;", 0x021B1 }, .{ "rsh;", 0x021B1 }, .{ "rsqb;", 0x0005D }, .{ "rsquo;", 0x02019 }, .{ "rsquor;", 0x02019 }, .{ "rthree;", 0x022CC }, .{ "rtimes;", 0x022CA }, .{ "rtri;", 0x025B9 }, .{ "rtrie;", 0x022B5 }, .{ "rtrif;", 0x025B8 }, .{ "rtriltri;", 0x029CE }, .{ "RuleDelayed;", 0x029F4 }, .{ "ruluhar;", 0x02968 }, .{ "rx;", 0x0211E }, .{ "Sacute;", 0x0015A }, .{ "sacute;", 0x0015B }, .{ "sbquo;", 0x0201A }, .{ "Sc;", 0x02ABC }, .{ "sc;", 0x0227B }, .{ "scap;", 0x02AB8 }, .{ "Scaron;", 0x00160 }, .{ "scaron;", 0x00161 }, .{ "sccue;", 0x0227D }, .{ "scE;", 0x02AB4 }, .{ "sce;", 0x02AB0 }, .{ "Scedil;", 0x0015E }, .{ "scedil;", 0x0015F }, .{ "Scirc;", 0x0015C }, .{ "scirc;", 0x0015D }, .{ "scnap;", 0x02ABA }, .{ "scnE;", 0x02AB6 }, .{ "scnsim;", 0x022E9 }, .{ "scpolint;", 0x02A13 }, .{ "scsim;", 0x0227F }, .{ "Scy;", 0x00421 }, .{ "scy;", 0x00441 }, .{ "sdot;", 0x022C5 }, .{ "sdotb;", 0x022A1 }, .{ "sdote;", 0x02A66 }, .{ "searhk;", 0x02925 }, .{ "seArr;", 0x021D8 }, .{ "searr;", 0x02198 }, .{ "searrow;", 0x02198 }, .{ "sect;", 0x000A7 }, .{ "sect", 0x000A7 }, .{ "semi;", 0x0003B }, .{ "seswar;", 0x02929 }, .{ "setminus;", 0x02216 }, .{ "setmn;", 0x02216 }, .{ "sext;", 0x02736 }, .{ "Sfr;", 0x1D516 }, .{ "sfr;", 0x1D530 }, .{ "sfrown;", 0x02322 }, .{ "sharp;", 0x0266F }, .{ "SHCHcy;", 0x00429 }, .{ "shchcy;", 0x00449 }, .{ "SHcy;", 0x00428 }, .{ "shcy;", 0x00448 }, .{ "ShortDownArrow;", 0x02193 }, .{ "ShortLeftArrow;", 0x02190 }, .{ "shortmid;", 0x02223 }, .{ "shortparallel;", 0x02225 }, .{ "ShortRightArrow;", 0x02192 }, .{ "ShortUpArrow;", 0x02191 }, .{ "shy;", 0x000AD }, .{ "shy", 0x000AD }, .{ "Sigma;", 0x003A3 }, .{ "sigma;", 0x003C3 }, .{ "sigmaf;", 0x003C2 }, .{ "sigmav;", 0x003C2 }, .{ "sim;", 0x0223C }, .{ "simdot;", 0x02A6A }, .{ "sime;", 0x02243 }, .{ "simeq;", 0x02243 }, .{ "simg;", 0x02A9E }, .{ "simgE;", 0x02AA0 }, .{ "siml;", 0x02A9D }, .{ "simlE;", 0x02A9F }, .{ "simne;", 0x02246 }, .{ "simplus;", 0x02A24 }, .{ "simrarr;", 0x02972 }, .{ "slarr;", 0x02190 }, .{ "SmallCircle;", 0x02218 }, .{ "smallsetminus;", 0x02216 }, .{ "smashp;", 0x02A33 }, .{ "smeparsl;", 0x029E4 }, .{ "smid;", 0x02223 }, .{ "smile;", 0x02323 }, .{ "smt;", 0x02AAA }, .{ "smte;", 0x02AAC }, .{ "smtes;", 0x02AAC }, .{ "SOFTcy;", 0x0042C }, .{ "softcy;", 0x0044C }, .{ "sol;", 0x0002F }, .{ "solb;", 0x029C4 }, .{ "solbar;", 0x0233F }, .{ "Sopf;", 0x1D54A }, .{ "sopf;", 0x1D564 }, .{ "spades;", 0x02660 }, .{ "spadesuit;", 0x02660 }, .{ "spar;", 0x02225 }, .{ "sqcap;", 0x02293 }, .{ "sqcaps;", 0x02293 }, .{ "sqcup;", 0x02294 }, .{ "sqcups;", 0x02294 }, .{ "Sqrt;", 0x0221A }, .{ "sqsub;", 0x0228F }, .{ "sqsube;", 0x02291 }, .{ "sqsubset;", 0x0228F }, .{ "sqsubseteq;", 0x02291 }, .{ "sqsup;", 0x02290 }, .{ "sqsupe;", 0x02292 }, .{ "sqsupset;", 0x02290 }, .{ "sqsupseteq;", 0x02292 }, .{ "squ;", 0x025A1 }, .{ "Square;", 0x025A1 }, .{ "square;", 0x025A1 }, .{ "SquareIntersection;", 0x02293 }, .{ "SquareSubset;", 0x0228F }, .{ "SquareSubsetEqual;", 0x02291 }, .{ "SquareSuperset;", 0x02290 }, .{ "SquareSupersetEqual;", 0x02292 }, .{ "SquareUnion;", 0x02294 }, .{ "squarf;", 0x025AA }, .{ "squf;", 0x025AA }, .{ "srarr;", 0x02192 }, .{ "Sscr;", 0x1D4AE }, .{ "sscr;", 0x1D4C8 }, .{ "ssetmn;", 0x02216 }, .{ "ssmile;", 0x02323 }, .{ "sstarf;", 0x022C6 }, .{ "Star;", 0x022C6 }, .{ "star;", 0x02606 }, .{ "starf;", 0x02605 }, .{ "straightepsilon;", 0x003F5 }, .{ "straightphi;", 0x003D5 }, .{ "strns;", 0x000AF }, .{ "Sub;", 0x022D0 }, .{ "sub;", 0x02282 }, .{ "subdot;", 0x02ABD }, .{ "subE;", 0x02AC5 }, .{ "sube;", 0x02286 }, .{ "subedot;", 0x02AC3 }, .{ "submult;", 0x02AC1 }, .{ "subnE;", 0x02ACB }, .{ "subne;", 0x0228A }, .{ "subplus;", 0x02ABF }, .{ "subrarr;", 0x02979 }, .{ "Subset;", 0x022D0 }, .{ "subset;", 0x02282 }, .{ "subseteq;", 0x02286 }, .{ "subseteqq;", 0x02AC5 }, .{ "SubsetEqual;", 0x02286 }, .{ "subsetneq;", 0x0228A }, .{ "subsetneqq;", 0x02ACB }, .{ "subsim;", 0x02AC7 }, .{ "subsub;", 0x02AD5 }, .{ "subsup;", 0x02AD3 }, .{ "succ;", 0x0227B }, .{ "succapprox;", 0x02AB8 }, .{ "succcurlyeq;", 0x0227D }, .{ "Succeeds;", 0x0227B }, .{ "SucceedsEqual;", 0x02AB0 }, .{ "SucceedsSlantEqual;", 0x0227D }, .{ "SucceedsTilde;", 0x0227F }, .{ "succeq;", 0x02AB0 }, .{ "succnapprox;", 0x02ABA }, .{ "succneqq;", 0x02AB6 }, .{ "succnsim;", 0x022E9 }, .{ "succsim;", 0x0227F }, .{ "SuchThat;", 0x0220B }, .{ "Sum;", 0x02211 }, .{ "sum;", 0x02211 }, .{ "sung;", 0x0266A }, .{ "Sup;", 0x022D1 }, .{ "sup;", 0x02283 }, .{ "sup1;", 0x000B9 }, .{ "sup1", 0x000B9 }, .{ "sup2;", 0x000B2 }, .{ "sup2", 0x000B2 }, .{ "sup3;", 0x000B3 }, .{ "sup3", 0x000B3 }, .{ "supdot;", 0x02ABE }, .{ "supdsub;", 0x02AD8 }, .{ "supE;", 0x02AC6 }, .{ "supe;", 0x02287 }, .{ "supedot;", 0x02AC4 }, .{ "Superset;", 0x02283 }, .{ "SupersetEqual;", 0x02287 }, .{ "suphsol;", 0x027C9 }, .{ "suphsub;", 0x02AD7 }, .{ "suplarr;", 0x0297B }, .{ "supmult;", 0x02AC2 }, .{ "supnE;", 0x02ACC }, .{ "supne;", 0x0228B }, .{ "supplus;", 0x02AC0 }, .{ "Supset;", 0x022D1 }, .{ "supset;", 0x02283 }, .{ "supseteq;", 0x02287 }, .{ "supseteqq;", 0x02AC6 }, .{ "supsetneq;", 0x0228B }, .{ "supsetneqq;", 0x02ACC }, .{ "supsim;", 0x02AC8 }, .{ "supsub;", 0x02AD4 }, .{ "supsup;", 0x02AD6 }, .{ "swarhk;", 0x02926 }, .{ "swArr;", 0x021D9 }, .{ "swarr;", 0x02199 }, .{ "swarrow;", 0x02199 }, .{ "swnwar;", 0x0292A }, .{ "szlig;", 0x000DF }, .{ "szlig", 0x000DF }, .{ "Tab;", 0x00009 }, .{ "target;", 0x02316 }, .{ "Tau;", 0x003A4 }, .{ "tau;", 0x003C4 }, .{ "tbrk;", 0x023B4 }, .{ "Tcaron;", 0x00164 }, .{ "tcaron;", 0x00165 }, .{ "Tcedil;", 0x00162 }, .{ "tcedil;", 0x00163 }, .{ "Tcy;", 0x00422 }, .{ "tcy;", 0x00442 }, .{ "tdot;", 0x020DB }, .{ "telrec;", 0x02315 }, .{ "Tfr;", 0x1D517 }, .{ "tfr;", 0x1D531 }, .{ "there4;", 0x02234 }, .{ "Therefore;", 0x02234 }, .{ "therefore;", 0x02234 }, .{ "Theta;", 0x00398 }, .{ "theta;", 0x003B8 }, .{ "thetasym;", 0x003D1 }, .{ "thetav;", 0x003D1 }, .{ "thickapprox;", 0x02248 }, .{ "thicksim;", 0x0223C }, .{ "ThickSpace;", 0x0205F }, .{ "thinsp;", 0x02009 }, .{ "ThinSpace;", 0x02009 }, .{ "thkap;", 0x02248 }, .{ "thksim;", 0x0223C }, .{ "THORN;", 0x000DE }, .{ "THORN", 0x000DE }, .{ "thorn;", 0x000FE }, .{ "thorn", 0x000FE }, .{ "Tilde;", 0x0223C }, .{ "tilde;", 0x002DC }, .{ "TildeEqual;", 0x02243 }, .{ "TildeFullEqual;", 0x02245 }, .{ "TildeTilde;", 0x02248 }, .{ "times;", 0x000D7 }, .{ "times", 0x000D7 }, .{ "timesb;", 0x022A0 }, .{ "timesbar;", 0x02A31 }, .{ "timesd;", 0x02A30 }, .{ "tint;", 0x0222D }, .{ "toea;", 0x02928 }, .{ "top;", 0x022A4 }, .{ "topbot;", 0x02336 }, .{ "topcir;", 0x02AF1 }, .{ "Topf;", 0x1D54B }, .{ "topf;", 0x1D565 }, .{ "topfork;", 0x02ADA }, .{ "tosa;", 0x02929 }, .{ "tprime;", 0x02034 }, .{ "TRADE;", 0x02122 }, .{ "trade;", 0x02122 }, .{ "triangle;", 0x025B5 }, .{ "triangledown;", 0x025BF }, .{ "triangleleft;", 0x025C3 }, .{ "trianglelefteq;", 0x022B4 }, .{ "triangleq;", 0x0225C }, .{ "triangleright;", 0x025B9 }, .{ "trianglerighteq;", 0x022B5 }, .{ "tridot;", 0x025EC }, .{ "trie;", 0x0225C }, .{ "triminus;", 0x02A3A }, .{ "TripleDot;", 0x020DB }, .{ "triplus;", 0x02A39 }, .{ "trisb;", 0x029CD }, .{ "tritime;", 0x02A3B }, .{ "trpezium;", 0x023E2 }, .{ "Tscr;", 0x1D4AF }, .{ "tscr;", 0x1D4C9 }, .{ "TScy;", 0x00426 }, .{ "tscy;", 0x00446 }, .{ "TSHcy;", 0x0040B }, .{ "tshcy;", 0x0045B }, .{ "Tstrok;", 0x00166 }, .{ "tstrok;", 0x00167 }, .{ "twixt;", 0x0226C }, .{ "twoheadleftarrow;", 0x0219E }, .{ "twoheadrightarrow;", 0x021A0 }, .{ "Uacute;", 0x000DA }, .{ "Uacute", 0x000DA }, .{ "uacute;", 0x000FA }, .{ "uacute", 0x000FA }, .{ "Uarr;", 0x0219F }, .{ "uArr;", 0x021D1 }, .{ "uarr;", 0x02191 }, .{ "Uarrocir;", 0x02949 }, .{ "Ubrcy;", 0x0040E }, .{ "ubrcy;", 0x0045E }, .{ "Ubreve;", 0x0016C }, .{ "ubreve;", 0x0016D }, .{ "Ucirc;", 0x000DB }, .{ "Ucirc", 0x000DB }, .{ "ucirc;", 0x000FB }, .{ "ucirc", 0x000FB }, .{ "Ucy;", 0x00423 }, .{ "ucy;", 0x00443 }, .{ "udarr;", 0x021C5 }, .{ "Udblac;", 0x00170 }, .{ "udblac;", 0x00171 }, .{ "udhar;", 0x0296E }, .{ "ufisht;", 0x0297E }, .{ "Ufr;", 0x1D518 }, .{ "ufr;", 0x1D532 }, .{ "Ugrave;", 0x000D9 }, .{ "Ugrave", 0x000D9 }, .{ "ugrave;", 0x000F9 }, .{ "ugrave", 0x000F9 }, .{ "uHar;", 0x02963 }, .{ "uharl;", 0x021BF }, .{ "uharr;", 0x021BE }, .{ "uhblk;", 0x02580 }, .{ "ulcorn;", 0x0231C }, .{ "ulcorner;", 0x0231C }, .{ "ulcrop;", 0x0230F }, .{ "ultri;", 0x025F8 }, .{ "Umacr;", 0x0016A }, .{ "umacr;", 0x0016B }, .{ "uml;", 0x000A8 }, .{ "uml", 0x000A8 }, .{ "UnderBar;", 0x0005F }, .{ "UnderBrace;", 0x023DF }, .{ "UnderBracket;", 0x023B5 }, .{ "UnderParenthesis;", 0x023DD }, .{ "Union;", 0x022C3 }, .{ "UnionPlus;", 0x0228E }, .{ "Uogon;", 0x00172 }, .{ "uogon;", 0x00173 }, .{ "Uopf;", 0x1D54C }, .{ "uopf;", 0x1D566 }, .{ "UpArrow;", 0x02191 }, .{ "Uparrow;", 0x021D1 }, .{ "uparrow;", 0x02191 }, .{ "UpArrowBar;", 0x02912 }, .{ "UpArrowDownArrow;", 0x021C5 }, .{ "UpDownArrow;", 0x02195 }, .{ "Updownarrow;", 0x021D5 }, .{ "updownarrow;", 0x02195 }, .{ "UpEquilibrium;", 0x0296E }, .{ "upharpoonleft;", 0x021BF }, .{ "upharpoonright;", 0x021BE }, .{ "uplus;", 0x0228E }, .{ "UpperLeftArrow;", 0x02196 }, .{ "UpperRightArrow;", 0x02197 }, .{ "Upsi;", 0x003D2 }, .{ "upsi;", 0x003C5 }, .{ "upsih;", 0x003D2 }, .{ "Upsilon;", 0x003A5 }, .{ "upsilon;", 0x003C5 }, .{ "UpTee;", 0x022A5 }, .{ "UpTeeArrow;", 0x021A5 }, .{ "upuparrows;", 0x021C8 }, .{ "urcorn;", 0x0231D }, .{ "urcorner;", 0x0231D }, .{ "urcrop;", 0x0230E }, .{ "Uring;", 0x0016E }, .{ "uring;", 0x0016F }, .{ "urtri;", 0x025F9 }, .{ "Uscr;", 0x1D4B0 }, .{ "uscr;", 0x1D4CA }, .{ "utdot;", 0x022F0 }, .{ "Utilde;", 0x00168 }, .{ "utilde;", 0x00169 }, .{ "utri;", 0x025B5 }, .{ "utrif;", 0x025B4 }, .{ "uuarr;", 0x021C8 }, .{ "Uuml;", 0x000DC }, .{ "Uuml", 0x000DC }, .{ "uuml;", 0x000FC }, .{ "uuml", 0x000FC }, .{ "uwangle;", 0x029A7 }, .{ "vangrt;", 0x0299C }, .{ "varepsilon;", 0x003F5 }, .{ "varkappa;", 0x003F0 }, .{ "varnothing;", 0x02205 }, .{ "varphi;", 0x003D5 }, .{ "varpi;", 0x003D6 }, .{ "varpropto;", 0x0221D }, .{ "vArr;", 0x021D5 }, .{ "varr;", 0x02195 }, .{ "varrho;", 0x003F1 }, .{ "varsigma;", 0x003C2 }, .{ "varsubsetneq;", 0x0228A }, .{ "varsubsetneqq;", 0x02ACB }, .{ "varsupsetneq;", 0x0228B }, .{ "varsupsetneqq;", 0x02ACC }, .{ "vartheta;", 0x003D1 }, .{ "vartriangleleft;", 0x022B2 }, .{ "vartriangleright;", 0x022B3 }, .{ "Vbar;", 0x02AEB }, .{ "vBar;", 0x02AE8 }, .{ "vBarv;", 0x02AE9 }, .{ "Vcy;", 0x00412 }, .{ "vcy;", 0x00432 }, .{ "VDash;", 0x022AB }, .{ "Vdash;", 0x022A9 }, .{ "vDash;", 0x022A8 }, .{ "vdash;", 0x022A2 }, .{ "Vdashl;", 0x02AE6 }, .{ "Vee;", 0x022C1 }, .{ "vee;", 0x02228 }, .{ "veebar;", 0x022BB }, .{ "veeeq;", 0x0225A }, .{ "vellip;", 0x022EE }, .{ "Verbar;", 0x02016 }, .{ "verbar;", 0x0007C }, .{ "Vert;", 0x02016 }, .{ "vert;", 0x0007C }, .{ "VerticalBar;", 0x02223 }, .{ "VerticalLine;", 0x0007C }, .{ "VerticalSeparator;", 0x02758 }, .{ "VerticalTilde;", 0x02240 }, .{ "VeryThinSpace;", 0x0200A }, .{ "Vfr;", 0x1D519 }, .{ "vfr;", 0x1D533 }, .{ "vltri;", 0x022B2 }, .{ "vnsub;", 0x02282 }, .{ "vnsup;", 0x02283 }, .{ "Vopf;", 0x1D54D }, .{ "vopf;", 0x1D567 }, .{ "vprop;", 0x0221D }, .{ "vrtri;", 0x022B3 }, .{ "Vscr;", 0x1D4B1 }, .{ "vscr;", 0x1D4CB }, .{ "vsubnE;", 0x02ACB }, .{ "vsubne;", 0x0228A }, .{ "vsupnE;", 0x02ACC }, .{ "vsupne;", 0x0228B }, .{ "Vvdash;", 0x022AA }, .{ "vzigzag;", 0x0299A }, .{ "Wcirc;", 0x00174 }, .{ "wcirc;", 0x00175 }, .{ "wedbar;", 0x02A5F }, .{ "Wedge;", 0x022C0 }, .{ "wedge;", 0x02227 }, .{ "wedgeq;", 0x02259 }, .{ "weierp;", 0x02118 }, .{ "Wfr;", 0x1D51A }, .{ "wfr;", 0x1D534 }, .{ "Wopf;", 0x1D54E }, .{ "wopf;", 0x1D568 }, .{ "wp;", 0x02118 }, .{ "wr;", 0x02240 }, .{ "wreath;", 0x02240 }, .{ "Wscr;", 0x1D4B2 }, .{ "wscr;", 0x1D4CC }, .{ "xcap;", 0x022C2 }, .{ "xcirc;", 0x025EF }, .{ "xcup;", 0x022C3 }, .{ "xdtri;", 0x025BD }, .{ "Xfr;", 0x1D51B }, .{ "xfr;", 0x1D535 }, .{ "xhArr;", 0x027FA }, .{ "xharr;", 0x027F7 }, .{ "Xi;", 0x0039E }, .{ "xi;", 0x003BE }, .{ "xlArr;", 0x027F8 }, .{ "xlarr;", 0x027F5 }, .{ "xmap;", 0x027FC }, .{ "xnis;", 0x022FB }, .{ "xodot;", 0x02A00 }, .{ "Xopf;", 0x1D54F }, .{ "xopf;", 0x1D569 }, .{ "xoplus;", 0x02A01 }, .{ "xotime;", 0x02A02 }, .{ "xrArr;", 0x027F9 }, .{ "xrarr;", 0x027F6 }, .{ "Xscr;", 0x1D4B3 }, .{ "xscr;", 0x1D4CD }, .{ "xsqcup;", 0x02A06 }, .{ "xuplus;", 0x02A04 }, .{ "xutri;", 0x025B3 }, .{ "xvee;", 0x022C1 }, .{ "xwedge;", 0x022C0 }, .{ "Yacute;", 0x000DD }, .{ "Yacute", 0x000DD }, .{ "yacute;", 0x000FD }, .{ "yacute", 0x000FD }, .{ "YAcy;", 0x0042F }, .{ "yacy;", 0x0044F }, .{ "Ycirc;", 0x00176 }, .{ "ycirc;", 0x00177 }, .{ "Ycy;", 0x0042B }, .{ "ycy;", 0x0044B }, .{ "yen;", 0x000A5 }, .{ "yen", 0x000A5 }, .{ "Yfr;", 0x1D51C }, .{ "yfr;", 0x1D536 }, .{ "YIcy;", 0x00407 }, .{ "yicy;", 0x00457 }, .{ "Yopf;", 0x1D550 }, .{ "yopf;", 0x1D56A }, .{ "Yscr;", 0x1D4B4 }, .{ "yscr;", 0x1D4CE }, .{ "YUcy;", 0x0042E }, .{ "yucy;", 0x0044E }, .{ "Yuml;", 0x00178 }, .{ "yuml;", 0x000FF }, .{ "yuml", 0x000FF }, .{ "Zacute;", 0x00179 }, .{ "zacute;", 0x0017A }, .{ "Zcaron;", 0x0017D }, .{ "zcaron;", 0x0017E }, .{ "Zcy;", 0x00417 }, .{ "zcy;", 0x00437 }, .{ "Zdot;", 0x0017B }, .{ "zdot;", 0x0017C }, .{ "zeetrf;", 0x02128 }, .{ "ZeroWidthSpace;", 0x0200B }, .{ "Zeta;", 0x00396 }, .{ "zeta;", 0x003B6 }, .{ "Zfr;", 0x02128 }, .{ "zfr;", 0x1D537 }, .{ "ZHcy;", 0x00416 }, .{ "zhcy;", 0x00436 }, .{ "zigrarr;", 0x021DD }, .{ "Zopf;", 0x02124 }, .{ "zopf;", 0x1D56B }, .{ "Zscr;", 0x1D4B5 }, .{ "zscr;", 0x1D4CF }, .{ "zwj;", 0x0200D }, .{ "zwnj;", 0x0200 }, }; var hashmap = StringHashMap(u21).init(allocator); var i: usize = 0; inline for (pairs) |pair| { _ = hashmap.put(pair.@"0", pair.@"1") catch unreachable; } return hashmap; }
src/namedCharacterReference.zig
const os = @import("root").os; const builtin = @import("builtin"); const std = @import("std"); const paging = os.memory.paging; const pci = os.platform.pci; const libalign = os.lib.libalign; const range = os.lib.range; const RSDP = packed struct { signature: [8]u8, checksum: u8, oemid: [6]u8, revision: u8, rsdt_addr: u32, extended_length: u32, xsdt_addr: u64, extended_checksum: u8, }; const SDTHeader = packed struct { signature: [4]u8, len: u32, revision: u8, checksum: u8, oem: [6]u8, oem_table: [8]u8, oem_revison: u32, creator_id: u32, creator_revision: u32, }; const GenericAddrStructure = packed struct { addrspace: u8, bit_width: u8, bit_offset: u8, access_size: u8, base: u64, }; const FADT = packed struct { header: SDTHeader, firmware_control: u32, dsdt: u32, res0: u8, profile: u8, sci_irq: u16, smi_command_port: u32, acpi_enable: u8, acpi_disable: u8, s4bios_req: u8, pstate_control: u8, pm1a_event_block: u32, pm1b_event_block: u32, pm1a_control_block: u32, pm1b_control_block: u32, pm2_control_block: u32, pm_timer_block: u32, gpe0_block: u32, gpe1_block: u32, pm1_event_length: u8, pm1_control_length: u8, pm2_control_length: u8, pm_timer_length: u8, gpe0_length: u8, gpe1_length: u8, gpe1_base: u8, cstate_control: u8, worst_c2_latency: u16, worst_c3_latency: u16, flush_size: u16, flush_stride: u16, duty_offset: u8, duty_width: u8, // cmos registers day_alarm: u8, month_alarm: u8, century: u8, // ACPI 2.0 fields iapc_boot_flags: u16, reserved2: u8, flags: u32, reset_register: GenericAddrStructure, reset_command: u8, arm_boot_flags: u16, minor_version: u8, x_firmware_control: u64, x_dsdt: u64, x_pm1a_event_block: GenericAddrStructure, x_pm1b_event_block: GenericAddrStructure, x_pm1a_control_block: GenericAddrStructure, x_pm1b_control_block: GenericAddrStructure, x_pm2_control_block: GenericAddrStructure, x_pm_timer_block: GenericAddrStructure, x_gpe0_block: GenericAddrStructure, x_gpe1_block: GenericAddrStructure, }; comptime { std.debug.assert(@byteOffsetOf(FADT, "dsdt") == 40); std.debug.assert(@byteOffsetOf(FADT, "x_dsdt") == 140); } const lai = os.lib.lai; var rsdp_phys: usize = 0; var rsdp: *RSDP = undefined; pub fn register_rsdp(rsdp_in: usize) void { rsdp_phys = rsdp_in; } fn locate_rsdp() ?u64 { // @TODO return null; } fn parse_MCFG(sdt: []u8) void { var offset: usize = 44; while(offset + 16 <= sdt.len): (offset += 16) { var addr = std.mem.readIntNative(u64, sdt[offset..][0..8]); var lo_bus = sdt[offset + 10]; const hi_bus = sdt[offset + 11]; while(true) { pci.register_mmio(lo_bus, addr) catch |err| { os.log("ACPI: Unable to register PCI mmio: {}\n", .{@errorName(err)}); }; if(lo_bus == hi_bus) break; addr += 1 << 20; lo_bus += 1; } } } fn signature_value(sdt: anytype) u32 { return std.mem.readIntNative(u32, sdt[0..4]); } fn get_sdt(addr: u64) []u8 { var result = os.platform.phys_slice(u8).init(addr, 8); result.len = std.mem.readIntNative(u32, result.to_slice_writeback()[4..8]); return result.to_slice_writeback(); } fn parse_sdt(addr: usize) void { const sdt = get_sdt(addr); switch(signature_value(sdt)) { signature_value("FACP") => { }, // Ignore for now signature_value("SSDT") => { }, // Ignore for now signature_value("DMAR") => { }, // Ignore for now signature_value("ECDT") => { }, // Ignore for now signature_value("SBST") => { }, // Ignore for now signature_value("HPET") => { }, // Ignore for now signature_value("WAET") => { }, // Ignore for now signature_value("SPCR") => { }, // Ignore for now signature_value("GTDT") => { }, // Ignore for now signature_value("APIC") => { switch(builtin.arch) { .x86_64 => @import("x86_64/apic.zig").handle_madt(sdt), else => os.log("ACPI: MADT found on unsupported architecture!\n", .{}), } }, signature_value("MCFG") => { parse_MCFG(sdt); }, else => { os.log("ACPI: Unknown SDT: '{s}' with size {} bytes\n", .{sdt[0..4], sdt.len}); }, } } fn parse_root_sdt(comptime T: type, addr: usize) void { const sdt = get_sdt(addr); var offset: u64 = 36; while(offset + @sizeOf(T) <= sdt.len): (offset += @sizeOf(T)) { parse_sdt(std.mem.readIntNative(T, sdt[offset..][0..@sizeOf(T)])); } } export fn laihost_log(kind: c_int, str: [*:0]const u8) void { os.log("[{s}]: {s}\n", .{ switch(kind) { lai.LAI_WARN_LOG => @as([]const u8, "LAI WARN"), lai.LAI_DEBUG_LOG => @as([]const u8, "LAI DEBUG"), else => @as([]const u8, "LAI UNK"), }, str, }); } fn impl_laihost_scan_table(addr: usize, name: *const [4]u8, index: *c_int) ?*c_void { const table = get_sdt(addr); if(std.mem.eql(u8, table[0..4], name)) { if(index.* == 0) return @ptrCast(*c_void, table.ptr); index.* -= 1; } return null; } fn impl_laihost_scan_root(comptime T: type, addr: usize, name: *const [4]u8, index_c: c_int) ?*c_void { const sdt = get_sdt(addr); var index = index_c; var offset: u64 = 36; while(offset + @sizeOf(T) <= sdt.len): (offset += @sizeOf(T)) { const paddr = std.mem.readIntNative(T, sdt[offset..][0..@sizeOf(T)]); if(impl_laihost_scan_table(paddr, name, &index)) |result| return result; } return lai.NULL; } export fn laihost_scan(name: *const [4]u8, index: c_int) ?*c_void { if(index == 0) { if(std.mem.eql(u8, name, "RSDT")) return @ptrCast(*c_void, get_sdt(rsdp.rsdt_addr).ptr); if(std.mem.eql(u8, name, "XSDT")) return @ptrCast(*c_void, get_sdt(rsdp.xsdt_addr).ptr); if(std.mem.eql(u8, name, "DSDT")) { const fadt = @ptrCast(*align(1) FADT, laihost_scan("FACP", 0) orelse return lai.NULL); if(fadt.dsdt != 0) return @ptrCast(*c_void, get_sdt(fadt.dsdt).ptr); if(fadt.x_dsdt != 0) return @ptrCast(*c_void, get_sdt(fadt.x_dsdt).ptr); return lai.NULL; } } switch(rsdp.revision) { 0 => return impl_laihost_scan_root(u32, rsdp.rsdt_addr, name, index), 2 => return impl_laihost_scan_root(u64, rsdp.xsdt_addr, name, index), else => unreachable, } } export fn laihost_panic(err: [*:0]const u8) noreturn { has_lai_acpi = false; os.log("[LAI PANIC]: {s}\n", .{err}); @panic("LAI PANIC"); } export fn laihost_map(addr: usize, size: usize) ?*c_void { return os.platform.phys_ptr(*c_void).from_int(addr).get_uncached(); } export fn laihost_unmap(ptr: *c_void, size: usize) void { } var has_lai_acpi = false; pub fn init_acpi() !void { if(rsdp_phys == 0) rsdp_phys = locate_rsdp() orelse return; rsdp = os.platform.phys_ptr(*RSDP).from_int(rsdp_phys).get_writeback(); os.log("ACPI: Revision: {}\n", .{rsdp.revision}); switch(rsdp.revision) { 0 => parse_root_sdt(u32, rsdp.rsdt_addr), 2 => parse_root_sdt(u64, rsdp.xsdt_addr), else => return error.UnknownACPIRevision, } lai.lai_set_acpi_revision(rsdp.revision); lai.lai_create_namespace(); has_lai_acpi = true; }
src/platform/acpi.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day09.txt"); pub const DijkstraMap = struct { const Self = @This(); values: []u8, width: u32, allocator: *util.Allocator, pub fn initFromSerializedData(allocator: *util.Allocator, serialized_data: []const u8) !Self { var width: u32 = 0; const values = blk: { var values_list = util.List(u8).init(allocator); defer values_list.deinit(); var it = util.tokenize(u8, serialized_data, "\n"); // Parse each row while (it.next()) |row_data| { if (row_data.len == 0) continue; // Just in case we get an extra newline width = @intCast(u32, row_data.len); // For each row, parse the numbers (no in-row separator) for (row_data) |int_data| { if (int_data < '0' or int_data > '9') return error.InvalidInput; try values_list.append(int_data - '0'); } } break :blk values_list.toOwnedSlice(); }; errdefer allocator.free(values); // Return map return Self{ .values = values, .width = width, .allocator = allocator }; } /// Deallocates underlying representation of the map. pub fn deinit(self: *Self) void { self.allocator.free(self.values); } /// Finds the low-points of the map (as defined in the part 1 problem description), and /// returns them. pub fn findLowPoints(self: Self) ![]util.Point(i32) { var low_points = util.List(util.Point(i32)).init(self.allocator); defer low_points.deinit(); for (self.values) |val, idx| { const cur_point = util.Point(i32).fromIndex(idx, self.width); // Iterate over all neighbors, skipping ones off the edge of the map const is_low_point = for (util.cardinalNeighbors) |direction| { const neighbor = util.Point(i32).add(cur_point, direction); if (neighbor.x < 0 or neighbor.x >= self.width or neighbor.y < 0 or neighbor.y >= self.height()) continue; const neighborIndex = neighbor.toIndex(self.width); if (self.values[neighborIndex] <= val) break false; } else true; if (is_low_point) { try low_points.append(cur_point); } } return low_points.toOwnedSlice(); } /// Per part 1 problem description, risk level is the sum of (1 + height) for all points such /// that they have no lower neighbors. pub fn calculateRiskLevel(self: Self) !u32 { var sum: u32 = 0; const low_points = try self.findLowPoints(); defer self.allocator.free(low_points); for (low_points) |low_point| { sum += (1 + self.values[low_point.toIndex(self.width)]); } return sum; } /// Uses the map given to find all basins, as defined in the part 2 problem description. pub fn getBasins(self: Self) ![][]util.Point(i32) { var basins = util.List([]util.Point(i32)).init(self.allocator); defer basins.deinit(); // Find low points const low_points = try self.findLowPoints(); defer self.allocator.free(low_points); // For each low-point, flood outward toward high points, until we can't get to a higher // point. The resulting points are the basin associated with that low point. for (low_points) |low_point| { // Queue of points we still need to check var queue = util.List(util.Point(i32)).init(self.allocator); defer queue.deinit(); // Set of nodes we've already visited while finding this basin. Same as the result // however the set is unordered, and contains operations are much faster so the algorithm // can be more efficient. var visited = util.Map(util.Point(i32), void).init(self.allocator); defer visited.deinit(); // Set of nodes we've found in this basin. var current_basin = util.List(util.Point(i32)).init(self.allocator); defer current_basin.deinit(); // Queue first node in basin try queue.append(low_point); while (queue.items.len > 0) { // Skip nodes we've already visited const cur_point = queue.orderedRemove(0); if (visited.contains(cur_point)) continue; // Add current position to basin, and mark current position as visited try current_basin.append(cur_point); try visited.put(cur_point, {}); // Check neighbors, and if they aren't 9's and are greater, then add them to the // basin queue for (util.cardinalNeighbors) |direction| { const neighbor = util.Point(i32).add(cur_point, direction); if (neighbor.x < 0 or neighbor.x >= self.width or neighbor.y < 0 or neighbor.y >= self.height()) continue; const neighborIndex = neighbor.toIndex(self.width); if (self.values[neighborIndex] != 9 and self.values[neighborIndex] > self.values[cur_point.toIndex(self.width)] and !visited.contains(neighbor)) { try queue.append(neighbor); } } } // Add basin to list of basins we've found try basins.append(current_basin.toOwnedSlice()); } return basins.toOwnedSlice(); } pub fn height(self: Self) u32 { return @intCast(u32, self.values.len / self.width); } }; /// Find basins of the map as defined in the part 2 problem description, and return the sizes of the /// biggest 3 multiplied together. pub fn calculateTopThreeBasinValue(map: DijkstraMap) !u32 { // Find basins of the map var basins = try map.getBasins(); defer { for (basins) |basin| { util.gpa.free(basin); } util.gpa.free(basins); } // Sort such that the biggest basins are at the top util.sort([]util.Point(i32), basins, {}, comptime util.sliceLenDesc(util.Point(i32))); // Calculate product of top 3 basin sizes var product: u32 = 1; for (basins[0..3]) |basin| { product *= @intCast(u32, basin.len); } return product; } pub fn main() !void { defer { const leaks = util.gpa_impl.deinit(); std.debug.assert(!leaks); } var map = try DijkstraMap.initFromSerializedData(util.gpa, data); defer map.deinit(); // Part 1 const risk_lvl_pt1 = try map.calculateRiskLevel(); util.print("Part 1: Risk level of map is {d}\n", .{risk_lvl_pt1}); // Part 2 const top_3_basin_product_pt2 = try calculateTopThreeBasinValue(map); util.print("Part 2: Product of top 3 basin sizes is {d}\n", .{top_3_basin_product_pt2}); }
src/day09.zig
const std = @import("std"); const zfetch = @import("zfetch"); const json = @import("json"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const f = try std.fs.cwd().createFile("src/lib.zig", .{}); const w = f.writer(); { std.log.info("spdx", .{}); const val = try simple_fetch(alloc, "https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json"); try w.writeAll("// SPDX License Data generated from https://github.com/spdx/license-list-data\n"); try w.writeAll("//\n"); try w.print("// Last generated from version {s}\n", .{val.get("licenseListVersion").?.String}); try w.writeAll("//\n"); var licenses = val.get("licenses").?.Array; std.sort.sort(json.Value, licenses, {}, spdxlicenseLessThan); try w.writeAll("\n"); try w.writeAll("pub const spdx = &[_][]const u8{\n"); for (licenses) |lic| { try w.print(" \"{s}\",\n", .{ lic.get("licenseId").?.String, }); } try w.writeAll("};\n"); try w.writeAll("\n"); try w.writeAll("pub const osi = &[_][]const u8{\n"); for (licenses) |lic| { if (!lic.get("isOsiApproved").?.Bool) continue; try w.print(" \"{s}\",\n", .{lic.get("licenseId").?.String}); } try w.writeAll("};\n"); } { std.log.info("blueoak", .{}); const val = try simple_fetch(alloc, "https://blueoakcouncil.org/list.json"); try w.writeAll("\n"); try w.writeAll("// Blue Oak Council data generated from https://blueoakcouncil.org/list\n"); try w.writeAll("//\n"); try w.print("// Last generated from version {s}\n", .{val.get("version").?.String}); try w.writeAll("//\n"); try w.writeAll("\n"); try w.writeAll("pub const blueoak = struct {\n"); for (val.get("ratings").?.Array) |rating| { try w.print(" pub const {s} = &[_][]const u8{{\n", .{std.ascii.allocLowerString(alloc, rating.get("name").?.String)}); for (rating.get("licenses").?.Array) |lic| { try w.print(" \"{s}\",\n", .{ lic.get("id").?.String, }); } try w.print(" }};\n", .{}); } try w.writeAll("};\n"); } } pub fn simple_fetch(alloc: *std.mem.Allocator, url: []const u8) !json.Value { const req = try zfetch.Request.init(alloc, url, null); defer req.deinit(); try req.do(.GET, null, null); const r = req.reader(); const body_content = try r.readAllAlloc(alloc, std.math.maxInt(usize)); const val = try json.parse(alloc, body_content); return val; } fn spdxlicenseLessThan(context: void, lhs: json.Value, rhs: json.Value) bool { _ = context; const l = lhs.get("licenseId").?.String; const r = rhs.get("licenseId").?.String; return std.mem.lessThan(u8, l, r); }
generate.zig
const std = @import("std"); const zp = @import("zplay.zig"); const sdl = zp.deps.sdl; /// event definitions pub const WindowEvent = @import("event/WindowEvent.zig"); pub const KeyboardEvent = @import("event/KeyboardEvent.zig"); pub const TextInputEvent = @import("event/TextInputEvent.zig"); pub const MouseEvent = @import("event/MouseEvent.zig"); pub const GamepadEvent = @import("event/GamepadEvent.zig"); pub const QuitEvent = struct {}; /// generic event pub const Event = union(enum) { window_event: WindowEvent, keyboard_event: KeyboardEvent, text_input_event: TextInputEvent, mouse_event: MouseEvent, gamepad_event: GamepadEvent, quit_event: QuitEvent, pub fn init(e: sdl.Event) ?Event { return switch (e) { .window => |ee| Event{ .window_event = WindowEvent.init(ee), }, .key_up => |ee| Event{ .keyboard_event = KeyboardEvent.init(ee), }, .key_down => |ee| Event{ .keyboard_event = KeyboardEvent.init(ee), }, .text_input => |ee| Event{ .text_input_event = TextInputEvent.init(ee), }, .mouse_motion => |ee| Event{ .mouse_event = MouseEvent.fromMotionEvent(ee), }, .mouse_button_up => |ee| Event{ .mouse_event = MouseEvent.fromButtonEvent(ee), }, .mouse_button_down => |ee| Event{ .mouse_event = MouseEvent.fromButtonEvent(ee), }, .mouse_wheel => |ee| Event{ .mouse_event = MouseEvent.fromWheelEvent(ee), }, .controller_axis_motion => |ee| Event{ .gamepad_event = GamepadEvent.fromAxisEvent(ee), }, .controller_button_up => |ee| Event{ .gamepad_event = GamepadEvent.fromButtonEvent(ee), }, .controller_button_down => |ee| Event{ .gamepad_event = GamepadEvent.fromButtonEvent(ee), }, .controller_device_added => |ee| Event{ .gamepad_event = GamepadEvent.fromDeviceEvent(ee), }, .controller_device_removed => |ee| Event{ .gamepad_event = GamepadEvent.fromDeviceEvent(ee), }, .controller_device_remapped => |ee| Event{ .gamepad_event = GamepadEvent.fromDeviceEvent(ee), }, .quit => Event{ .quit_event = QuitEvent{}, }, // ignored other events else => null, }; } };
src/event.zig
const std = @import("std"); const testing = std.testing; pub fn RadixTree( comptime K: type, comptime V: type, comptime cmp: fn (K, K) bool, ) type { return struct { const Self = @This(); /// Represents a node within the tree /// Is possible a Leaf or else contains edges to /// other nodes const Node = struct { /// Possible leaf leaf: ?Leaf, /// Ignored prefix prefix: []const K, /// array of other edges /// Can only be non-zero in case of non-Leaf edges: []Edge, /// Adds a new `Edge` in the `edges` list of the `Node` fn addEdge(self: *Node, comptime e: Edge) void { comptime var edges: [self.edges.len + 1]Edge = undefined; std.mem.copy(Edge, &edges, self.edges ++ &[_]Edge{e}); self.edges = &edges; } /// Updates the edge's node that contains the given label with the new Node /// It's a Compiler error if the Edge does not yet exist fn updateEdge(self: *Node, comptime label: K, comptime node: *Node) void { const idx = blk: { var i: usize = 0; while (i < self.edges.len) : (i += 1) { if (cmp(self.edges[i].label, label)) break; } break :blk i; }; if (idx < self.edges.len and cmp(self.edges[idx].label, label)) { self.edges[idx].node = node; return; } @compileError("Edge with label '" ++ &[_]K{label} ++ "' does not exist\n"); } /// Retrieves a Node based on the given `label` /// Returns `null` if no Node exists with given label fn edge(self: *Node, label: K) ?*Node { @setEvalBranchQuota(100_000); const idx = blk: { var i: usize = 0; while (i < self.edges.len) : (i += 1) { if (cmp(self.edges[i].label, label)) break; } break :blk i; }; if (idx < self.edges.len and cmp(self.edges[idx].label, label)) return self.edges[idx].node; return null; } }; /// End node of the tree, contains the key and data component const Leaf = struct { key: []const K, data: V, }; /// Specific node within the tree, contains the label (character) /// and reference to another node const Edge = struct { label: K, node: *Node, }; /// Root node root: Node = .{ .leaf = null, .prefix = undefined, .edges = &[_]Edge{}, }, /// Total edges within the tree size: usize = 0, /// Inserts or updates a Node based on the `key` and `data` where /// `data` is of type `V` pub fn insert(self: *Self, comptime key: []const K, comptime data: V) ?V { var parent: *Node = undefined; var current: *Node = &self.root; var search: []const K = key; while (true) { // reached end of tree, create leaf if (search.len == 0) { // leaf exists? update data if (current.leaf) |*leaf| { const temp = leaf.data; leaf.data = data; return temp; } current.leaf = Leaf{ .key = key, .data = data, }; self.size += 1; return null; } parent = current; // get existing edge if it exists so we can update it // else create a new `Edge` if (current.edge(search[0])) |n| { current = n; } else { var leaf = Leaf{ .key = key, .data = data, }; var new_node = Node{ .leaf = leaf, .prefix = search, .edges = &[_]Edge{}, }; parent.addEdge(.{ .label = search[0], .node = &new_node, }); self.size += 1; return null; } // determine the length of the prefix const prefix = longestPrefix(K, search, current.prefix, cmp); if (prefix == current.prefix.len) { // basically we jump directly to creating/updating the leaf search = search[prefix..]; continue; } self.size += 1; // Split the node into 2 Edges var child = Node{ .leaf = null, .edges = &[_]Edge{}, .prefix = search[0..prefix], }; parent.updateEdge(search[0], &child); child.addEdge(.{ .label = current.prefix[prefix], .node = current, }); current.prefix = current.prefix[prefix..]; var leaf = Leaf{ .key = key, .data = data, }; search = search[prefix..]; if (search.len == 0) { child.leaf = leaf; return null; } var new_node = Node{ .leaf = leaf, .prefix = search, .edges = &[_]Edge{}, }; child.addEdge(.{ .label = search[0], .node = &new_node, }); return null; } } /// Searches for a result using the given `key` /// Returns null if key is not found /// Returns `V` if found pub fn get(self: *Self, key: []const K) ?V { var current = self.root; var search = key; while (search.len != 0) { current = (current.edge(search[0]) orelse return null).*; if (startsWith(K, search, current.prefix, cmp)) search = search[current.prefix.len..] else return null; } return if (current.leaf) |leaf| leaf.data else null; } /// Rather than searching for the exact match, it will return the longest prefix match /// i.e. If "hello" exists as leaf, and the given `key` is "helloworld", this will return /// `V` that belongs to prefix "hello". /// Returns null if nothing was found /// Returns `V` if prefix match was found pub fn getLongestPrefix(self: *Self, key: []const K) ?V { var last: ?V = null; var current = self.root; var search = key; while (true) { if (current.leaf) |leaf| last = leaf.data; if (search.len == 0) break; current = (current.edge(search[0]) orelse break).*; if (startsWith(K, search, current.prefix, cmp)) search = search[current.prefix.len..] else break; } return last; } }; } /// Finds the length of the longest prefix between 2 slices /// i.e.: /// lhs: foop /// rhs: foobar /// result: 2 -> matches foo as prefix fn longestPrefix( comptime T: type, comptime lhs: []const T, comptime rhs: []const T, comptime cmp: fn (T, T) bool, ) usize { const max = if (lhs.len < rhs.len) lhs.len else rhs.len; var i: usize = 0; return while (i < max) : (i += 1) { if (!cmp(lhs[i], rhs[i])) break i; } else i; } /// Generic startsWith function where user can provide the comparison function fn startsWith( comptime T: type, haystack: []const T, needle: []const T, cmp: fn (T, T) bool, ) bool { return if (needle.len > haystack.len) false else eql(T, haystack[0..needle.len], needle, cmp); } /// Compares two slices using a provided comparison function fn eql( comptime T: type, a: []const T, b: []const T, cmp: fn (T, T) bool, ) bool { if (a.len != b.len) return false; if (a.ptr == b.ptr) return true; for (a) |item, i| if (!cmp(item, b[i])) return false; return true; } /// compares two u8's which is used inside the /// StringRadixTree as comparison function fn stringCmp(lhs: u8, rhs: u8) bool { return lhs == rhs; } /// Creates a Radix Tree where the key is composed of a string, rather /// than a generic type. This function is solely for convencience. If a /// generic key is required, use the regular RadixTree. pub fn StringRadixTree(comptime T: type) type { return RadixTree(u8, T, stringCmp); } test "Insertion (u8)" { comptime var radix = StringRadixTree(u32){}; const a = comptime radix.insert("hi", 1); const b = comptime radix.insert("hi2", 2); const c = comptime radix.insert("hi2", 3); try testing.expectEqual(@as(usize, 2), radix.size); try testing.expectEqual(@as(?u32, null), a); try testing.expectEqual(@as(?u32, null), b); try testing.expectEqual(@as(?u32, 2), c); } test "Lookup value (u8)" { comptime var radix = StringRadixTree(u32){}; _ = comptime radix.insert("hello", 1); _ = comptime radix.insert("hello2", 2); _ = comptime radix.insert("aardvark", 3); _ = comptime radix.insert("aaardvark", 4); const result = radix.get("hello"); const result2 = radix.get("hello2"); const result3 = radix.get("foo"); _ = radix.get("aardvark").?; try testing.expectEqual(@as(?u32, 1), result); try testing.expectEqual(@as(?u32, 2), result2); try testing.expectEqual(@as(?u32, null), result3); } test "Lookup longest prefix (u8)" { comptime var radix = StringRadixTree(u32){}; _ = comptime radix.insert("foo", 1); _ = comptime radix.insert("bar", 2); _ = comptime radix.insert("foobar", 3); const result = radix.getLongestPrefix("foobark"); try testing.expectEqual(@as(?u32, 3), result); } fn testCmp(lhs: u16, rhs: u16) bool { return lhs == rhs; } test "Insertion (u16)" { comptime var radix = RadixTree(u16, u32, testCmp){}; const a = comptime radix.insert(&[_]u16{ 'h', 'i' }, 1); const b = comptime radix.insert(&[_]u16{ 'h', 'i', '2' }, 2); const c = comptime radix.insert(&[_]u16{ 'h', 'i', '2' }, 3); try testing.expectEqual(@as(usize, 2), radix.size); try testing.expectEqual(@as(?u32, null), a); try testing.expectEqual(@as(?u32, null), b); try testing.expectEqual(@as(?u32, 2), c); } test "Lookup value (u16)" { comptime var radix = RadixTree(u16, u32, testCmp){}; _ = comptime radix.insert(&[_]u16{ 'h', 'e', 'l', 'l', 'o' }, 1); _ = comptime radix.insert(&[_]u16{ 'h', 'e', 'l', 'l', 'o', '2' }, 2); _ = comptime radix.insert(&[_]u16{ 'a', 'a', 'r', 'd', 'v', 'a', 'r', 'k' }, 3); _ = comptime radix.insert(&[_]u16{ 'a', 'a', 'a', 'r', 'd', 'v', 'a', 'r', 'k' }, 4); const result = radix.get(&[_]u16{ 'h', 'e', 'l', 'l', 'o' }); const result2 = radix.get(&[_]u16{ 'h', 'e', 'l', 'l', 'o', '2' }); const result3 = radix.get(&[_]u16{ 'f', 'o', 'o' }); _ = radix.get(&[_]u16{ 'a', 'a', 'r', 'd', 'v', 'a', 'r', 'k' }).?; try testing.expectEqual(@as(?u32, 1), result); try testing.expectEqual(@as(?u32, 2), result2); try testing.expectEqual(@as(?u32, null), result3); } test "Lookup longest prefix (u16)" { comptime var radix = RadixTree(u16, u32, testCmp){}; _ = comptime radix.insert(&[_]u16{ 'f', 'o', 'o' }, 1); _ = comptime radix.insert(&[_]u16{ 'b', 'a', 'r' }, 2); _ = comptime radix.insert(&[_]u16{ 'f', 'o', 'o', 'b', 'a', 'r' }, 3); const result = radix.getLongestPrefix(&[_]u16{ 'f', 'o', 'o', 'b', 'a', 'r', 'k' }); try testing.expectEqual(@as(?u32, 3), result); } test "Struct as key" { const Key = struct { x: u32, y: u32, fn cmp(lhs: @This(), rhs: @This()) bool { return lhs.x == rhs.x and lhs.y == rhs.y; } }; comptime var radix = RadixTree(Key, u32, Key.cmp){}; _ = comptime radix.insert(&[_]Key{ .{ .x = 1, .y = 1 }, .{ .x = 2, .y = 2 }, }, 1); _ = comptime radix.insert(&[_]Key{ .{ .x = 5, .y = 5 }, .{ .x = 6, .y = 6 }, }, 2); const result = radix.get(&[_]Key{ .{ .x = 5, .y = 5 }, .{ .x = 6, .y = 6 }, }); try testing.expectEqual(@as(?u32, 2), result); } test "'get' ignores partial results" { comptime var radix = StringRadixTree(u32){}; _ = comptime radix.insert("await", 0); _ = comptime radix.insert("awaitable", 1); _ = comptime radix.insert("async", 2); //Partial results should fail try testing.expect(radix.get("aws") == null); try testing.expect(radix.get("asnc") == null); try testing.expect(radix.get("asyn") == null); //Full results should be found try testing.expect(radix.get("await") == @as(u32, 0)); try testing.expect(radix.get("awaitable") == @as(u32, 1)); try testing.expect(radix.get("async") == @as(u32, 2)); }
src/main.zig
pub const XINPUT_DEVTYPE_GAMEPAD = @as(u32, 1); pub const XINPUT_DEVSUBTYPE_GAMEPAD = @as(u32, 1); pub const XINPUT_DEVSUBTYPE_UNKNOWN = @as(u32, 0); pub const XINPUT_DEVSUBTYPE_WHEEL = @as(u32, 2); pub const XINPUT_DEVSUBTYPE_ARCADE_STICK = @as(u32, 3); pub const XINPUT_DEVSUBTYPE_FLIGHT_STICK = @as(u32, 4); pub const XINPUT_DEVSUBTYPE_DANCE_PAD = @as(u32, 5); pub const XINPUT_DEVSUBTYPE_GUITAR = @as(u32, 6); pub const XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE = @as(u32, 7); pub const XINPUT_DEVSUBTYPE_DRUM_KIT = @as(u32, 8); pub const XINPUT_DEVSUBTYPE_GUITAR_BASS = @as(u32, 11); pub const XINPUT_DEVSUBTYPE_ARCADE_PAD = @as(u32, 19); pub const XINPUT_CAPS_VOICE_SUPPORTED = @as(u32, 4); pub const XINPUT_CAPS_FFB_SUPPORTED = @as(u32, 1); pub const XINPUT_CAPS_WIRELESS = @as(u32, 2); pub const XINPUT_CAPS_PMD_SUPPORTED = @as(u32, 8); pub const XINPUT_CAPS_NO_NAVIGATION = @as(u32, 16); pub const XINPUT_GAMEPAD_DPAD_UP = @as(u32, 1); pub const XINPUT_GAMEPAD_DPAD_DOWN = @as(u32, 2); pub const XINPUT_GAMEPAD_DPAD_LEFT = @as(u32, 4); pub const XINPUT_GAMEPAD_DPAD_RIGHT = @as(u32, 8); pub const XINPUT_GAMEPAD_START = @as(u32, 16); pub const XINPUT_GAMEPAD_BACK = @as(u32, 32); pub const XINPUT_GAMEPAD_LEFT_THUMB = @as(u32, 64); pub const XINPUT_GAMEPAD_RIGHT_THUMB = @as(u32, 128); pub const XINPUT_GAMEPAD_LEFT_SHOULDER = @as(u32, 256); pub const XINPUT_GAMEPAD_RIGHT_SHOULDER = @as(u32, 512); pub const XINPUT_GAMEPAD_A = @as(u32, 4096); pub const XINPUT_GAMEPAD_B = @as(u32, 8192); pub const XINPUT_GAMEPAD_X = @as(u32, 16384); pub const XINPUT_GAMEPAD_Y = @as(u32, 32768); pub const XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE = @as(u32, 7849); pub const XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE = @as(u32, 8689); pub const XINPUT_GAMEPAD_TRIGGER_THRESHOLD = @as(u32, 30); pub const XINPUT_FLAG_GAMEPAD = @as(u32, 1); pub const BATTERY_DEVTYPE_GAMEPAD = @as(u32, 0); pub const BATTERY_DEVTYPE_HEADSET = @as(u32, 1); pub const BATTERY_TYPE_DISCONNECTED = @as(u32, 0); pub const BATTERY_TYPE_WIRED = @as(u32, 1); pub const BATTERY_TYPE_ALKALINE = @as(u32, 2); pub const BATTERY_TYPE_NIMH = @as(u32, 3); pub const BATTERY_TYPE_UNKNOWN = @as(u32, 255); pub const BATTERY_LEVEL_EMPTY = @as(u32, 0); pub const BATTERY_LEVEL_LOW = @as(u32, 1); pub const BATTERY_LEVEL_MEDIUM = @as(u32, 2); pub const BATTERY_LEVEL_FULL = @as(u32, 3); pub const XUSER_MAX_COUNT = @as(u32, 4); pub const XUSER_INDEX_ANY = @as(u32, 255); pub const XINPUT_KEYSTROKE_KEYDOWN = @as(u32, 1); pub const XINPUT_KEYSTROKE_KEYUP = @as(u32, 2); pub const XINPUT_KEYSTROKE_REPEAT = @as(u32, 4); //-------------------------------------------------------------------------------- // Section: Types (7) //-------------------------------------------------------------------------------- pub const XINPUT_VIRTUAL_KEY = enum(u16) { A = 22528, B = 22529, X = 22530, Y = 22531, RSHOULDER = 22532, LSHOULDER = 22533, LTRIGGER = 22534, RTRIGGER = 22535, DPAD_UP = 22544, DPAD_DOWN = 22545, DPAD_LEFT = 22546, DPAD_RIGHT = 22547, START = 22548, BACK = 22549, LTHUMB_PRESS = 22550, RTHUMB_PRESS = 22551, LTHUMB_UP = 22560, LTHUMB_DOWN = 22561, LTHUMB_RIGHT = 22562, LTHUMB_LEFT = 22563, LTHUMB_UPLEFT = 22564, LTHUMB_UPRIGHT = 22565, LTHUMB_DOWNRIGHT = 22566, LTHUMB_DOWNLEFT = 22567, RTHUMB_UP = 22576, RTHUMB_DOWN = 22577, RTHUMB_RIGHT = 22578, RTHUMB_LEFT = 22579, RTHUMB_UPLEFT = 22580, RTHUMB_UPRIGHT = 22581, RTHUMB_DOWNRIGHT = 22582, RTHUMB_DOWNLEFT = 22583, }; pub const VK_PAD_A = XINPUT_VIRTUAL_KEY.A; pub const VK_PAD_B = XINPUT_VIRTUAL_KEY.B; pub const VK_PAD_X = XINPUT_VIRTUAL_KEY.X; pub const VK_PAD_Y = XINPUT_VIRTUAL_KEY.Y; pub const VK_PAD_RSHOULDER = XINPUT_VIRTUAL_KEY.RSHOULDER; pub const VK_PAD_LSHOULDER = XINPUT_VIRTUAL_KEY.LSHOULDER; pub const VK_PAD_LTRIGGER = XINPUT_VIRTUAL_KEY.LTRIGGER; pub const VK_PAD_RTRIGGER = XINPUT_VIRTUAL_KEY.RTRIGGER; pub const VK_PAD_DPAD_UP = XINPUT_VIRTUAL_KEY.DPAD_UP; pub const VK_PAD_DPAD_DOWN = XINPUT_VIRTUAL_KEY.DPAD_DOWN; pub const VK_PAD_DPAD_LEFT = XINPUT_VIRTUAL_KEY.DPAD_LEFT; pub const VK_PAD_DPAD_RIGHT = XINPUT_VIRTUAL_KEY.DPAD_RIGHT; pub const VK_PAD_START = XINPUT_VIRTUAL_KEY.START; pub const VK_PAD_BACK = XINPUT_VIRTUAL_KEY.BACK; pub const VK_PAD_LTHUMB_PRESS = XINPUT_VIRTUAL_KEY.LTHUMB_PRESS; pub const VK_PAD_RTHUMB_PRESS = XINPUT_VIRTUAL_KEY.RTHUMB_PRESS; pub const VK_PAD_LTHUMB_UP = XINPUT_VIRTUAL_KEY.LTHUMB_UP; pub const VK_PAD_LTHUMB_DOWN = XINPUT_VIRTUAL_KEY.LTHUMB_DOWN; pub const VK_PAD_LTHUMB_RIGHT = XINPUT_VIRTUAL_KEY.LTHUMB_RIGHT; pub const VK_PAD_LTHUMB_LEFT = XINPUT_VIRTUAL_KEY.LTHUMB_LEFT; pub const VK_PAD_LTHUMB_UPLEFT = XINPUT_VIRTUAL_KEY.LTHUMB_UPLEFT; pub const VK_PAD_LTHUMB_UPRIGHT = XINPUT_VIRTUAL_KEY.LTHUMB_UPRIGHT; pub const VK_PAD_LTHUMB_DOWNRIGHT = XINPUT_VIRTUAL_KEY.LTHUMB_DOWNRIGHT; pub const VK_PAD_LTHUMB_DOWNLEFT = XINPUT_VIRTUAL_KEY.LTHUMB_DOWNLEFT; pub const VK_PAD_RTHUMB_UP = XINPUT_VIRTUAL_KEY.RTHUMB_UP; pub const VK_PAD_RTHUMB_DOWN = XINPUT_VIRTUAL_KEY.RTHUMB_DOWN; pub const VK_PAD_RTHUMB_RIGHT = XINPUT_VIRTUAL_KEY.RTHUMB_RIGHT; pub const VK_PAD_RTHUMB_LEFT = XINPUT_VIRTUAL_KEY.RTHUMB_LEFT; pub const VK_PAD_RTHUMB_UPLEFT = XINPUT_VIRTUAL_KEY.RTHUMB_UPLEFT; pub const VK_PAD_RTHUMB_UPRIGHT = XINPUT_VIRTUAL_KEY.RTHUMB_UPRIGHT; pub const VK_PAD_RTHUMB_DOWNRIGHT = XINPUT_VIRTUAL_KEY.RTHUMB_DOWNRIGHT; pub const VK_PAD_RTHUMB_DOWNLEFT = XINPUT_VIRTUAL_KEY.RTHUMB_DOWNLEFT; pub const XINPUT_GAMEPAD = extern struct { wButtons: u16, bLeftTrigger: u8, bRightTrigger: u8, sThumbLX: i16, sThumbLY: i16, sThumbRX: i16, sThumbRY: i16, }; pub const XINPUT_STATE = extern struct { dwPacketNumber: u32, Gamepad: XINPUT_GAMEPAD, }; pub const XINPUT_VIBRATION = extern struct { wLeftMotorSpeed: u16, wRightMotorSpeed: u16, }; pub const XINPUT_CAPABILITIES = extern struct { Type: u8, SubType: u8, Flags: u16, Gamepad: XINPUT_GAMEPAD, Vibration: XINPUT_VIBRATION, }; pub const XINPUT_BATTERY_INFORMATION = extern struct { BatteryType: u8, BatteryLevel: u8, }; pub const XINPUT_KEYSTROKE = extern struct { VirtualKey: XINPUT_VIRTUAL_KEY, Unicode: u16, Flags: u16, UserIndex: u8, HidCode: u8, }; //-------------------------------------------------------------------------------- // Section: Functions (7) //-------------------------------------------------------------------------------- pub extern "XINPUTUAP" fn XInputGetState( dwUserIndex: u32, pState: ?*XINPUT_STATE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "XINPUTUAP" fn XInputSetState( dwUserIndex: u32, pVibration: ?*XINPUT_VIBRATION, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "XINPUTUAP" fn XInputGetCapabilities( dwUserIndex: u32, dwFlags: u32, pCapabilities: ?*XINPUT_CAPABILITIES, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "XINPUTUAP" fn XInputEnable( enable: BOOL, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "XINPUTUAP" fn XInputGetAudioDeviceIds( dwUserIndex: u32, pRenderDeviceId: ?[*:0]u16, pRenderCount: ?*u32, pCaptureDeviceId: ?[*:0]u16, pCaptureCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "XINPUTUAP" fn XInputGetBatteryInformation( dwUserIndex: u32, devType: u8, pBatteryInformation: ?*XINPUT_BATTERY_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "XINPUTUAP" fn XInputGetKeystroke( dwUserIndex: u32, dwReserved: u32, pKeystroke: ?*XINPUT_KEYSTROKE, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (1) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/ui/xinput.zig
const std = @import("std"); const u = @import("../util.zig"); const Expr = @import("../Expr.zig"); const IR = @import("../IR.zig"); const Wasm = @import("../Wasm.zig"); const Opt = struct { ids: bool = false, }; pub fn emit(m: IR.Module, gpa: std.mem.Allocator, comptime opt: Opt) !Expr.Root { var n_top: usize = 1; n_top += m.funcs.len; n_top += @boolToInt(m.memory != null); n_top += m.datas.len; var arena = std.heap.ArenaAllocator.init(gpa); const allocator = arena.allocator(); var top = try Arr.init(n_top, allocator); top.append(keyword("module")); for (m.funcs) |func| { var n_arr = 1 + func.exports.len; n_arr += @boolToInt(opt.ids and func.id != null); n_arr += @boolToInt(func.type.params.len > 0); n_arr += @boolToInt(func.type.results.len > 0); n_arr += switch (func.body) { .import => @as(usize, 1), .code => |code| blk: { var n: usize = 0; var reader = Wasm.Reader.init(code.bytes); const nLocals = try reader.uleb32(); if (nLocals > 0) { try reader.it.seekBy(nLocals * 2); n += 1; } var depth: usize = 1; while (true) { const inst = try reader.op(&depth); if (depth == 0) break; n += 1 + @as(usize, switch (inst.arg) { .none => 0, .int, .float, .idx => 1, .table, .xy => 2, .memarg => |arg| @as(usize, 1) + @boolToInt(arg.offset != 0), .blocktype => |b| @boolToInt(b != .empty), }); } if (!reader.finished()) return error.NoFuncEnd; break :blk n; }, }; var arr = try Arr.init(n_arr, allocator); arr.append(keyword("func")); if (opt.ids) if (func.id) |v| arr.append(try id(v, allocator)); for (func.exports) |expor| arr.append(try exportAbrev(expor, allocator)); switch (func.body) { .import => |impor| arr.append(try importAbbrev(impor, allocator)), .code => {}, } if (func.type.params.len > 0) arr.append(try valtypes("param", func.type.params, allocator)); if (func.type.results.len > 0) arr.append(try valtypes("result", func.type.results, allocator)); switch (func.body) { .import => {}, .code => |code| { //TODO: relocate var reader = Wasm.Reader.init(code.bytes); var nLocals = try reader.uleb32(); if (nLocals > 0) { var lcs = try Arr.init(2, allocator); lcs.append(keyword("local")); while (nLocals > 0) : (nLocals -= 1) { const n = try reader.uleb32(); const typ = try reader.valtype(); try lcs.inner.appendNTimes(allocator, keyword(@tagName(typ)), n); } arr.append(lcs.finish()); } var depth: usize = 1; while (true) { const inst = try reader.op(&depth); if (depth == 0) break; arr.append(try opToKeyword(inst.op, allocator)); switch (inst.arg) { .none => {}, .int => |i| arr.append(try int(i, allocator)), .idx => |i| arr.append(try int(i, allocator)), .float => |f| arr.append(try float(f, allocator)), .memarg => |arg| { if (arg.offset != 0) arr.append(try prefixedInt(arg.offset, "offset=", allocator)); arr.append(try prefixedInt(@as(i64, 1) << @truncate(u6, arg.align_), "align=", allocator)); }, .blocktype => |b| switch (b) { .empty => {}, .valtype => |v| { var val = try Arr.init(2, allocator); val.append(keyword("result")); val.append(keyword(@tagName(v))); arr.append(val.finish()); }, .idx => |v| { std.debug.print("{}", .{v}); //FIXME: func types unreachable; }, }, .table => |t| { var lst = try Arr.init(t.n, allocator); var rd = Wasm.Reader.init(t.buf); var n: usize = 0; while (n < t.n) : (n += 1) lst.append(try int(try rd.uleb32(), allocator)); arr.append(lst.finish()); arr.append(try int(try rd.uleb32(), allocator)); std.debug.assert(rd.finished()); }, .xy => |xy| for (xy) |v| arr.append(try int(v, allocator)), } } std.debug.assert(reader.finished()); }, } top.append(arr.finish()); } if (m.memory) |mem| { var n_arr: usize = 2 + mem.exports.len; n_arr += @boolToInt(mem.size.max != null); n_arr += @boolToInt(mem.import != null); var arr = try Arr.init(n_arr, allocator); arr.append(keyword("memory")); for (mem.exports) |expor| arr.append(try exportAbrev(expor, allocator)); if (mem.import) |impor| arr.append(try importAbbrev(impor, allocator)); arr.append(try int(mem.size.min, allocator)); if (mem.size.max) |max| arr.append(try int(max, allocator)); top.append(arr.finish()); } for (m.datas) |data| { const n_arr = @as(usize, switch (data.body) { .active => 2, .passive => 1, }) + 1; var arr = try Arr.init(n_arr, allocator); arr.append(keyword("data")); const content = switch (data.body) { .active => |act| blk: { std.debug.assert(act.mem == 0); arr.append(try constExpr(act.offset, allocator)); break :blk act.content; }, .passive => |pas| pas, }; arr.append(try string(content, allocator)); top.append(arr.finish()); } return Expr.Root{ .val = top.finish(), .arena = arena }; } inline fn list(content: []Expr) Expr { return .{ .val = .{ .list = content } }; } inline fn keyword(str: u.Txt) Expr { return .{ .val = .{ .keyword = str } }; } fn StrExpr(comptime field: u.Txt) fn (u.Txt, std.mem.Allocator) std.mem.Allocator.Error!Expr { return struct { fn f(str: u.Txt, allocator: std.mem.Allocator) !Expr { return Expr{ .val = @unionInit(Expr.Val, field, try allocator.dupe(u8, str)) }; } }.f; } const string = StrExpr("string"); const id = StrExpr("id"); const Arr = struct { inner: std.ArrayListUnmanaged(Expr), fn init(size: usize, allocator: std.mem.Allocator) !Arr { return Arr{ .inner = try std.ArrayListUnmanaged(Expr).initCapacity(allocator, size) }; } fn appendSlice(self: *Arr, exprs: []const Expr) void { self.inner.appendSliceAssumeCapacity(exprs); } fn append(self: *Arr, expr: Expr) void { self.inner.appendAssumeCapacity(expr); } inline fn finish(self: Arr) Expr { return list(self.inner.items); } }; fn exportAbrev(expor: IR.ExportName, allocator: std.mem.Allocator) !Expr { const exp = try allocator.alloc(Expr, 2); exp[0] = keyword("export"); exp[1] = try string(expor, allocator); return list(exp); } fn importAbbrev(impor: IR.ImportName, allocator: std.mem.Allocator) !Expr { const imp = try allocator.alloc(Expr, 3); imp[0] = keyword("import"); imp[1] = try string(impor.module, allocator); imp[2] = try string(impor.name, allocator); return list(imp); } fn valtypes(comptime key: u.Txt, of: []const IR.Sigtype, allocator: std.mem.Allocator) !Expr { const typ = try allocator.alloc(Expr, 1 + of.len); typ[0] = keyword(key); for (of) |param, i| { typ[i + 1] = keyword(@tagName(param.lower())); } return list(typ); } fn prefixedInt(v: i64, comptime prefix: u.Txt, allocator: std.mem.Allocator) !Expr { //MAYBE: deduplicated var buf: [prefix.len + 20]u8 = undefined; std.mem.copy(u8, &buf, prefix); const len = std.fmt.formatIntBuf(buf[prefix.len..], v, 10, .lower, .{}); return StrExpr("keyword")(buf[0 .. prefix.len + len], allocator); } fn int(v: i64, allocator: std.mem.Allocator) !Expr { return prefixedInt(v, "", allocator); } fn float(v: f64, allocator: std.mem.Allocator) !Expr { //FIXME: check for spec compliance var counter = std.io.countingWriter(std.io.null_writer); try std.fmt.formatFloatScientific(v, .{}, counter.writer()); const buf = try allocator.alloc(u8, counter.bytes_written); var fixed = std.io.fixedBufferStream(buf); try std.fmt.formatFloatScientific(v, .{}, fixed.writer()); return keyword(fixed.getWritten()); } fn constExpr(expr: IR.InitExpr, allocator: std.mem.Allocator) !Expr { var arr = try Arr.init(2, allocator); arr.append(try opToKeyword(IR.initExpr(expr), allocator)); arr.append(switch (expr) { .i32_const => |i| try int(i, allocator), .i64_const => |i| try int(i, allocator), .f32_const => |f| try float(f, allocator), .f64_const => |f| try float(f, allocator), .global_get => |i| try int(i, allocator), }); return arr.finish(); } inline fn opToKeyword(op: IR.Code.Op, allocator: std.mem.Allocator) std.mem.Allocator.Error!Expr { const tag = @tagName(op); if (std.mem.indexOfScalar(u8, tag, '_')) |i| if (!std.mem.startsWith(u8, tag, "br")) { var buf: [32]u8 = undefined; const slice = buf[0..tag.len]; std.mem.copy(u8, slice, tag); slice[i] = '.'; return StrExpr("keyword")(slice, allocator); }; return keyword(tag); }
src/Wat/Emit.zig
const panic = @import("std").debug.panic; pub const c = @import("c.zig"); pub const event = @import("sdl/event.zig"); pub const hint = @import("sdl/hint.zig"); // Errors pub const SdlError = error{ WindowCreation, RendererCreation, GlContextCreation, NoOpenGlContext, NoOpenGlAttachedToWindow, }; pub const getError = c.SDL_GetError; // Hints pub const HintPriority = enum { Default, Normal, Override, pub fn toC(self: HintPriority) c.SDL_HintPriority { return switch(self) { .Default => c.SDL_HintPriority.SDL_HINT_DEFAULT, .Normal => c.SDL_HintPriority.SDL_HINT_NORMAL, .Override => c.SDL_HintPriority.SDL_HINT_OVERRIDE, }; } }; pub fn setHintWithPriority(name: [*c]const u8, value: [*c]const u8, priority: HintPriority) bool { switch(c.SDL_SetHintWithPriority(name, value, priority.toC())) { .SDL_FALSE => return false, .SDL_TRUE => return true, else => unreachable, } } // Type Definitions pub const Window = c.SDL_Window; pub const GlContext = c.SDL_GLContext; pub const Event = c.SDL_Event; pub const Renderer = c.SDL_Renderer; // Init Variables pub const init_timer = c.SDL_INIT_TIMER; pub const init_audio = c.SDL_INIT_AUDIO; pub const init_video = c.SDL_INIT_VIDEO; pub const init_joystick = c.SDL_INIT_JOYSTICK; pub const init_haptic = c.SDL_INIT_HAPTIC; pub const init_gamecontroller = c.SDL_INIT_GAMECONTROLLER; pub const init_events = c.SDL_INIT_EVENTS; pub const init_everything = c.SDL_INIT_EVERYTHING; pub const init_noparachute = c.SDL_INIT_NOPARACHUTE; // Function pub const init = c.SDL_Init; pub const quit = c.SDL_Quit; pub const delay = c.SDL_Delay; pub const pollEvent = c.SDL_PollEvent; // Window Flags pub const window_position_centered = c.SDL_WINDOWPOS_CENTERED; pub const window_position_undefined = c.SDL_WINDOWPOS_UNDEFINED; pub const window_fullscreen = c.SDL_WINDOW_FULLSCREEN; pub const window_fullscreen_desktop = c.SDL_WINDOW_FULLSCREEN_DESKTOP; pub const window_opengl = c.SDL_WINDOW_OPENGL; pub const window_shown = c.SDL_WINDOW_SHOWN; pub const window_hidden = c.SDL_WINDOW_HIDDEN; pub const window_borderless = c.SDL_WINDOW_BORDERLESS; pub const window_resizable = c.SDL_WINDOW_RESIZABLE; pub const window_minimized = c.SDL_WINDOW_MINIMIZED; pub const window_maximized = c.SDL_WINDOW_MAXIMIZED; pub const window_input_grabbed = c.SDL_WINDOW_INPUT_GRABBED; pub const window_input_focus = c.SDL_WINDOW_INPUT_FOCUS; pub const window_mouse_focus = c.SDL_WINDOW_MOUSE_FOCUS; pub const window_foreign = c.SDL_WINDOW_FOREIGN; // OpenGL Attribute Enum pub const gl_red_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_RED_SIZE); pub const gl_green_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_GREEN_SIZE); pub const gl_blue_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_BLUE_SIZE); pub const gl_alpha_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_ALPHA_SIZE); pub const gl_buffer_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_BUFFER_SIZE); pub const gl_doublebuffer = @intToEnum(c.SDL_GLattr, c.SDL_GL_DOUBLEBUFFER); pub const gl_depth_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_DEPTH_SIZE); pub const gl_stencil_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_STENCIL_SIZE); pub const gl_accum_red_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_ACCUM_RED_SIZE); pub const gl_accum_green_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_ACCUM_GREEN_SIZE); pub const gl_accum_blue_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_ACCUM_BLUE_SIZE); pub const gl_accum_alpha_size = @intToEnum(c.SDL_GLattr, c.SDL_GL_ACCUM_ALPHA_SIZE); pub const gl_stereo = @intToEnum(c.SDL_GLattr, c.SDL_GL_STEREO); pub const gl_multisamplebuffers = @intToEnum(c.SDL_GLattr, c.SDL_GL_MULTISAMPLEBUFFERS); pub const gl_multisamplesamples = @intToEnum(c.SDL_GLattr, c.SDL_GL_MULTISAMPLESAMPLES); pub const gl_accelerated_visual = @intToEnum(c.SDL_GLattr, c.SDL_GL_ACCELERATED_VISUAL); pub const gl_retained_backing = @intToEnum(c.SDL_GLattr, c.SDL_GL_RETAINED_BACKING); pub const gl_context_major_version = @intToEnum(c.SDL_GLattr, c.SDL_GL_CONTEXT_MAJOR_VERSION); pub const gl_context_minor_version = @intToEnum(c.SDL_GLattr, c.SDL_GL_CONTEXT_MINOR_VERSION); pub const gl_context_flags = @intToEnum(c.SDL_GLattr, c.SDL_GL_CONTEXT_FLAGS); pub const gl_context_profile_mask = @intToEnum(c.SDL_GLattr, c.SDL_GL_CONTEXT_PROFILE_MASK); pub const gl_share_with_current_context = @intToEnum(c.SDL_GLattr, c.SDL_GL_SHARE_WITH_CURRENT_CONTEXT); pub const gl_context_profile_core = c.SDL_GL_CONTEXT_PROFILE_CORE; pub const gl_context_profile_compatibility = c.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY; pub const gl_context_profile_es = c.SDL_GL_CONTEXT_PROFILE_ES; // OpenGL Functions pub const BindGlTexture = c.SDL_GL_BindTexture; pub fn CreateGlContext(window: *Window) !GlContext { if (c.SDL_GL_CreateContext(window)) |context| { return context; } return SdlError.GlContextCreation; } pub const DeleteGlContext = c.SDL_GL_DeleteContext; pub const ExtensionGlSupported = c.SDL_GL_ExtensionSupported; pub const GetGlAttribute = c.SDL_GL_GetAttribute; pub fn GetGlCurrentContext() *GlContext { if (c.SDL_GL_GetCurrentContext()) |context| { return context; } return SdlError.NoOpenGlContext; } pub fn GetGlCurrentWindow() *GlContext { if (c.SDL_GL_GetCurrentWindow()) |window| { return window; } return SdlError.NoOpenGlAttachedToWindow; } pub const getGlDrawableSize = c.SDL_GL_GetDrawableSize; pub const getGlProcAddress = c.SDL_GL_GetProcAddress; pub const getGlSwapInterval = c.SDL_GL_GetSwapInterval; pub const loadGlLibrary = c.SDL_GL_LoadLibrary; pub const makeGlCurrent = c.SDL_GL_MakeCurrent; pub const resetGlAttributes = c.SDL_GL_ResetAttributes; pub const setGlAttribute = c.SDL_GL_SetAttribute; pub const setGlSwapInterval = c.SDL_GL_SetSwapInterval; pub const swapGlWindow = c.SDL_GL_SwapWindow; pub const unbindGlTexture = c.SDL_GL_UnbindTexture; pub const unloadGlLibrary = c.SDL_GL_UnloadLibrary; // Window Creation Functions pub fn createWindow(title: [*c]const u8, x: i32, y: i32, w: i32, h: i32, flags: u32) !*Window { if (c.SDL_CreateWindow(title, x, y, w, h, flags)) |window| { return window; } return SdlError.WindowCreation; } pub const destroyWindow = c.SDL_DestroyWindow; pub const getTicks = c.SDL_GetTicks; // Renderer Creation Functions pub const renderer_software = c.SDL_RENDERER_SOFTWARE; pub const renderer_accelerated = c.SDL_RENDERER_ACCELERATED; pub const renderer_presentvsync = c.SDL_RENDERER_PRESENTVSYNC; pub const renderer_targettexture = c.SDL_RENDERER_TARGETTEXTURE; pub fn createRenderer(window: *Window, index: c_int, flags: c_uint) !*Renderer { if (c.SDL_CreateRenderer(window, index, flags)) |renderer| { return renderer; } return SdlError.RendererCreation; } pub const destroyRenderer = c.SDL_DestroyRenderer; pub inline fn ASSERT_OK(result: var) void { if (result == 0) return; panic("SDL Error: {}\n", .{ getError()}); } pub const getPerformanceCounter = c.SDL_GetPerformanceCounter; pub const getPerformanceFrequency = c.SDL_GetPerformanceFrequency;
sdl.zig
const std = @import("std"); const ArrayList = std.ArrayList; const fmt = std.fmt; const io = std.io; const mem = std.mem; const Collection = @import("Collection.zig"); const Record = @import("record.zig").Record; const ascii = @import("ascii.zig"); const UcdGenerator = struct { allocator: *mem.Allocator, pub fn new(allocator: *mem.Allocator) UcdGenerator { return UcdGenerator{ .allocator = allocator, }; } const Self = @This(); // Files with the code point type in field index 1. fn processF1(self: *Self, path: []const u8) !void { // Setup input. var file = try std.fs.cwd().openFile(path, .{}); defer file.close(); var buf_reader = io.bufferedReader(file.reader()); var input_stream = buf_reader.reader(); var collections = ArrayList(Collection).init(self.allocator); defer { for (collections.items) |*collection| { collection.deinit(); } collections.deinit(); } var records = ArrayList(Record).init(self.allocator); defer records.deinit(); var al = std.heap.ArenaAllocator.init(self.allocator); defer al.deinit(); var arena_allocator = &al.allocator; var kind: ?[]const u8 = null; // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip comments or empty lines. if (line.len == 0 or line[0] == '#') continue; // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { // Construct record. var record: Record = undefined; if (mem.indexOf(u8, field, "..")) |dots| { // Ranges. const r_lo = try fmt.parseInt(u21, field[0..dots], 16); const r_hi = try fmt.parseInt(u21, field[dots + 2 ..], 16); record = .{ .range = .{ .lo = r_lo, .hi = r_hi } }; } else { const code_point = try fmt.parseInt(u21, field, 16); record = .{ .single = code_point }; } // Add this record. try records.append(record); } else if (field_index == 1) { // Record kind. // Possible comment at end. var clean_field = if (mem.indexOf(u8, field, "#")) |octo| blk: { var tmp = field[0..octo]; break :blk mem.trimRight(u8, tmp, " "); } else field; // Check if new collection started. if (kind) |k| { if (!mem.eql(u8, k, clean_field)) { // New collection for new record kind. // Last record belongs to next collection. const one_past = records.pop(); // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } // Add new collection. try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); // Update kind. kind = try arena_allocator.dupe(u8, clean_field); // Add first record of new collection. try records.append(one_past); } } else { // kind is null, initialize it. kind = try arena_allocator.dupe(u8, clean_field); } } else { // Ignore other fields. continue; } } } // Last collection. if (kind) |k| { // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); } // Write out files. var dir = std.fs.path.basename(path); const dot = mem.lastIndexOf(u8, dir, "."); if (dot) |d| dir = dir[0..d]; for (collections.items) |*collection| { try collection.writeFile(dir); } } // data/ucd/extracted/DerivedEastAsianWidth.txt fn processAsianWidth(self: *Self) !void { // Setup input. var file = try std.fs.cwd().openFile("data/ucd/extracted/DerivedEastAsianWidth.txt", .{}); defer file.close(); var buf_reader = io.bufferedReader(file.reader()); var input_stream = buf_reader.reader(); var collections = ArrayList(Collection).init(self.allocator); defer { for (collections.items) |*collection| { collection.deinit(); } collections.deinit(); } var records = ArrayList(Record).init(self.allocator); defer records.deinit(); var al = std.heap.ArenaAllocator.init(self.allocator); defer al.deinit(); var arena_allocator = &al.allocator; var kind: ?[]const u8 = null; // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip empty lines. if (line.len == 0) continue; if (mem.indexOf(u8, line, "East_Asian_Width=")) |_| { // Record kind. const equals = mem.indexOf(u8, line, "=").?; const current_kind = mem.trim(u8, line[equals + 1 ..], " "); // Check if new collection started. if (kind) |k| { // New collection for new record kind. if (!mem.eql(u8, k, current_kind)) { // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); // Update kind. kind = try arena_allocator.dupe(u8, current_kind); } } else { // kind is null, initialize it. kind = try arena_allocator.dupe(u8, current_kind); } continue; } else if (line[0] == '#') { // Skip comments. continue; } // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { // Construct record. var record: Record = undefined; // Ranges. if (mem.indexOf(u8, field, "..")) |dots| { const r_lo = try fmt.parseInt(u21, field[0..dots], 16); const r_hi = try fmt.parseInt(u21, field[dots + 2 ..], 16); record = .{ .range = .{ .lo = r_lo, .hi = r_hi } }; } else { const code_point = try fmt.parseInt(u21, field, 16); record = .{ .single = code_point }; } // Add this record. try records.append(record); } else { continue; } } } // Last collection. if (kind) |k| { // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); } // Write out files. for (collections.items) |*collection| { try collection.writeFile("DerivedEastAsianWidth"); } } // data/ucd/extracted/DerivedGeneralCategory.txt fn processGenCat(self: *Self) !void { // Setup input. var file = try std.fs.cwd().openFile("data/ucd/extracted/DerivedGeneralCategory.txt", .{}); defer file.close(); var buf_reader = io.bufferedReader(file.reader()); var input_stream = buf_reader.reader(); var collections = ArrayList(Collection).init(self.allocator); defer { for (collections.items) |*collection| { collection.deinit(); } collections.deinit(); } var records = ArrayList(Record).init(self.allocator); defer records.deinit(); var al = std.heap.ArenaAllocator.init(self.allocator); defer al.deinit(); var arena_allocator = &al.allocator; var kind: ?[]const u8 = null; // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip empty lines. if (line.len == 0) continue; if (mem.indexOf(u8, line, "General_Category=")) |_| { // Record kind. const equals = mem.indexOf(u8, line, "=").?; const current_kind = mem.trim(u8, line[equals + 1 ..], " "); // Check if new collection started. if (kind) |k| { // New collection for new record kind. if (!mem.eql(u8, k, current_kind)) { // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); // Update kind. kind = try arena_allocator.dupe(u8, current_kind); } } else { // kind is null, initialize it. kind = try arena_allocator.dupe(u8, current_kind); } continue; } else if (line[0] == '#') { // Skip comments. continue; } // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { // Construct record. var record: Record = undefined; // Ranges. if (mem.indexOf(u8, field, "..")) |dots| { const r_lo = try fmt.parseInt(u21, field[0..dots], 16); const r_hi = try fmt.parseInt(u21, field[dots + 2 ..], 16); record = .{ .range = .{ .lo = r_lo, .hi = r_hi } }; } else { const code_point = try fmt.parseInt(u21, field, 16); record = .{ .single = code_point }; } // Add this record. try records.append(record); } else { continue; } } } // Last collection. if (kind) |k| { // Calculate lo/hi. var lo: u21 = 0x10FFFF; var hi: u21 = 0; for (records.items) |rec| { switch (rec) { .single => |cp| { if (cp < lo) lo = cp; if (cp > hi) hi = cp; }, .range => |range| { if (range.lo < lo) lo = range.lo; if (range.hi > hi) hi = range.hi; }, } } try collections.append(try Collection.init( self.allocator, k, lo, hi, records.toOwnedSlice(), )); } // Write out files. for (collections.items) |*collection| { try collection.writeFile("DerivedGeneralCategory"); } } // data/ucd/CaseFolding.txt fn processCaseFold(self: *Self) !void { // Setup input. var in_file = try std.fs.cwd().openFile("data/ucd/CaseFolding.txt", .{}); defer in_file.close(); var buf_reader = io.bufferedReader(in_file.reader()); var input_stream = buf_reader.reader(); // Setup output. const header_tpl = @embedFile("parts/fold_map_header_tpl.txt"); const trailer_tpl = @embedFile("parts/fold_map_trailer_tpl.txt"); var cwd = std.fs.cwd(); cwd.makeDir("components/autogen/CaseFolding") catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var out_file = try cwd.createFile("components/autogen/CaseFolding/CaseFoldMap.zig", .{}); defer out_file.close(); var buf_writer = io.bufferedWriter(out_file.writer()); const writer = buf_writer.writer(); _ = try writer.print(header_tpl, .{}); // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip comments or empty lines. if (line.len == 0 or line[0] == '#') continue; // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; var code_point: []const u8 = undefined; var select = false; while (fields.next()) |raw| : (field_index += 1) { if (field_index == 0) { // Code point. code_point = raw; } else if (field_index == 1) { if (mem.endsWith(u8, raw, " C") or mem.endsWith(u8, raw, " F")) select = true; } else if (field_index == 2) { if (select) { // Mapping. var field = mem.trim(u8, raw, " "); var cp_iter = mem.split(field, " "); _ = try writer.print(" try instance.map.put(0x{s}, &[_]u21{{\n", .{code_point}); while (cp_iter.next()) |cp| { _ = try writer.print(" 0x{s},\n", .{cp}); } _ = try writer.write(" });\n"); select = false; } } else { continue; } } } // Finish writing. _ = try writer.print(trailer_tpl, .{}); try buf_writer.flush(); } // data/ucd/UnicodeData.txt fn processUcd(self: *Self) !void { // Setup input. var in_file = try std.fs.cwd().openFile("data/ucd/UnicodeData.txt", .{}); defer in_file.close(); var buf_reader = io.bufferedReader(in_file.reader()); var input_stream = buf_reader.reader(); // Output directory. var cwd = std.fs.cwd(); cwd.makeDir("components/autogen/UnicodeData") catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; // Templates. const decomp_header_tpl = @embedFile("parts/decomp_map_header_tpl.txt"); const decomp_trailer_tpl = @embedFile("parts/decomp_map_trailer_tpl.txt"); const map_header_tpl = @embedFile("parts/map_header_tpl.txt"); const map_trailer_tpl = @embedFile("parts/map_trailer_tpl.txt"); // Setup output. var d_file = try cwd.createFile("components/autogen/UnicodeData/DecomposeMap.zig", .{}); defer d_file.close(); var d_buf = io.bufferedWriter(d_file.writer()); const d_writer = d_buf.writer(); var l_file = try cwd.createFile("components/autogen/UnicodeData/LowerMap.zig", .{}); defer l_file.close(); var l_buf = io.bufferedWriter(l_file.writer()); const l_writer = l_buf.writer(); var t_file = try cwd.createFile("components/autogen/UnicodeData/TitleMap.zig", .{}); defer t_file.close(); var t_buf = io.bufferedWriter(t_file.writer()); const t_writer = t_buf.writer(); var u_file = try cwd.createFile("components/autogen/UnicodeData/UpperMap.zig", .{}); defer u_file.close(); var u_buf = io.bufferedWriter(u_file.writer()); const u_writer = u_buf.writer(); // Headers. _ = try d_writer.print(decomp_header_tpl, .{}); _ = try l_writer.print(map_header_tpl, .{"LowerMap"}); _ = try t_writer.print(map_header_tpl, .{"TitleMap"}); _ = try u_writer.print(map_header_tpl, .{"UpperMap"}); // Iterate over lines. // pf == Final_Punctuation var pf_records = ArrayList(Record).init(self.allocator); defer pf_records.deinit(); var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; var code_point: []const u8 = undefined; while (fields.next()) |raw| : (field_index += 1) { if (field_index == 0) { // Code point. code_point = raw; } else if (field_index == 2 and mem.eql(u8, raw, "Pf")) { // Final Punctuation. const cp = try fmt.parseInt(u21, code_point, 16); try pf_records.append(.{ .single = cp }); } else if (field_index == 5 and raw.len != 0) { // Decomposition. var is_compat = false; var cp_list = ArrayList([]const u8).init(self.allocator); defer cp_list.deinit(); var cp_iter = mem.split(raw, " "); while (cp_iter.next()) |cp| { if (mem.startsWith(u8, cp, "<")) { is_compat = true; continue; } try cp_list.append(cp); } if (!is_compat and cp_list.items.len == 1) { // Singleton _ = try d_writer.print(" try instance.map.put(0x{s}, .{{ .single = 0x{s} }});\n", .{ code_point, cp_list.items[0] }); } else if (!is_compat) { // Canonical std.debug.assert(cp_list.items.len != 0); _ = try d_writer.print(" try instance.map.put(0x{s}, .{{ .canon = [2]u21{{\n", .{code_point}); for (cp_list.items) |cp| { _ = try d_writer.print(" 0x{s},\n", .{cp}); } _ = try d_writer.write(" } });\n"); } else { // Compatibility std.debug.assert(cp_list.items.len != 0); _ = try d_writer.print(" try instance.map.put(0x{s}, .{{ .compat = &[_]u21{{\n", .{code_point}); for (cp_list.items) |cp| { _ = try d_writer.print(" 0x{s},\n", .{cp}); } _ = try d_writer.write(" } });\n"); } } else if (field_index == 12 and raw.len != 0) { // Uppercase mapping. _ = try u_writer.print(" try instance.map.put(0x{s}, 0x{s});\n", .{ code_point, raw }); } else if (field_index == 13 and raw.len != 0) { // Lowercase mapping. _ = try l_writer.print(" try instance.map.put(0x{s}, 0x{s});\n", .{ code_point, raw }); } else if (field_index == 14 and raw.len != 0) { // Titlecase mapping. _ = try t_writer.print(" try instance.map.put(0x{s}, 0x{s});\n", .{ code_point, raw }); } else { continue; } } } // Finish writing. _ = try d_writer.write(decomp_trailer_tpl); _ = try l_writer.print(map_trailer_tpl, .{ "Lower", "LowerMap" }); _ = try t_writer.print(map_trailer_tpl, .{ "Title", "TitleMap" }); _ = try u_writer.print(map_trailer_tpl, .{ "Upper", "UpperMap" }); try d_buf.flush(); try l_buf.flush(); try t_buf.flush(); try u_buf.flush(); // Final Punctuation collection. if (pf_records.items.len != 0) { var pf_lo: u21 = 0x10FFFF; var pf_hi: u21 = 0; for (pf_records.items) |pfr| { switch (pfr) { .single => |cp| { if (cp < pf_lo) pf_lo = cp; if (cp > pf_hi) pf_hi = cp; }, else => unreachable, } } std.debug.assert(pf_lo < pf_hi); var pf_collection = try Collection.init(self.allocator, "Final_Punctuation", pf_lo, pf_hi, pf_records.toOwnedSlice()); try pf_collection.writeFile("UnicodeData"); } } // data/ucd/SpecialCassing.txt fn processSpecialCasing(self: *Self) !void { // Setup input. var in_file = try std.fs.cwd().openFile("data/ucd/SpecialCasing.txt", .{}); defer in_file.close(); var buf_reader = io.bufferedReader(in_file.reader()); var input_stream = buf_reader.reader(); // Setup output. const header_tpl = @embedFile("parts/special_case_header_tpl.txt"); const trailer_tpl = @embedFile("parts/special_case_trailer_tpl.txt"); var cwd = std.fs.cwd(); cwd.makeDir("components/autogen/SpecialCasing") catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var out_file = try cwd.createFile("components/autogen/SpecialCasing/SpecialCaseMap.zig", .{}); defer out_file.close(); var buf_writer = io.bufferedWriter(out_file.writer()); const writer = buf_writer.writer(); _ = try writer.print(header_tpl, .{}); // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip comments or empty lines. if (line.len == 0 or line[0] == '#') continue; // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; var code_point: []const u8 = undefined; var mappings: [3][][]const u8 = undefined; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { // Code point. code_point = field; } else if (field_index == 1) { // Lowercase. var cp_iter = mem.split(field, " "); var cp_list = ArrayList([]const u8).init(self.allocator); while (cp_iter.next()) |cp| { try cp_list.append(cp); } mappings[0] = cp_list.toOwnedSlice(); } else if (field_index == 2) { // Titlecase. var cp_iter = mem.split(field, " "); var cp_list = ArrayList([]const u8).init(self.allocator); while (cp_iter.next()) |cp| { try cp_list.append(cp); } mappings[1] = cp_list.toOwnedSlice(); } else if (field_index == 3) { // Uppercase. var cp_iter = mem.split(field, " "); var cp_list = ArrayList([]const u8).init(self.allocator); while (cp_iter.next()) |cp| { try cp_list.append(cp); } mappings[2] = cp_list.toOwnedSlice(); } else if (field_index == 4) { _ = try writer.print(" try instance.map.put(0x{s}, .{{\n", .{code_point}); if (field.len == 0 or field[0] == '#') { // No countries or conditions. _ = try writer.write(" .countries = &[0][]u8{},\n"); _ = try writer.write(" .conditions = &[0][]u8{},\n"); } else { // Countries and/or conditions. var countries_started = false; var conditions_started = false; var coco_iter = mem.split(field, " "); while (coco_iter.next()) |cc| { if (ascii.isLower(cc[0])) { // Country code. if (!countries_started) { _ = try writer.write(" .countries = &[_][]u8{\n"); countries_started = true; } _ = try writer.print(" \"{s}\",\n", .{cc}); } else { // Conditions. if (countries_started) { _ = try writer.write(" },\n"); countries_started = false; } if (!conditions_started) { _ = try writer.write(" .conditions = &[_][]u8{\n"); conditions_started = true; } _ = try writer.print(" \"{s}\",\n", .{cc}); } } if (countries_started) { _ = try writer.write(" },\n"); } if (conditions_started) { _ = try writer.write(" },\n"); } } // Mappings. _ = try writer.write(" .mappings = [3][]u8{\n"); for (mappings) |cmaps| { if (cmaps.len == 0) { // No mapping. _ = try writer.write(" &[0]u8{},\n"); } else { _ = try writer.write(" &[_]u8{ "); for (cmaps) |mcp, i| { if (mcp.len == 0) continue; if (i != 0) { _ = try writer.write(", "); } _ = try writer.print("0x{s}", .{mcp}); } _ = try writer.write(" },\n"); } } _ = try writer.write(" },\n });\n"); } else { continue; } } } // Finish writing. _ = try writer.print(trailer_tpl, .{}); try buf_writer.flush(); } // data/ucd/extracted/DerivedCombiningClass.txt fn processCccMap(self: *Self) !void { // Setup input. var file = try std.fs.cwd().openFile("data/ucd/extracted/DerivedCombiningClass.txt", .{}); defer file.close(); var buf_reader = io.bufferedReader(file.reader()); var input_stream = buf_reader.reader(); // Setup output. const header_tpl = @embedFile("parts/ccc_header_tpl.txt"); const trailer_tpl = @embedFile("parts/ccc_trailer_tpl.txt"); var cwd = std.fs.cwd(); cwd.makeDir("components/autogen/DerivedCombiningClass") catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var out_file = try cwd.createFile("components/autogen/DerivedCombiningClass/CccMap.zig", .{}); defer out_file.close(); var buf_writer = io.bufferedWriter(out_file.writer()); const writer = buf_writer.writer(); _ = try writer.write(header_tpl); // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip comments or empty lines. if (line.len == 0 or line[0] == '#') continue; // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; var r_lo: ?[]const u8 = null; var r_hi: ?[]const u8 = null; var code_point: ?[]const u8 = null; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { if (mem.indexOf(u8, field, "..")) |dots| { // Ranges. r_lo = field[0..dots]; r_hi = field[dots + 2 ..]; } else { code_point = field; } } else if (field_index == 1) { // CCC value. // Possible comment at end. if (mem.indexOf(u8, field, "#")) |octo| { field = mem.trimRight(u8, field[0..octo], " "); } if (mem.eql(u8, field, "0")) { // Skip default value. r_lo = null; r_hi = null; code_point = null; continue; } if (code_point) |cp| { _ = try writer.print(" try instance.map.put(0x{s}, {s});\n", .{ code_point, field }); } else { _ = try writer.print(" index = 0x{s};\n", .{r_lo.?}); _ = try writer.print(" while (index <= 0x{s}) : (index += 1) {{\n", .{r_hi.?}); _ = try writer.print(" try instance.map.put(index, {s});\n", .{field}); _ = try writer.write(" }\n"); } r_lo = null; r_hi = null; code_point = null; continue; } else { r_lo = null; r_hi = null; code_point = null; continue; } } } // Finish writing. _ = try writer.write(trailer_tpl); try buf_writer.flush(); } // data/ucd/HangulSyllableType.txt fn processHangul(self: *Self) !void { // Setup input. var file = try std.fs.cwd().openFile("data/ucd/HangulSyllableType.txt", .{}); defer file.close(); var buf_reader = io.bufferedReader(file.reader()); var input_stream = buf_reader.reader(); // Setup output. const header_tpl = @embedFile("parts/hangul_header_tpl.txt"); const trailer_tpl = @embedFile("parts/hangul_trailer_tpl.txt"); var cwd = std.fs.cwd(); cwd.makeDir("components/autogen/HangulSyllableType") catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var out_file = try cwd.createFile("components/autogen/HangulSyllableType/HangulMap.zig", .{}); defer out_file.close(); var buf_writer = io.bufferedWriter(out_file.writer()); const writer = buf_writer.writer(); _ = try writer.write(header_tpl); // Iterate over lines. var buf: [640]u8 = undefined; while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { // Skip comments or empty lines. if (line.len == 0 or line[0] == '#') continue; // Iterate over fields. var fields = mem.split(line, ";"); var field_index: usize = 0; var r_lo: ?[]const u8 = null; var r_hi: ?[]const u8 = null; var code_point: ?[]const u8 = null; while (fields.next()) |raw| : (field_index += 1) { var field = mem.trim(u8, raw, " "); if (field_index == 0) { if (mem.indexOf(u8, field, "..")) |dots| { // Ranges. r_lo = field[0..dots]; r_hi = field[dots + 2 ..]; } else { code_point = field; } } else if (field_index == 1) { // Syllable type. // Possible comment at end. if (mem.indexOf(u8, field, "#")) |octo| { field = mem.trimRight(u8, field[0..octo], " "); } if (code_point) |cp| { _ = try writer.print(" try instance.map.put(0x{s}, .{s});\n", .{ code_point, field }); } else { _ = try writer.print(" index = 0x{s};\n", .{r_lo.?}); _ = try writer.print(" while (index <= 0x{s}) : (index += 1) {{\n", .{r_hi.?}); _ = try writer.print(" try instance.map.put(index, .{s});\n", .{field}); _ = try writer.write(" }\n"); } r_lo = null; r_hi = null; code_point = null; continue; } else { r_lo = null; r_hi = null; code_point = null; continue; } } } // Finish writing. _ = try writer.write(trailer_tpl); try buf_writer.flush(); } }; fn clean_name(allocator: *mem.Allocator, str: []const u8) ![]u8 { var name1 = try allocator.alloc(u8, mem.replacementSize(u8, str, "_", "")); defer allocator.free(name1); _ = mem.replace(u8, str, "_", "", name1); var name2 = try allocator.alloc(u8, mem.replacementSize(u8, name1, "-", "")); defer allocator.free(name2); _ = mem.replace(u8, name1, "-", "", name2); var name = try allocator.alloc(u8, mem.replacementSize(u8, name1, " ", "")); _ = mem.replace(u8, name2, " ", "", name); return name; } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; //var allocator = std.testing.allocator; var ugen = UcdGenerator.new(allocator); //try ugen.processF1("data/ucd/Blocks.txt"); try ugen.processF1("data/ucd/PropList.txt"); //try ugen.processF1("data/ucd/Scripts.txt"); try ugen.processF1("data/ucd/auxiliary/GraphemeBreakProperty.txt"); try ugen.processF1("data/ucd/DerivedCoreProperties.txt"); //try ugen.processF1("data/ucd/extracted/DerivedDecompositionType.txt"); try ugen.processF1("data/ucd/extracted/DerivedNumericType.txt"); try ugen.processF1("data/ucd/emoji/emoji-data.txt"); try ugen.processGenCat(); try ugen.processCaseFold(); try ugen.processUcd(); //try ugen.processSpecialCasing(); try ugen.processCccMap(); try ugen.processHangul(); try ugen.processAsianWidth(); }
src/ucd_gen.zig
const std = @import("std"); const assert = std.debug.assert; const allocator = std.testing.allocator; const TargetInfo = struct { angle: f64, x: usize, y: usize, dist: usize, shot: bool, }; fn cmpByAngle(_: void, l: TargetInfo, r: TargetInfo) bool { if (l.angle < r.angle) return true; if (l.angle > r.angle) return false; return l.dist < r.dist; } pub const Board = struct { maxx: usize, maxy: usize, data: [50][50]usize, pub fn init() Board { var self = Board{ .maxx = 0, .maxy = 0, .data = undefined, }; return self; } pub fn deinit(self: Board) void { _ = self; } pub fn add_lines(self: *Board, lines: []const u8) void { var it = std.mem.split(u8, lines, "\n"); while (it.next()) |str| { self.add_line(str); } } pub fn add_line(self: *Board, str: []const u8) void { var j: usize = 0; while (j < str.len) : (j += 1) { var c: usize = 0; if (str[j] == '#') c = 1; self.data[self.maxy][j] = c; } if (self.maxx < j) { self.maxx = j; } self.maxy += 1; } fn gcd(a: usize, b: usize) usize { var la = a; var lb = b; while (lb != 0) { const t = lb; lb = la % lb; la = t; } return la; } pub fn show(self: Board) void { var y: usize = 0; std.debug.warn("BOARD {}x{}\n", self.maxy, self.maxx); while (y < self.maxy) : (y += 1) { var x: usize = 0; std.debug.warn("|"); while (x < self.maxx) : (x += 1) { std.debug.warn("{}", self.data[y][x]); } std.debug.warn("|\n"); } } pub fn find_best_position(self: *Board) usize { var minc: usize = 0; var minx: usize = 0; var miny: usize = 0; var seen = std.AutoHashMap(usize, void).init(allocator); defer seen.deinit(); var srcy: usize = 0; while (srcy < self.maxy) : (srcy += 1) { var srcx: usize = 0; while (srcx < self.maxx) : (srcx += 1) { if (self.data[srcy][srcx] == 0) continue; seen.clearRetainingCapacity(); var tgty: usize = 0; while (tgty < self.maxy) : (tgty += 1) { var tgtx: usize = 0; while (tgtx < self.maxx) : (tgtx += 1) { if (tgtx == srcx and tgty == srcy) continue; if (self.data[tgty][tgtx] == 0) continue; const label = make_label(srcx, srcy, tgtx, tgty); if (seen.contains(label)) continue; self.data[srcy][srcx] += 1; if (minc < self.data[srcy][srcx]) { minx = srcx; miny = srcy; minc = self.data[srcy][srcx]; } _ = seen.put(label, {}) catch unreachable; } } } } // std.debug.warn("MIN is {} at {} {}\n", minc - 1, minx, miny); return minc - 1; // the position itself doesn't count } pub fn scan_and_blast(self: *Board, srcx: usize, srcy: usize, target: usize) usize { var data: [50 * 50]TargetInfo = undefined; var pos: usize = 0; var y: usize = 0; while (y < self.maxy) : (y += 1) { var x: usize = 0; while (x < self.maxx) : (x += 1) { if (x == srcx and y == srcy) continue; if (self.data[y][x] == 0) continue; // compute theta = atan(dx / dy) // in this case we do want the signs for the differences // atan returns angles that grow counterclockwise, hence the '-' // atan returns negative angles for x<0, hence we add 2*pi then const dx = @intToFloat(f64, @intCast(i32, srcx) - @intCast(i32, x)); const dy = @intToFloat(f64, @intCast(i32, srcy) - @intCast(i32, y)); var theta = -std.math.atan2(f64, dx, dy); if (theta < 0) theta += 2.0 * std.math.pi; data[pos].angle = theta; data[pos].x = x; data[pos].y = y; data[pos].dist = @floatToInt(usize, std.math.absFloat(dx)) + @floatToInt(usize, std.math.absFloat(dy)); data[pos].shot = false; // std.debug.warn("POS {} = {} {} : {}\n", pos, data[pos].x, data[pos].y, data[pos].a); pos += 1; } } // we can now sort by angle; for positions with the same angle, the lowest distance wins std.sort.sort(TargetInfo, data[0..pos], {}, cmpByAngle); // we can now circle around as many times as necessary to hit the desired target var seen = std.AutoHashMap(usize, void).init(allocator); defer seen.deinit(); var shot: usize = 0; while (shot < pos) { // on each turn we "forget" the previous targets seen.clearRetainingCapacity(); var j: usize = 0; while (j < pos) : (j += 1) { // skip positions we have already shot if (data[j].shot) continue; const label = make_label(srcx, srcy, data[j].x, data[j].y); if (seen.contains(label)) continue; _ = seen.put(label, {}) catch unreachable; // we have not shot yet in this direction; do it! shot += 1; // std.debug.warn("SHOT #{}: {} {}\n", shot, data[j].x, data[j].y); data[j].shot = true; if (shot == target) { return data[j].x * 100 + data[j].y; } } } return 0; } fn make_label(srcx: usize, srcy: usize, tgtx: usize, tgty: usize) usize { var dir: usize = 0; var dx: usize = 0; if (srcx > tgtx) { dx = srcx - tgtx; dir |= 0x01; } else { dx = tgtx - srcx; } var dy: usize = 0; if (srcy > tgty) { dy = srcy - tgty; dir |= 0x10; } else { dy = tgty - srcy; } const common = gcd(dx, dy); const canonx = dx / common; const canony = dy / common; const label = (dir * 10 + canonx) * 100 + canony; return label; } }; test "best position 1" { const data: []const u8 = \\.#..# \\..... \\##### \\....# \\...## ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.find_best_position(); assert(result == 8); } test "best position 2" { const data: []const u8 = \\......#.#. \\#..#.#.... \\..#######. \\.#.#.###.. \\.#..#..... \\..#....#.# \\#..#....#. \\.##.#..### \\##...#..#. \\.#....#### ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.find_best_position(); assert(result == 33); } test "best position 3" { const data: []const u8 = \\#.#...#.#. \\.###....#. \\.#....#... \\##.#.#.#.# \\....#.#.#. \\.##..###.# \\..#...##.. \\..##....## \\......#... \\.####.###. ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.find_best_position(); assert(result == 35); } test "best position 4" { const data: []const u8 = \\.#..#..### \\####.###.# \\....###.#. \\..###.##.# \\##.##.#.#. \\....###..# \\..#.#..#.# \\#..#.#.### \\.##...##.# \\.....#.#.. ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.find_best_position(); assert(result == 41); } test "best position 5" { const data: []const u8 = \\.#..##.###...####### \\##.############..##. \\.#.######.########.# \\.###.#######.####.#. \\#####.##.#.##.###.## \\..#####..#.######### \\#################### \\#.####....###.#.#.## \\##.################# \\#####.##.###..####.. \\..######..##.####### \\####.##.####...##..# \\.#####..#.######.### \\##...#.##########... \\#.##########.####### \\.####.#.###.###.#.## \\....##.##.###..##### \\.#.#.###########.### \\#.#.#.#####.####.### \\###.##.####.##.#..## ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.find_best_position(); assert(result == 210); } test "scan small" { const data: []const u8 = \\.#....#####...#.. \\##...##.#####..## \\##...#...#.#####. \\..#.....#...###.. \\..#.#.....#....## ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.scan_and_blast(8, 3, 36); assert(result == 1403); } test "scan medium" { const data: []const u8 = \\.#..##.###...####### \\##.############..##. \\.#.######.########.# \\.###.#######.####.#. \\#####.##.#.##.###.## \\..#####..#.######### \\#################### \\#.####....###.#.#.## \\##.################# \\#####.##.###..####.. \\..######..##.####### \\####.##.####...##..# \\.#####..#.######.### \\##...#.##########... \\#.##########.####### \\.####.#.###.###.#.## \\....##.##.###..##### \\.#.#.###########.### \\#.#.#.#####.####.### \\###.##.####.##.#..## ; var board = Board.init(); board.add_lines(data); // board.show(); const result = board.scan_and_blast(11, 13, 200); assert(result == 802); }
2019/p10/board.zig
const std = @import("std"); const with_trace = false; const with_dissassemble = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.warn(fmt, args); } const Computer = struct { name: []const u8, memory: []Data, pc: usize = undefined, base: Data = undefined, io_mode: IOMode = undefined, io_port: Data = undefined, io_runframe: @Frame(run) = undefined, const Data = i64; const halted: usize = 9999999; const OperandType = enum { any, adr, }; const OperandMode = enum { pos, imm, rel, }; const Operation = enum { hlt, jne, jeq, add, mul, slt, seq, in, out, err, arb, }; const Instruction = struct { op: Operation, name: []const u8, operands: []const OperandType, }; const insn_table = comptime build_instruction_table(); fn add_insn(op: Operation, name: []const u8, code: u8, operands: []const OperandType, table: []Instruction) void { table[code].op = op; table[code].name = name; table[code].operands = operands; } fn build_instruction_table() [100]Instruction { var table = [1]Instruction{.{ .op = Operation.err, .name = "invalid", .operands = &[_]OperandType{s} }} ** 100; add_insn(.hlt, "ctl.HALT", 99, &[_]OperandType{s}, &table); add_insn(.jne, "ctl.JNE", 5, &[_]OperandType{ .any, .any }, &table); // jump-if-true add_insn(.jeq, "ctl.JEQ", 6, &[_]OperandType{ .any, .any }, &table); // jump-if-false add_insn(.add, "alu.ADD", 1, &[_]OperandType{ .any, .any, .adr }, &table); add_insn(.mul, "alu.MUL", 2, &[_]OperandType{ .any, .any, .adr }, &table); add_insn(.slt, "alu.SLT", 7, &[_]OperandType{ .any, .any, .adr }, &table); // set if less than add_insn(.seq, "alu.SEQ", 8, &[_]OperandType{ .any, .any, .adr }, &table); // set if zero add_insn(.arb, "alu.ARB", 9, &[_]OperandType{.any}, &table); // adjust relative base add_insn(.in, "io.IN ", 3, &[_]OperandType{.adr}, &table); add_insn(.out, "io.OUT ", 4, &[_]OperandType{.any}, &table); return table; } fn parse_mode(v: usize) !OperandMode { switch (v) { 0 => return .pos, 1 => return .imm, 2 => return .rel, else => return error.unknownMode, //@panic("unknown mode"), } } fn parse_opcode(v: Data, opcode: *u8, modes: []OperandMode) !void { const opcode_and_modes = @intCast(usize, v); opcode.* = @intCast(u8, opcode_and_modes % 100); modes[0] = try parse_mode((opcode_and_modes / 100) % 10); modes[1] = try parse_mode((opcode_and_modes / 1000) % 10); modes[2] = try parse_mode((opcode_and_modes / 10000) % 10); } fn load_param(par: Data, t: OperandType, mode: OperandMode, base: Data, mem: []const Data) Data { switch (t) { .adr => switch (mode) { .pos => return par, .imm => @panic("invalid mode"), .rel => return par + base, }, .any => switch (mode) { .pos => return mem[@intCast(usize, par)], .imm => return par, .rel => return mem[@intCast(usize, par + base)], }, } } fn reboot(c: *Computer, boot_image: []const Data) void { trace("[{s}] reboot\n", .{c.name}); std.mem.copy(Data, c.memory[0..boot_image.len], boot_image); std.mem.set(Data, c.memory[boot_image.len..], 0); c.pc = 0; c.base = 0; c.io_port = undefined; } fn is_halted(c: *Computer) bool { return c.pc == halted; } const IOMode = enum { input, output, }; fn run(c: *Computer) void { while (c.pc != halted) { // decode insn opcode var opcode: u8 = undefined; var modes: [3]OperandMode = undefined; parse_opcode(c.memory[c.pc], &opcode, &modes) catch unreachable; c.pc += 1; const insn = insn_table[opcode]; var string_storage: [100]u8 = undefined; trace("[{s}] {s}\n", .{ c.name, dissamble_insn(insn, &modes, c.memory[c.pc..], &string_storage) }); // load parameters from insn operands var param_registers: [3]Data = undefined; const p = blk: { const operands = insn.operands; const p = param_registers[0..operands.len]; var i: usize = 0; while (i < operands.len) : (i += 1) { p[i] = load_param(c.memory[c.pc + i], operands[i], modes[i], c.base, c.memory); } c.pc += operands.len; break :blk p; }; // execute insn switch (insn.op) { .hlt => c.pc = halted, .jne => c.pc = if (p[0] != 0) @intCast(usize, p[1]) else c.pc, .jeq => c.pc = if (p[0] == 0) @intCast(usize, p[1]) else c.pc, .add => c.memory[@intCast(usize, p[2])] = p[0] + p[1], .mul => c.memory[@intCast(usize, p[2])] = p[0] * p[1], .slt => c.memory[@intCast(usize, p[2])] = if (p[0] < p[1]) 1 else 0, .seq => c.memory[@intCast(usize, p[2])] = if (p[0] == p[1]) 1 else 0, .arb => c.base += p[0], .in => { c.io_mode = .input; trace("[{s}] reading...\n", .{c.name}); suspend { c.io_runframe = @frame().*; } trace("[{s}] ...got {s}\n", .{ c.name, c.io_port }); c.memory[@intCast(usize, p[0])] = c.io_port; }, .out => { c.io_mode = .output; c.io_port = p[0]; trace("[{s}] writing {s}...\n", .{ c.name, c.io_port }); suspend { c.io_runframe = @frame().*; } trace("[{s}] ...ok\n", .{c.name}); }, .err => @panic("Illegal instruction"), } } } fn append_fmt(storage: []u8, i: *usize, comptime fmt: []const u8, v: anytype) void { const r = std.fmt.bufPrint(storage[i.*..], fmt, .{v}) catch unreachable; i.* += r.len; } fn dissamble_insn(insn: Instruction, modes: []const OperandMode, operands: []const Data, storage: []u8) []const u8 { var i: usize = 0; std.mem.copy(u8, storage[i..], insn.name); i += insn.name.len; std.mem.copy(u8, storage[i..], "\t"); i += 1; for (insn.operands) |optype, j| { if (j > 0) { std.mem.copy(u8, storage[i..], ", "); i += 2; } if (j >= operands.len) { std.mem.copy(u8, storage[i..], "ERR"); i += 3; } else { switch (optype) { .adr => switch (modes[j]) { .imm => append_fmt(storage, &i, "ERR{s}", operands[j]), .pos => append_fmt(storage, &i, "@{s}", operands[j]), .rel => append_fmt(storage, &i, "@b+{s}", operands[j]), }, .any => switch (modes[j]) { .imm => append_fmt(storage, &i, "{s}", operands[j]), .pos => append_fmt(storage, &i, "[{s}]", operands[j]), .rel => append_fmt(storage, &i, "[b+{s}]", operands[j]), }, } } } return storage[0..i]; } fn disassemble(image: []const Data) void { var pc: usize = 0; while (pc < image.len) { var opcode: u8 = undefined; var modes: [3]OperandMode = undefined; var insn_size: usize = 1; var asmstr_storage: [100]u8 = undefined; const asmstr = blk: { if (parse_opcode(image[pc], &opcode, &modes)) { const insn = insn_table[opcode]; insn_size += insn.operands.len; break :blk dissamble_insn(insn, &modes, image[pc + 1 ..], &asmstr_storage); } else |err| { break :blk ""; } }; var datastr_storage: [100]u8 = undefined; const datastr = blk: { var i: usize = 0; var l: usize = 0; while (i < insn_size) : (i += 1) { append_fmt(&datastr_storage, &l, "{s} ", if (pc + i < image.len) image[pc + i] else 0); } break :blk datastr_storage[0..l]; }; std.debug.warn("{d:0>4}: {s:15} {s}\n", .{ pc, datastr, asmstr }); pc += insn_size; } } }; const Vec2 = struct { x: i32, y: i32, }; fn vecmin(a: Vec2, b: Vec2) Vec2 { return Vec2{ .x = if (a.x < b.x) a.x else b.x, .y = if (a.y < b.y) a.y else b.y, }; } fn vecmax(a: Vec2, b: Vec2) Vec2 { return Vec2{ .x = if (a.x > b.x) a.x else b.x, .y = if (a.y > b.y) a.y else b.y, }; } const BBox = struct { min: Vec2, max: Vec2, }; const Map = struct { const Tile = u8; const stride = 128; map: [stride * stride]Tile = undefined, bbox: BBox = BBox{ .min = Vec2{ .x = 99999, .y = 99999 }, .max = Vec2{ .x = -99999, .y = -99999 } }, fn print_to_buf(map: Map, pos: Vec2, crop: ?BBox, buf: []u8) []const u8 { var i: usize = 0; const b = if (crop) |box| BBox{ .min = vecmax(map.bbox.min, box.min), .max = vecmin(map.bbox.max, box.max), } else map.bbox; var p = b.min; while (p.y <= b.max.y) : (p.y += 1) { p.x = b.min.x; while (p.x <= b.max.x) : (p.x += 1) { const offset = map.offsetof(p); buf[i] = map.map[offset]; if (p.x == pos.x and p.y == pos.y) { buf[i] = '@'; } i += 1; } buf[i] = '\n'; i += 1; } return buf[0..i]; } fn offsetof(map: *const Map, p: Vec2) usize { return @intCast(usize, p.x) + @intCast(usize, p.y) * stride; } fn at(map: *const Map, p: Vec2) Tile { assert(p.x >= map.bbox.min.x and p.y >= map.bbox.min.y and p.x <= map.bbox.max.x and p.y <= map.bbox.max.y); assert(p.x >= 0 and p.y >= 0 and p.x < stride); const offset = map.offsetof(p); return map.map[offset]; } fn get(map: *const Map, p: Vec2) ?Tile { if (p.x < map.bbox.min.x or p.y < map.bbox.min.y) return null; if (p.x > map.bbox.max.x or p.y > map.bbox.max.y) return null; if (p.x < 0 or p.y < 0) return null; if (p.x >= stride) return null; const offset = map.offsetof(p); if (offset >= map.map.len) return null; return map.map[offset]; } fn set(map: *Map, p: Vec2, t: Tile) void { map.bbox.min = vecmin(p, map.bbox.min); map.bbox.max = vecmax(p, map.bbox.max); assert(p.x >= 0 or p.y >= 0); assert(p.x < stride); const offset = map.offsetof(p); assert(offset < map.map.len); map.map[offset] = t; } }; const BestFirstSearch = struct { const State = struct { maplevel: u32, curtp: u16, }; const Node = struct { rating: i32, steps: u32, state: State, }; const Agenda = std.ArrayList(*const Node); const VisitedNodes = std.AutoHashMap(State, *const Node); allocator: *std.mem.Allocator, agenda: Agenda, recyclebin: std.ArrayList(*Node), visited: VisitedNodes, fn init(allocator: *std.mem.Allocator) BestFirstSearch { return BestFirstSearch{ .allocator = allocator, .agenda = BestFirstSearch.Agenda.init(allocator), .recyclebin = std.ArrayList(*BestFirstSearch.Node).init(allocator), .visited = BestFirstSearch.VisitedNodes.init(allocator), }; } fn deinit(s: *BestFirstSearch) void { var iterator = s.visited.iterator(); while (iterator.next()) |it| { s.allocator.destroy(it.value); } s.visited.deinit(); s.recyclebin.deinit(); s.agenda.deinit(); } fn insert(s: *BestFirstSearch, node: Node) !void { if (s.visited.get(node.state)) |kv| { if (kv.value.cost <= node.cost) { return; } } var index: ?usize = null; for (s.agenda.items) |n, i| { if (n.rating <= node.rating) { index = i; break; } } const poolelem = if (s.recyclebin.popOrNull()) |n| n else try s.allocator.create(Node); poolelem.* = node; if (index) |i| { try s.agenda.insert(i, poolelem); } else { try s.agenda.append(poolelem); } if (try s.visited.put(poolelem.state, poolelem)) |kv| { // overwriten elem? for (s.agenda.items) |v, i| { if (v == kv.value) { _ = s.agenda.orderedRemove(i); break; } } s.allocator.destroy(kv.value); } } fn pop(s: *BestFirstSearch) ?Node { if (s.agenda.popOrNull()) |n| { // if (!visited) { //const writable_node: *Node = @intToPtr(*Node, @ptrToInt(n)); //s.recyclebin.append(writable_node) catch unreachable; // } return n.*; } else { return null; } } }; fn decode_tp(map: *Map, maplevel: u32, p: Vec2) ?u16 { const m = map.at(p); if (m < 'A' or m > 'Z') return null; const is_outer = (p.x < map.bbox.min.x + 2 or p.y < map.bbox.min.y + 2 or p.x >= map.bbox.max.x - 2 or p.y >= map.bbox.max.y - 2); if (maplevel > 0 and (m == 'A' or m == 'Z')) return null; //if (maplevel == 0 and !(m == 'A' or m == 'Z') and is_outer) // return null; // outer tp var firstletter: u8 = undefined; var secondletter: u8 = undefined; const up = map.get(Vec2{ .x = p.x, .y = p.y - 1 }) orelse ' '; const down = map.get(Vec2{ .x = p.x, .y = p.y + 1 }) orelse ' '; const left = map.get(Vec2{ .x = p.x - 1, .y = p.y }) orelse ' '; const right = map.get(Vec2{ .x = p.x + 1, .y = p.y }) orelse ' '; if (up >= 'A' and up <= 'Z') { firstletter = up; secondletter = m; } else if (down >= 'A' and down <= 'Z') { firstletter = m; secondletter = down; } else if (left >= 'A' and left <= 'Z') { firstletter = left; secondletter = m; } else if (right >= 'A' and right <= 'Z') { firstletter = m; secondletter = right; } else { unreachable; } return (@intCast(u16, firstletter - 'A') * 26 + @intCast(u16, secondletter - 'A')) + (if (is_outer) 0 else maxtp); } const maxtp: u16 = 26 * 26; fn compute_tpdists(map: *Map, maplevel: u32, start_tp: u16) [maxtp * 2]u16 { const maxdist: u16 = 65535; var dmap = [1]u16{maxdist - 1} ** (Map.stride * Map.stride); var tpdist = [1]u16{maxdist} ** (maxtp * 2); tpdist[start_tp] = 0; var changed = true; while (changed) { changed = false; var p = map.bbox.min; p.y = map.bbox.min.y + 1; while (p.y <= map.bbox.max.y - 1) : (p.y += 1) { p.x = map.bbox.min.x + 1; while (p.x <= map.bbox.max.x - 1) : (p.x += 1) { const up = Vec2{ .x = p.x, .y = p.y - 1 }; const down = Vec2{ .x = p.x, .y = p.y + 1 }; const left = Vec2{ .x = p.x - 1, .y = p.y }; const right = Vec2{ .x = p.x + 1, .y = p.y }; const tpup = decode_tp(map, maplevel, up); const tpdown = decode_tp(map, maplevel, down); const tpleft = decode_tp(map, maplevel, left); const tpright = decode_tp(map, maplevel, right); const offsetup = map.offsetof(up); const offsetdown = map.offsetof(down); const offsetleft = map.offsetof(left); const offsetright = map.offsetof(right); //const distup = if (tpup) |tp| tpdist[tp] else dmap[offsetup] + 1; //const distdown = if (tpdown) |tp| tpdist[tp] else dmap[offsetdown] + 1; //const distleft = if (tpleft) |tp| tpdist[tp] else dmap[offsetleft] + 1; //const distright = if (tpright) |tp| tpdist[tp] else dmap[offsetright] + 1; const distup = if (tpup) |tp| (if (tp == start_tp) 0 else maxdist) else dmap[offsetup] + 1; const distdown = if (tpdown) |tp| (if (tp == start_tp) 0 else maxdist) else dmap[offsetdown] + 1; const distleft = if (tpleft) |tp| (if (tp == start_tp) 0 else maxdist) else dmap[offsetleft] + 1; const distright = if (tpright) |tp| (if (tp == start_tp) 0 else maxdist) else dmap[offsetright] + 1; var cur_dist: u16 = maxdist; if (cur_dist > distup) cur_dist = distup; if (cur_dist > distdown) cur_dist = distdown; if (cur_dist > distleft) cur_dist = distleft; if (cur_dist > distright) cur_dist = distright; { const offset = map.offsetof(p); const m = map.map[offset]; if (decode_tp(map, maplevel, p)) |tp| { if (tpdist[tp] > cur_dist) { tpdist[tp] = cur_dist; changed = true; } } else if (m == '.') { if (dmap[offset] > cur_dist) { dmap[offset] = cur_dist; changed = true; } } } } } } return tpdist; } pub fn main() anyerror!void { const stdout = std.io.getStdOut().outStream(); const allocator = &std.heap.ArenaAllocator.init(std.heap.page_allocator).allocator; const limit = 1 * 1024 * 1024 * 1024; var random = std.rand.DefaultPrng.init(12).random; const text = try std.fs.cwd().readFileAlloc(allocator, "day20.txt", limit); defer allocator.free(text); var map = Map{}; var map_cursor = Vec2{ .x = 0, .y = 0 }; for (text) |c| { if (c == '\n') { map_cursor = Vec2{ .x = 0, .y = map_cursor.y + 1 }; } else { map.set(map_cursor, c); map_cursor.x += 1; } } { var buf: [15000]u8 = undefined; try stdout.print("{s}\n", .{map.print_to_buf(map_cursor, null, &buf)}); } var searcher = BestFirstSearch.init(allocator); defer searcher.deinit(); try searcher.insert(BestFirstSearch.Node{ .rating = 0, .cost = 0, .state = .{ .maplevel = 0, .curtp = 0, }, }); var trace_dep: usize = 0; var best: u32 = 999999; while (searcher.pop()) |node| { if (node.cost >= best) continue; //if (node.keylistlen > trace_dep) { // trace_dep = node.keylistlen; // trace("so far... steps={s}, agendalen={s}, visited={s}, recyclebin={s}, keylist[{s}]={s}\n", .{ node.cost, searcher.agenda.items.len, searcher.visited.count(), searcher.recyclebin.len, node.keylistlen, node.keylist[0..node.keylistlen] }); //} const tpdists = compute_tpdists(&map, node.state.maplevel, node.state.curtp); for (tpdists) |dist, tp| { if (dist >= 65534) continue; if (tp == (maxtp - 1)) { const steps = node.cost + (dist - 1); try stdout.print("Solution: steps={s}\n", .{steps}); best = steps; continue; } const is_outer = (tp / maxtp == 0); const tpname = @intCast(u16, tp % maxtp); var next: BestFirstSearch.Node = undefined; next.cost = node.cost + dist; next.state.curtp = tpname + (if (is_outer) maxtp else 0); next.state.maplevel = node.state.maplevel; next.rating = @intCast(i32, next.cost); // - @intCast(i32, next.keylistlen * next.keylistlen); try searcher.insert(next); } } // partie1 { const tpdist = compute_tpdists(&map, 0, 0); try stdout.print("ZZ : {s}\n", .{tpdist[maxtp - 1] - 1}); } }
2019/day20a.zig
const sf = @import("../sfml.zig"); pub const Sound = struct { const Self = @This(); // Constructor/destructor /// Inits an empty sound pub fn init() !Self { var sound = sf.c.sfSound_create(); if (sound == null) return sf.Error.nullptrUnknownReason; return Self{ .ptr = sound.? }; } /// Inits a sound with a SoundBuffer object pub fn initFromBuffer(buffer: sf.SoundBuffer) !Self { var sound = try Self.init(); sound.setBuffer(buffer); return sound; } /// Destroys this sound object pub fn deinit(self: Self) void { sf.c.sfSound_destroy(self.ptr); } // Sound control functions /// Plays the sound pub fn play(self: Self) void { sf.c.sfSound_play(self.ptr); } /// Pauses the sound pub fn pause(self: Self) void { sf.c.sfSound_pause(self.ptr); } /// Stops the sound and resets the player position pub fn stop(self: Self) void { sf.c.sfSound_stop(self.ptr); } // Getters / Setters /// Gets the buffer this sound is attached to pub fn getBuffer(self: Self) ?sf.SoundBuffer { var buf = sf.c.sfSound_getBuffer(self.ptr); if (buf) |buffer| { return .{ .ptr = buffer }; } else return null; } /// Sets the buffer this sound will play pub fn setBuffer(self: Self, buffer: sf.SoundBuffer) void { sf.c.sfSound_setBuffer(self.ptr, buffer.ptr); } /// Gets the current playing offset of the sound pub fn getPlayingOffset(self: Self) sf.Time { return sf.Time.fromCSFML(sf.c.sfSound_getPlayingOffset(self.ptr)); } /// Sets the current playing offset of the sound pub fn setPlayingOffset(self: Self, offset: sf.Time) void { sf.c.sfSound_setPlayingOffset(self.ptr, offset.toCSFML()); } /// Tells whether or not this sound is in loop mode pub fn getLoop(self: Self) bool { return sf.c.sfSound_getLoop(self.ptr) != 0; } /// Enable or disable auto loop pub fn setLoop(self: Self, loop: bool) void { sf.c.sfSound_setLoop(self.ptr, if (loop) 1 else 0); } /// Sets the pitch of the sound pub fn getPitch(self: Self) f32 { return sf.c.sfSound_getPitch(self.ptr); } /// Gets the pitch of the sound pub fn setPitch(self: Self, pitch: f32) void { sf.c.sfSound_setPitch(self.ptr, pitch); } /// Sets the volume of the sound pub fn getVolume(self: Self) f32 { return sf.c.sfSound_getVolume(self.ptr); } /// Gets the volume of the sound pub fn setVolume(self: Self, volume: f32) void { sf.c.sfSound_setVolume(self.ptr, volume); } pub const getStatus = @compileError("Function is not implemented yet."); pub const setRelativeToListener = @compileError("Function is not implemented yet."); pub const isRelativeToListener = @compileError("Function is not implemented yet."); pub const setMinDistance = @compileError("Function is not implemented yet."); pub const setAttenuation = @compileError("Function is not implemented yet."); pub const getMinDistance = @compileError("Function is not implemented yet."); pub const getAttenuation = @compileError("Function is not implemented yet."); /// Pointer to the csfml sound ptr: *sf.c.sfSound, };
src/sfml/audio/sound.zig
const std = @import("std"); const builtin = @import("builtin"); /// In concurrent programming, sometimes it is desirable to make sure commonly accessed pieces of /// data are not placed into the same cache line. Updating an atomic value invalidates the whole /// cache line it belongs to, which makes the next access to the same cache line slower for other /// CPU cores. Use `CachePadded` to ensure updating one piece of data doesn't invalidate other /// cached data. /// /// # Size and alignment /// /// Cache lines are assumed to be N bytes long, depending on the architecture: /// /// * On x86-64, aarch64, and powerpc64, N = 128. /// * On arm, mips, mips64, and riscv64, N = 32. /// * On s390x, N = 256. /// * On all others, N = 64. /// /// Note that N is just a reasonable guess and is not guaranteed to match the actual cache line /// length of the machine the program is running on. On modern Intel architectures, spatial /// prefetcher is pulling pairs of 64-byte cache lines at a time, so we pessimistically assume that /// cache lines are 128 bytes long. pub const CACHE_LINE_LENGTH: usize = switch (std.builtin.cpu.arch) { .x86_64, .aarch64, .powerpc64 => 128, .arm, .mips, .mips64, .riscv64 => 32, .s390x => 256, else => 64, }; pub fn loopHint(iterations: usize) void { var i = iterations; while (i != 0) : (i -= 1) { @call(.{ .modifier = .always_inline }, std.atomic.spinLoopHint, .{}); } } pub const Backoff = struct { const SPIN_LIMIT = 6; const YIELD_LIMIT = 10; step: u6 = 0, pub fn init() Backoff { return .{}; } pub fn reset(self: *Backoff) void { self.step = 0; } pub fn spin(self: *Backoff) void { const step = self.step; const spins: usize = @as(usize, 1) << if (step < SPIN_LIMIT) blk: { self.step += 1; break :blk step; } else SPIN_LIMIT; loopHint(spins); } pub fn snooze(self: *Backoff) void { const step = self.step; if (step <= SPIN_LIMIT) { loopHint(@as(usize, 1) << step); } else { yield(); } if (step < YIELD_LIMIT) self.step += 1; } comptime { std.testing.refAllDecls(@This()); } }; // taken from `std.SpinLock` // calling `std.SpinLock.yield()` directly is not possible if we want freestanding to be able to call this easily fn yield() void { // On native windows, SwitchToThread is too expensive, // and yielding for 380-410 iterations was found to be // a nice sweet spot. Posix systems on the other hand, // especially linux, perform better by yielding the thread. switch (builtin.os.tag) { .windows => loopHint(400), .freestanding => { if (comptime @hasDecl(std.os, "sched_yield")) { std.os.sched_yield() catch std.atomic.spinLoopHint(); } else { loopHint(400); } }, else => std.os.sched_yield() catch std.atomic.spinLoopHint(), } } comptime { std.testing.refAllDecls(@This()); }
src/utils.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day25.txt"); const Input = struct { map: [140][140]u8 = undefined, dim_x: usize = 0, dim_y: usize = 0, pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() { _ = allocator; var self = Input{}; errdefer self.deinit(); var lines = std.mem.tokenize(u8, input_text, "\r\n"); while (lines.next()) |line| : (self.dim_y += 1) { self.dim_x = line.len; std.mem.copy(u8, self.map[self.dim_y][0..], line); } return self; } pub fn deinit(self: @This()) void { _ = self; } }; fn part1(input: Input) i64 { var mapA = input.map; var mapB = input.map; var step: i64 = 1; while (true) : (step += 1) { var moved: bool = false; // move > mapB = mapA; var y: usize = 0; while (y < input.dim_y) : (y += 1) { var x: usize = 0; while (x < input.dim_x) : (x += 1) { const x2 = @mod(x + 1, input.dim_x); if (mapA[y][x] == '>' and mapA[y][x2] == '.') { mapB[y][x2] = '>'; mapB[y][x] = '.'; moved = true; } } } // move v mapA = mapB; y = 0; while (y < input.dim_y) : (y += 1) { const y2 = @mod(y + 1, input.dim_y); var x: usize = 0; while (x < input.dim_x) : (x += 1) { if (mapB[y][x] == 'v' and mapB[y2][x] == '.') { mapA[y2][x] = 'v'; mapA[y][x] = '.'; moved = true; } } } if (!moved) return step; } unreachable; } const test_data = \\v...>>.vv> \\.vv>>.vv.. \\>>.>v>...v \\>>v>>.>.v. \\v>v.vv.v.. \\>.>>..v... \\.vv..>.>v. \\v.v..>>v.v \\....v..v.> ; const part1_test_solution: ?i64 = 58; const part1_solution: ?i64 = 378; // Just boilerplate below here, nothing to see fn testPart1() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part1_test_solution) |solution| { try std.testing.expectEqual(solution, part1(test_input)); } var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } pub fn main() !void { try testPart1(); } test "part1" { try testPart1(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day25.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day25.txt"); pub fn main() !void { const result = try part1(data); print("{}\n", .{result}); } fn part1(input : []const u8) !usize { var board = std.ArrayList(u8).init(gpa); defer board.deinit(); var width : usize = 0; { var maybeWidth : ?usize = null; var lines = std.mem.tokenize(input, "\r\n"); while (lines.next()) |line| { if (maybeWidth == null) { maybeWidth = line.len; } else { std.debug.assert(maybeWidth.? == line.len); } for (line) |c| { try board.append(c); } } width = maybeWidth.?; } const height = board.items.len / width; var step : usize = 1; while (true) : (step += 1) { var move = false; var y : usize = 0; while (y < height) : (y += 1) { var x : usize = 0; while (x < width) : (x += 1) { const index = y * width + x; switch (board.items[index]) { '>' => { const next = y * width + (x + 1) % width; if (board.items[next] == '.') { board.items[index] = '-'; board.items[next] = '@'; move = true; } }, else => {}, } } } y = 0; while (y < height) : (y += 1) { var x : usize = 0; while (x < width) : (x += 1) { const index = y * width + x; switch (board.items[index]) { '-' => { board.items[index] = '.'; }, '@' => { board.items[index] = '>'; }, else => {}, } } } y = 0; while (y < height) : (y += 1) { var x : usize = 0; while (x < width) : (x += 1) { const index = y * width + x; switch (board.items[index]) { 'v' => { const next = ((y + 1) % height) * width + x; if (board.items[next] == '.') { board.items[index] = '|'; board.items[next] = '@'; move = true; } }, else => {}, } } } y = 0; while (y < height) : (y += 1) { var x : usize = 0; while (x < width) : (x += 1) { const index = y * width + x; switch (board.items[index]) { '|' => { board.items[index] = '.'; }, '@' => { board.items[index] = 'v'; }, else => {}, } } } if (!move) { return step; } } unreachable; } test "example" { const input = \\v...>>.vv> \\.vv>>.vv.. \\>>.>v>...v \\>>v>>.>.v. \\v>v.vv.v.. \\>.>>..v... \\.vv..>.>v. \\v.v..>>v.v \\....v..v.> ; const result = try part1(input); try std.testing.expect(result == 58); }
src/day25.zig
const std = @import("std"); const Builder = std.build.Builder; const builtin = std.builtin; const assert = std.debug.assert; const sabaton = @import("boot/Sabaton/build.zig"); const flork = @import("subprojects/flork/build.zig"); // zig fmt: off fn qemu_run_aarch64_sabaton(b: *Builder, board_name: []const u8, desc: []const u8) !void { const sabaton_blob = try sabaton.build_blob(b, .aarch64, board_name, "boot/Sabaton/"); const kernel_step = try flork.buildKernel(.{ .builder = b, .arch = .aarch64, }); const kernel_path = b.getInstallPath(kernel_step.install_step.?.dest_dir, kernel_step.out_filename); const command_step = b.step(board_name, desc); const params = &[_][]const u8 { "qemu-system-aarch64", "-M", board_name, "-cpu", "cortex-a57", "-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{sabaton_blob.output_path}), "-fw_cfg", b.fmt("opt/Sabaton/kernel,file={s}", .{kernel_path}), "-m", "4G", "-serial", "stdio", //"-S", "-s", "-smp", "4", "-device", "virtio-gpu-pci", "-device", "ramfb", }; const run_step = b.addSystemCommand(params); run_step.step.dependOn(&sabaton_blob.step); run_step.step.dependOn(&kernel_step.install_step.?.step); command_step.dependOn(&run_step.step); } fn qemu_run_riscv_sabaton(b: *Builder, board_name: []const u8, desc: []const u8, dep: *std.build.LibExeObjStep) void { const command_step = b.step(board_name, desc); const kernel_path = b.getInstallPath(kernel_stepdep.install_step.?.dest_dir, dep.out_filename); const params = &[_][]const u8{ "qemu-system-riscv64", "-M", board_name, "-cpu", "rv64", "-drive", b.fmt("if=pflash,format=raw,file=Sabaton/out/riscv64_{s}.bin,readonly=on", .{board_name}), "-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{kernel_path}), "-m", "4G", "-serial", "stdio", //"-S", "-s", "-d", "int", "-smp", "4", "-device", "virtio-gpu-pci", }; const pad_step = b.addSystemCommand( &[_][]const u8{ "truncate", "-s", "64M", kernel_path, }, ); const run_step = b.addSystemCommand(params); pad_step.step.dependOn(&dep.install_step.?.step); run_step.step.dependOn(&pad_step.step); command_step.dependOn(&run_step.step); } fn qemu_run_image_x86_64(b: *Builder, image_path: []const u8) *std.build.RunStep { const run_params = &[_][]const u8{ "qemu-system-x86_64", "-drive", b.fmt("format=raw,file={s}", .{image_path}), "-debugcon", "stdio", "-vga", "virtio", //"-serial", "stdio", "-m", "4G", "-no-reboot", "-no-shutdown", "-machine", "q35,accel=kvm:whpx:tcg", "-device", "qemu-xhci", "-netdev", "user,id=mynet0", "-device", "e1000,netdev=mynet0", "-smp", "8", //"-d", "int", //"-s", "-S", //"-trace", "ahci_*", }; return b.addSystemCommand(run_params); } fn universal_x86_64_image(b: *Builder, image_path: []const u8, kernel_path: []const u8) *std.build.RunStep { const image_dir = b.fmt("./{s}/universal_image/", .{b.cache_root}); const image_params = &[_][]const u8{ "/bin/sh", "-c", std.mem.concat(b.allocator, u8, &[_][]const u8{ "make -C boot/limine-bin && ", "mkdir -p ", image_dir, " && ", "cp boot/stivale2_image/limine.cfg ", "boot/limine-bin/limine.sys ", "boot/limine-bin/limine-cd.bin ", "boot/limine-bin/limine-eltorito-efi.bin ", image_dir, " && ", "cp ", kernel_path, " ", image_dir, "/flork.elf && ", "xorriso -as mkisofs -b limine-cd.bin ", "-no-emul-boot -boot-load-size 4 -boot-info-table ", "--efi-boot limine-eltorito-efi.bin ", "-efi-boot-part --efi-boot-image --protective-msdos-label ", image_dir, " -o ", image_path, "&&", "boot/limine-bin/limine-install ", image_path, }) catch unreachable, }; return b.addSystemCommand(image_params); } fn limine_target(b: *Builder, command: []const u8, desc: []const u8, image_path: []const u8, dep: *std.build.LibExeObjStep) void { assert(dep.target.cpu_arch.? == .x86_64); const command_step = b.step(command, desc); const run_step = qemu_run_image_x86_64(b, image_path); const kernel_path = b.getInstallPath(dep.install_step.?.dest_dir, dep.out_filename); const image_step = universal_x86_64_image(b, image_path, kernel_path); image_step.step.dependOn(&dep.install_step.?.step); run_step.step.dependOn(&image_step.step); command_step.dependOn(&run_step.step); } // zig fmt: on pub fn build(b: *Builder) !void { // try qemu_run_aarch64_sabaton( // b, // "raspi3", // "(WIP) Run aarch64 kernel with Sabaton stivale2 on the raspi3 board", // ); try qemu_run_aarch64_sabaton( b, "virt", "Run aarch64 kernel with Sabaton stivale2 on the virt board", ); // qemu_run_riscv_sabaton(b, // "riscv-virt", // "(WIP) Run risc-v kernel with Sabaton stivale2 on the virt board", // build_kernel(b, builtin.Arch.riscv64, "stivale2"), // ); limine_target( b, "x86_64-stivale2", "Run x86_64 kernel with limine stivale2", b.fmt("{s}/stivale2.img", .{b.cache_root}), try flork.buildKernel(.{ .builder = b, .arch = .x86_64, }), ); }
build.zig
pub const XK_MISCELLANY = ""; pub const XK_XKB_KEYS = ""; pub const XK_LATIN1 = ""; pub const XK_LATIN2 = ""; pub const XK_LATIN3 = ""; pub const XK_LATIN4 = ""; pub const XK_GREEK = ""; pub const XK_VoidSymbol = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFF, .hexadecimal); pub const XK_BackSpace = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF08, .hexadecimal); pub const XK_Tab = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF09, .hexadecimal); pub const XK_Linefeed = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF0A, .hexadecimal); pub const XK_Clear = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF0B, .hexadecimal); pub const XK_Return = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF0D, .hexadecimal); pub const XK_Pause = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF13, .hexadecimal); pub const XK_Scroll_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF14, .hexadecimal); pub const XK_Sys_Req = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF15, .hexadecimal); pub const XK_Escape = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF1B, .hexadecimal); pub const XK_Delete = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF, .hexadecimal); pub const XK_Multi_key = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF20, .hexadecimal); pub const XK_SingleCandidate = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF3C, .hexadecimal); pub const XK_MultipleCandidate = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF3D, .hexadecimal); pub const XK_PreviousCandidate = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF3E, .hexadecimal); pub const XK_Kanji = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF21, .hexadecimal); pub const XK_Muhenkan = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF22, .hexadecimal); pub const XK_Henkan_Mode = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF23, .hexadecimal); pub const XK_Henkan = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF23, .hexadecimal); pub const XK_Romaji = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF24, .hexadecimal); pub const XK_Hiragana = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF25, .hexadecimal); pub const XK_Katakana = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF26, .hexadecimal); pub const XK_Hiragana_Katakana = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF27, .hexadecimal); pub const XK_Zenkaku = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF28, .hexadecimal); pub const XK_Hankaku = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF29, .hexadecimal); pub const XK_Zenkaku_Hankaku = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2A, .hexadecimal); pub const XK_Touroku = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2B, .hexadecimal); pub const XK_Massyo = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2C, .hexadecimal); pub const XK_Kana_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2D, .hexadecimal); pub const XK_Kana_Shift = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2E, .hexadecimal); pub const XK_Eisu_Shift = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF2F, .hexadecimal); pub const XK_Eisu_toggle = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF30, .hexadecimal); pub const XK_Zen_Koho = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF3D, .hexadecimal); pub const XK_Mae_Koho = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF3E, .hexadecimal); pub const XK_Home = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF50, .hexadecimal); pub const XK_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF51, .hexadecimal); pub const XK_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF52, .hexadecimal); pub const XK_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF53, .hexadecimal); pub const XK_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF54, .hexadecimal); pub const XK_Prior = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF55, .hexadecimal); pub const XK_Page_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF55, .hexadecimal); pub const XK_Next = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF56, .hexadecimal); pub const XK_Page_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF56, .hexadecimal); pub const XK_End = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF57, .hexadecimal); pub const XK_Begin = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF58, .hexadecimal); pub const XK_Select = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF60, .hexadecimal); pub const XK_Print = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF61, .hexadecimal); pub const XK_Execute = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF62, .hexadecimal); pub const XK_Insert = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF63, .hexadecimal); pub const XK_Undo = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF65, .hexadecimal); pub const XK_Redo = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF66, .hexadecimal); pub const XK_Menu = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF67, .hexadecimal); pub const XK_Find = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF68, .hexadecimal); pub const XK_Cancel = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF69, .hexadecimal); pub const XK_Help = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF6A, .hexadecimal); pub const XK_Break = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF6B, .hexadecimal); pub const XK_Mode_switch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF7E, .hexadecimal); pub const XK_script_switch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF7E, .hexadecimal); pub const XK_Num_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF7F, .hexadecimal); pub const XK_KP_Space = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF80, .hexadecimal); pub const XK_KP_Tab = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF89, .hexadecimal); pub const XK_KP_Enter = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF8D, .hexadecimal); pub const XK_KP_F1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF91, .hexadecimal); pub const XK_KP_F2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF92, .hexadecimal); pub const XK_KP_F3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF93, .hexadecimal); pub const XK_KP_F4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF94, .hexadecimal); pub const XK_KP_Home = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF95, .hexadecimal); pub const XK_KP_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF96, .hexadecimal); pub const XK_KP_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF97, .hexadecimal); pub const XK_KP_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF98, .hexadecimal); pub const XK_KP_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF99, .hexadecimal); pub const XK_KP_Prior = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9A, .hexadecimal); pub const XK_KP_Page_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9A, .hexadecimal); pub const XK_KP_Next = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9B, .hexadecimal); pub const XK_KP_Page_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9B, .hexadecimal); pub const XK_KP_End = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9C, .hexadecimal); pub const XK_KP_Begin = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9D, .hexadecimal); pub const XK_KP_Insert = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9E, .hexadecimal); pub const XK_KP_Delete = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF9F, .hexadecimal); pub const XK_KP_Equal = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFBD, .hexadecimal); pub const XK_KP_Multiply = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAA, .hexadecimal); pub const XK_KP_Add = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAB, .hexadecimal); pub const XK_KP_Separator = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAC, .hexadecimal); pub const XK_KP_Subtract = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAD, .hexadecimal); pub const XK_KP_Decimal = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAE, .hexadecimal); pub const XK_KP_Divide = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFAF, .hexadecimal); pub const XK_KP_0 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB0, .hexadecimal); pub const XK_KP_1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB1, .hexadecimal); pub const XK_KP_2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB2, .hexadecimal); pub const XK_KP_3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB3, .hexadecimal); pub const XK_KP_4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB4, .hexadecimal); pub const XK_KP_5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB5, .hexadecimal); pub const XK_KP_6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB6, .hexadecimal); pub const XK_KP_7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB7, .hexadecimal); pub const XK_KP_8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB8, .hexadecimal); pub const XK_KP_9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFB9, .hexadecimal); pub const XK_F1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFBE, .hexadecimal); pub const XK_F2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFBF, .hexadecimal); pub const XK_F3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC0, .hexadecimal); pub const XK_F4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC1, .hexadecimal); pub const XK_F5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC2, .hexadecimal); pub const XK_F6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC3, .hexadecimal); pub const XK_F7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC4, .hexadecimal); pub const XK_F8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC5, .hexadecimal); pub const XK_F9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC6, .hexadecimal); pub const XK_F10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC7, .hexadecimal); pub const XK_F11 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC8, .hexadecimal); pub const XK_L1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC8, .hexadecimal); pub const XK_F12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC9, .hexadecimal); pub const XK_L2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFC9, .hexadecimal); pub const XK_F13 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCA, .hexadecimal); pub const XK_L3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCA, .hexadecimal); pub const XK_F14 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCB, .hexadecimal); pub const XK_L4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCB, .hexadecimal); pub const XK_F15 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCC, .hexadecimal); pub const XK_L5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCC, .hexadecimal); pub const XK_F16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCD, .hexadecimal); pub const XK_L6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCD, .hexadecimal); pub const XK_F17 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCE, .hexadecimal); pub const XK_L7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCE, .hexadecimal); pub const XK_F18 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCF, .hexadecimal); pub const XK_L8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFCF, .hexadecimal); pub const XK_F19 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD0, .hexadecimal); pub const XK_L9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD0, .hexadecimal); pub const XK_F20 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD1, .hexadecimal); pub const XK_L10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD1, .hexadecimal); pub const XK_F21 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD2, .hexadecimal); pub const XK_R1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD2, .hexadecimal); pub const XK_F22 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD3, .hexadecimal); pub const XK_R2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD3, .hexadecimal); pub const XK_F23 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD4, .hexadecimal); pub const XK_R3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD4, .hexadecimal); pub const XK_F24 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD5, .hexadecimal); pub const XK_R4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD5, .hexadecimal); pub const XK_F25 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD6, .hexadecimal); pub const XK_R5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD6, .hexadecimal); pub const XK_F26 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD7, .hexadecimal); pub const XK_R6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD7, .hexadecimal); pub const XK_F27 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD8, .hexadecimal); pub const XK_R7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD8, .hexadecimal); pub const XK_F28 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD9, .hexadecimal); pub const XK_R8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFD9, .hexadecimal); pub const XK_F29 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDA, .hexadecimal); pub const XK_R9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDA, .hexadecimal); pub const XK_F30 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDB, .hexadecimal); pub const XK_R10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDB, .hexadecimal); pub const XK_F31 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDC, .hexadecimal); pub const XK_R11 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDC, .hexadecimal); pub const XK_F32 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDD, .hexadecimal); pub const XK_R12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDD, .hexadecimal); pub const XK_F33 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDE, .hexadecimal); pub const XK_R13 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDE, .hexadecimal); pub const XK_F34 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDF, .hexadecimal); pub const XK_R14 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFDF, .hexadecimal); pub const XK_F35 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE0, .hexadecimal); pub const XK_R15 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE0, .hexadecimal); pub const XK_Shift_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE1, .hexadecimal); pub const XK_Shift_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE2, .hexadecimal); pub const XK_Control_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE3, .hexadecimal); pub const XK_Control_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE4, .hexadecimal); pub const XK_Caps_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE5, .hexadecimal); pub const XK_Shift_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE6, .hexadecimal); pub const XK_Meta_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE7, .hexadecimal); pub const XK_Meta_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE8, .hexadecimal); pub const XK_Alt_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFE9, .hexadecimal); pub const XK_Alt_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFEA, .hexadecimal); pub const XK_Super_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFEB, .hexadecimal); pub const XK_Super_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFEC, .hexadecimal); pub const XK_Hyper_L = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFED, .hexadecimal); pub const XK_Hyper_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFEE, .hexadecimal); pub const XK_ISO_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE01, .hexadecimal); pub const XK_ISO_Level2_Latch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE02, .hexadecimal); pub const XK_ISO_Level3_Shift = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE03, .hexadecimal); pub const XK_ISO_Level3_Latch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE04, .hexadecimal); pub const XK_ISO_Level3_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE05, .hexadecimal); pub const XK_ISO_Group_Shift = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF7E, .hexadecimal); pub const XK_ISO_Group_Latch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE06, .hexadecimal); pub const XK_ISO_Group_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE07, .hexadecimal); pub const XK_ISO_Next_Group = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE08, .hexadecimal); pub const XK_ISO_Next_Group_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE09, .hexadecimal); pub const XK_ISO_Prev_Group = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0A, .hexadecimal); pub const XK_ISO_Prev_Group_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0B, .hexadecimal); pub const XK_ISO_First_Group = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0C, .hexadecimal); pub const XK_ISO_First_Group_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0D, .hexadecimal); pub const XK_ISO_Last_Group = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0E, .hexadecimal); pub const XK_ISO_Last_Group_Lock = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE0F, .hexadecimal); pub const XK_ISO_Left_Tab = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE20, .hexadecimal); pub const XK_ISO_Move_Line_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE21, .hexadecimal); pub const XK_ISO_Move_Line_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE22, .hexadecimal); pub const XK_ISO_Partial_Line_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE23, .hexadecimal); pub const XK_ISO_Partial_Line_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE24, .hexadecimal); pub const XK_ISO_Partial_Space_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE25, .hexadecimal); pub const XK_ISO_Partial_Space_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE26, .hexadecimal); pub const XK_ISO_Set_Margin_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE27, .hexadecimal); pub const XK_ISO_Set_Margin_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE28, .hexadecimal); pub const XK_ISO_Release_Margin_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE29, .hexadecimal); pub const XK_ISO_Release_Margin_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2A, .hexadecimal); pub const XK_ISO_Release_Both_Margins = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2B, .hexadecimal); pub const XK_ISO_Fast_Cursor_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2C, .hexadecimal); pub const XK_ISO_Fast_Cursor_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2D, .hexadecimal); pub const XK_ISO_Fast_Cursor_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2E, .hexadecimal); pub const XK_ISO_Fast_Cursor_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE2F, .hexadecimal); pub const XK_ISO_Continuous_Underline = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE30, .hexadecimal); pub const XK_ISO_Discontinuous_Underline = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE31, .hexadecimal); pub const XK_ISO_Emphasize = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE32, .hexadecimal); pub const XK_ISO_Center_Object = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE33, .hexadecimal); pub const XK_ISO_Enter = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE34, .hexadecimal); pub const XK_dead_grave = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE50, .hexadecimal); pub const XK_dead_acute = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE51, .hexadecimal); pub const XK_dead_circumflex = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE52, .hexadecimal); pub const XK_dead_tilde = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE53, .hexadecimal); pub const XK_dead_macron = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE54, .hexadecimal); pub const XK_dead_breve = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE55, .hexadecimal); pub const XK_dead_abovedot = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE56, .hexadecimal); pub const XK_dead_diaeresis = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE57, .hexadecimal); pub const XK_dead_abovering = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE58, .hexadecimal); pub const XK_dead_doubleacute = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE59, .hexadecimal); pub const XK_dead_caron = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5A, .hexadecimal); pub const XK_dead_cedilla = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5B, .hexadecimal); pub const XK_dead_ogonek = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5C, .hexadecimal); pub const XK_dead_iota = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5D, .hexadecimal); pub const XK_dead_voiced_sound = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5E, .hexadecimal); pub const XK_dead_semivoiced_sound = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE5F, .hexadecimal); pub const XK_dead_belowdot = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE60, .hexadecimal); pub const XK_First_Virtual_Screen = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFED0, .hexadecimal); pub const XK_Prev_Virtual_Screen = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFED1, .hexadecimal); pub const XK_Next_Virtual_Screen = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFED2, .hexadecimal); pub const XK_Last_Virtual_Screen = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFED4, .hexadecimal); pub const XK_Terminate_Server = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFED5, .hexadecimal); pub const XK_AccessX_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE70, .hexadecimal); pub const XK_AccessX_Feedback_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE71, .hexadecimal); pub const XK_RepeatKeys_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE72, .hexadecimal); pub const XK_SlowKeys_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE73, .hexadecimal); pub const XK_BounceKeys_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE74, .hexadecimal); pub const XK_StickyKeys_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE75, .hexadecimal); pub const XK_MouseKeys_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE76, .hexadecimal); pub const XK_MouseKeys_Accel_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE77, .hexadecimal); pub const XK_Overlay1_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE78, .hexadecimal); pub const XK_Overlay2_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE79, .hexadecimal); pub const XK_AudibleBell_Enable = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFE7A, .hexadecimal); pub const XK_Pointer_Left = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE0, .hexadecimal); pub const XK_Pointer_Right = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE1, .hexadecimal); pub const XK_Pointer_Up = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE2, .hexadecimal); pub const XK_Pointer_Down = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE3, .hexadecimal); pub const XK_Pointer_UpLeft = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE4, .hexadecimal); pub const XK_Pointer_UpRight = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE5, .hexadecimal); pub const XK_Pointer_DownLeft = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE6, .hexadecimal); pub const XK_Pointer_DownRight = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE7, .hexadecimal); pub const XK_Pointer_Button_Dflt = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE8, .hexadecimal); pub const XK_Pointer_Button1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEE9, .hexadecimal); pub const XK_Pointer_Button2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEEA, .hexadecimal); pub const XK_Pointer_Button3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEEB, .hexadecimal); pub const XK_Pointer_Button4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEEC, .hexadecimal); pub const XK_Pointer_Button5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEED, .hexadecimal); pub const XK_Pointer_DblClick_Dflt = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEEE, .hexadecimal); pub const XK_Pointer_DblClick1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEEF, .hexadecimal); pub const XK_Pointer_DblClick2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF0, .hexadecimal); pub const XK_Pointer_DblClick3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF1, .hexadecimal); pub const XK_Pointer_DblClick4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF2, .hexadecimal); pub const XK_Pointer_DblClick5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF3, .hexadecimal); pub const XK_Pointer_Drag_Dflt = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF4, .hexadecimal); pub const XK_Pointer_Drag1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF5, .hexadecimal); pub const XK_Pointer_Drag2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF6, .hexadecimal); pub const XK_Pointer_Drag3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF7, .hexadecimal); pub const XK_Pointer_Drag4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF8, .hexadecimal); pub const XK_Pointer_Drag5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEFD, .hexadecimal); pub const XK_Pointer_EnableKeys = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEF9, .hexadecimal); pub const XK_Pointer_Accelerate = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEFA, .hexadecimal); pub const XK_Pointer_DfltBtnNext = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEFB, .hexadecimal); pub const XK_Pointer_DfltBtnPrev = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFEFC, .hexadecimal); pub const XK_space = @as(c_int, 0x020); pub const XK_exclam = @as(c_int, 0x021); pub const XK_quotedbl = @as(c_int, 0x022); pub const XK_numbersign = @as(c_int, 0x023); pub const XK_dollar = @as(c_int, 0x024); pub const XK_percent = @as(c_int, 0x025); pub const XK_ampersand = @as(c_int, 0x026); pub const XK_apostrophe = @as(c_int, 0x027); pub const XK_quoteright = @as(c_int, 0x027); pub const XK_parenleft = @as(c_int, 0x028); pub const XK_parenright = @as(c_int, 0x029); pub const XK_asterisk = @as(c_int, 0x02a); pub const XK_plus = @as(c_int, 0x02b); pub const XK_comma = @as(c_int, 0x02c); pub const XK_minus = @as(c_int, 0x02d); pub const XK_period = @as(c_int, 0x02e); pub const XK_slash = @as(c_int, 0x02f); pub const XK_0 = @as(c_int, 0x030); pub const XK_1 = @as(c_int, 0x031); pub const XK_2 = @as(c_int, 0x032); pub const XK_3 = @as(c_int, 0x033); pub const XK_4 = @as(c_int, 0x034); pub const XK_5 = @as(c_int, 0x035); pub const XK_6 = @as(c_int, 0x036); pub const XK_7 = @as(c_int, 0x037); pub const XK_8 = @as(c_int, 0x038); pub const XK_9 = @as(c_int, 0x039); pub const XK_colon = @as(c_int, 0x03a); pub const XK_semicolon = @as(c_int, 0x03b); pub const XK_less = @as(c_int, 0x03c); pub const XK_equal = @as(c_int, 0x03d); pub const XK_greater = @as(c_int, 0x03e); pub const XK_question = @as(c_int, 0x03f); pub const XK_at = @as(c_int, 0x040); pub const XK_A = @as(c_int, 0x041); pub const XK_B = @as(c_int, 0x042); pub const XK_C = @as(c_int, 0x043); pub const XK_D = @as(c_int, 0x044); pub const XK_E = @as(c_int, 0x045); pub const XK_F = @as(c_int, 0x046); pub const XK_G = @as(c_int, 0x047); pub const XK_H = @as(c_int, 0x048); pub const XK_I = @as(c_int, 0x049); pub const XK_J = @as(c_int, 0x04a); pub const XK_K = @as(c_int, 0x04b); pub const XK_L = @as(c_int, 0x04c); pub const XK_M = @as(c_int, 0x04d); pub const XK_N = @as(c_int, 0x04e); pub const XK_O = @as(c_int, 0x04f); pub const XK_P = @as(c_int, 0x050); pub const XK_Q = @as(c_int, 0x051); pub const XK_R = @as(c_int, 0x052); pub const XK_S = @as(c_int, 0x053); pub const XK_T = @as(c_int, 0x054); pub const XK_U = @as(c_int, 0x055); pub const XK_V = @as(c_int, 0x056); pub const XK_W = @as(c_int, 0x057); pub const XK_X = @as(c_int, 0x058); pub const XK_Y = @as(c_int, 0x059); pub const XK_Z = @as(c_int, 0x05a); pub const XK_bracketleft = @as(c_int, 0x05b); pub const XK_backslash = @as(c_int, 0x05c); pub const XK_bracketright = @as(c_int, 0x05d); pub const XK_asciicircum = @as(c_int, 0x05e); pub const XK_underscore = @as(c_int, 0x05f); pub const XK_grave = @as(c_int, 0x060); pub const XK_quoteleft = @as(c_int, 0x060); pub const XK_a = @as(c_int, 0x061); pub const XK_b = @as(c_int, 0x062); pub const XK_c = @as(c_int, 0x063); pub const XK_d = @as(c_int, 0x064); pub const XK_e = @as(c_int, 0x065); pub const XK_f = @as(c_int, 0x066); pub const XK_g = @as(c_int, 0x067); pub const XK_h = @as(c_int, 0x068); pub const XK_i = @as(c_int, 0x069); pub const XK_j = @as(c_int, 0x06a); pub const XK_k = @as(c_int, 0x06b); pub const XK_l = @as(c_int, 0x06c); pub const XK_m = @as(c_int, 0x06d); pub const XK_n = @as(c_int, 0x06e); pub const XK_o = @as(c_int, 0x06f); pub const XK_p = @as(c_int, 0x070); pub const XK_q = @as(c_int, 0x071); pub const XK_r = @as(c_int, 0x072); pub const XK_s = @as(c_int, 0x073); pub const XK_t = @as(c_int, 0x074); pub const XK_u = @as(c_int, 0x075); pub const XK_v = @as(c_int, 0x076); pub const XK_w = @as(c_int, 0x077); pub const XK_x = @as(c_int, 0x078); pub const XK_y = @as(c_int, 0x079); pub const XK_z = @as(c_int, 0x07a); pub const XK_braceleft = @as(c_int, 0x07b); pub const XK_bar = @as(c_int, 0x07c); pub const XK_braceright = @as(c_int, 0x07d); pub const XK_asciitilde = @as(c_int, 0x07e); pub const XK_nobreakspace = @as(c_int, 0x0a0); pub const XK_exclamdown = @as(c_int, 0x0a1); pub const XK_cent = @as(c_int, 0x0a2); pub const XK_sterling = @as(c_int, 0x0a3); pub const XK_currency = @as(c_int, 0x0a4); pub const XK_yen = @as(c_int, 0x0a5); pub const XK_brokenbar = @as(c_int, 0x0a6); pub const XK_section = @as(c_int, 0x0a7); pub const XK_diaeresis = @as(c_int, 0x0a8); pub const XK_copyright = @as(c_int, 0x0a9); pub const XK_ordfeminine = @as(c_int, 0x0aa); pub const XK_guillemotleft = @as(c_int, 0x0ab); pub const XK_notsign = @as(c_int, 0x0ac); pub const XK_hyphen = @as(c_int, 0x0ad); pub const XK_registered = @as(c_int, 0x0ae); pub const XK_macron = @as(c_int, 0x0af); pub const XK_degree = @as(c_int, 0x0b0); pub const XK_plusminus = @as(c_int, 0x0b1); pub const XK_twosuperior = @as(c_int, 0x0b2); pub const XK_threesuperior = @as(c_int, 0x0b3); pub const XK_acute = @as(c_int, 0x0b4); pub const XK_mu = @as(c_int, 0x0b5); pub const XK_paragraph = @as(c_int, 0x0b6); pub const XK_periodcentered = @as(c_int, 0x0b7); pub const XK_cedilla = @as(c_int, 0x0b8); pub const XK_onesuperior = @as(c_int, 0x0b9); pub const XK_masculine = @as(c_int, 0x0ba); pub const XK_guillemotright = @as(c_int, 0x0bb); pub const XK_onequarter = @as(c_int, 0x0bc); pub const XK_onehalf = @as(c_int, 0x0bd); pub const XK_threequarters = @as(c_int, 0x0be); pub const XK_questiondown = @as(c_int, 0x0bf); pub const XK_Agrave = @as(c_int, 0x0c0); pub const XK_Aacute = @as(c_int, 0x0c1); pub const XK_Acircumflex = @as(c_int, 0x0c2); pub const XK_Atilde = @as(c_int, 0x0c3); pub const XK_Adiaeresis = @as(c_int, 0x0c4); pub const XK_Aring = @as(c_int, 0x0c5); pub const XK_AE = @as(c_int, 0x0c6); pub const XK_Ccedilla = @as(c_int, 0x0c7); pub const XK_Egrave = @as(c_int, 0x0c8); pub const XK_Eacute = @as(c_int, 0x0c9); pub const XK_Ecircumflex = @as(c_int, 0x0ca); pub const XK_Ediaeresis = @as(c_int, 0x0cb); pub const XK_Igrave = @as(c_int, 0x0cc); pub const XK_Iacute = @as(c_int, 0x0cd); pub const XK_Icircumflex = @as(c_int, 0x0ce); pub const XK_Idiaeresis = @as(c_int, 0x0cf); pub const XK_ETH = @as(c_int, 0x0d0); pub const XK_Eth = @as(c_int, 0x0d0); pub const XK_Ntilde = @as(c_int, 0x0d1); pub const XK_Ograve = @as(c_int, 0x0d2); pub const XK_Oacute = @as(c_int, 0x0d3); pub const XK_Ocircumflex = @as(c_int, 0x0d4); pub const XK_Otilde = @as(c_int, 0x0d5); pub const XK_Odiaeresis = @as(c_int, 0x0d6); pub const XK_multiply = @as(c_int, 0x0d7); pub const XK_Ooblique = @as(c_int, 0x0d8); pub const XK_Ugrave = @as(c_int, 0x0d9); pub const XK_Uacute = @as(c_int, 0x0da); pub const XK_Ucircumflex = @as(c_int, 0x0db); pub const XK_Udiaeresis = @as(c_int, 0x0dc); pub const XK_Yacute = @as(c_int, 0x0dd); pub const XK_THORN = @as(c_int, 0x0de); pub const XK_Thorn = @as(c_int, 0x0de); pub const XK_ssharp = @as(c_int, 0x0df); pub const XK_agrave = @as(c_int, 0x0e0); pub const XK_aacute = @as(c_int, 0x0e1); pub const XK_acircumflex = @as(c_int, 0x0e2); pub const XK_atilde = @as(c_int, 0x0e3); pub const XK_adiaeresis = @as(c_int, 0x0e4); pub const XK_aring = @as(c_int, 0x0e5); pub const XK_ae = @as(c_int, 0x0e6); pub const XK_ccedilla = @as(c_int, 0x0e7); pub const XK_egrave = @as(c_int, 0x0e8); pub const XK_eacute = @as(c_int, 0x0e9); pub const XK_ecircumflex = @as(c_int, 0x0ea); pub const XK_ediaeresis = @as(c_int, 0x0eb); pub const XK_igrave = @as(c_int, 0x0ec); pub const XK_iacute = @as(c_int, 0x0ed); pub const XK_icircumflex = @as(c_int, 0x0ee); pub const XK_idiaeresis = @as(c_int, 0x0ef); pub const XK_eth = @as(c_int, 0x0f0); pub const XK_ntilde = @as(c_int, 0x0f1); pub const XK_ograve = @as(c_int, 0x0f2); pub const XK_oacute = @as(c_int, 0x0f3); pub const XK_ocircumflex = @as(c_int, 0x0f4); pub const XK_otilde = @as(c_int, 0x0f5); pub const XK_odiaeresis = @as(c_int, 0x0f6); pub const XK_division = @as(c_int, 0x0f7); pub const XK_oslash = @as(c_int, 0x0f8); pub const XK_ugrave = @as(c_int, 0x0f9); pub const XK_uacute = @as(c_int, 0x0fa); pub const XK_ucircumflex = @as(c_int, 0x0fb); pub const XK_udiaeresis = @as(c_int, 0x0fc); pub const XK_yacute = @as(c_int, 0x0fd); pub const XK_thorn = @as(c_int, 0x0fe); pub const XK_ydiaeresis = @as(c_int, 0x0ff); pub const XK_Aogonek = @as(c_int, 0x1a1); pub const XK_breve = @as(c_int, 0x1a2); pub const XK_Lstroke = @as(c_int, 0x1a3); pub const XK_Lcaron = @as(c_int, 0x1a5); pub const XK_Sacute = @as(c_int, 0x1a6); pub const XK_Scaron = @as(c_int, 0x1a9); pub const XK_Scedilla = @as(c_int, 0x1aa); pub const XK_Tcaron = @as(c_int, 0x1ab); pub const XK_Zacute = @as(c_int, 0x1ac); pub const XK_Zcaron = @as(c_int, 0x1ae); pub const XK_Zabovedot = @as(c_int, 0x1af); pub const XK_aogonek = @as(c_int, 0x1b1); pub const XK_ogonek = @as(c_int, 0x1b2); pub const XK_lstroke = @as(c_int, 0x1b3); pub const XK_lcaron = @as(c_int, 0x1b5); pub const XK_sacute = @as(c_int, 0x1b6); pub const XK_caron = @as(c_int, 0x1b7); pub const XK_scaron = @as(c_int, 0x1b9); pub const XK_scedilla = @as(c_int, 0x1ba); pub const XK_tcaron = @as(c_int, 0x1bb); pub const XK_zacute = @as(c_int, 0x1bc); pub const XK_doubleacute = @as(c_int, 0x1bd); pub const XK_zcaron = @as(c_int, 0x1be); pub const XK_zabovedot = @as(c_int, 0x1bf); pub const XK_Racute = @as(c_int, 0x1c0); pub const XK_Abreve = @as(c_int, 0x1c3); pub const XK_Lacute = @as(c_int, 0x1c5); pub const XK_Cacute = @as(c_int, 0x1c6); pub const XK_Ccaron = @as(c_int, 0x1c8); pub const XK_Eogonek = @as(c_int, 0x1ca); pub const XK_Ecaron = @as(c_int, 0x1cc); pub const XK_Dcaron = @as(c_int, 0x1cf); pub const XK_Dstroke = @as(c_int, 0x1d0); pub const XK_Nacute = @as(c_int, 0x1d1); pub const XK_Ncaron = @as(c_int, 0x1d2); pub const XK_Odoubleacute = @as(c_int, 0x1d5); pub const XK_Rcaron = @as(c_int, 0x1d8); pub const XK_Uring = @as(c_int, 0x1d9); pub const XK_Udoubleacute = @as(c_int, 0x1db); pub const XK_Tcedilla = @as(c_int, 0x1de); pub const XK_racute = @as(c_int, 0x1e0); pub const XK_abreve = @as(c_int, 0x1e3); pub const XK_lacute = @as(c_int, 0x1e5); pub const XK_cacute = @as(c_int, 0x1e6); pub const XK_ccaron = @as(c_int, 0x1e8); pub const XK_eogonek = @as(c_int, 0x1ea); pub const XK_ecaron = @as(c_int, 0x1ec); pub const XK_dcaron = @as(c_int, 0x1ef); pub const XK_dstroke = @as(c_int, 0x1f0); pub const XK_nacute = @as(c_int, 0x1f1); pub const XK_ncaron = @as(c_int, 0x1f2); pub const XK_odoubleacute = @as(c_int, 0x1f5); pub const XK_udoubleacute = @as(c_int, 0x1fb); pub const XK_rcaron = @as(c_int, 0x1f8); pub const XK_uring = @as(c_int, 0x1f9); pub const XK_tcedilla = @as(c_int, 0x1fe); pub const XK_abovedot = @as(c_int, 0x1ff); pub const XK_Hstroke = @as(c_int, 0x2a1); pub const XK_Hcircumflex = @as(c_int, 0x2a6); pub const XK_Iabovedot = @as(c_int, 0x2a9); pub const XK_Gbreve = @as(c_int, 0x2ab); pub const XK_Jcircumflex = @as(c_int, 0x2ac); pub const XK_hstroke = @as(c_int, 0x2b1); pub const XK_hcircumflex = @as(c_int, 0x2b6); pub const XK_idotless = @as(c_int, 0x2b9); pub const XK_gbreve = @as(c_int, 0x2bb); pub const XK_jcircumflex = @as(c_int, 0x2bc); pub const XK_Cabovedot = @as(c_int, 0x2c5); pub const XK_Ccircumflex = @as(c_int, 0x2c6); pub const XK_Gabovedot = @as(c_int, 0x2d5); pub const XK_Gcircumflex = @as(c_int, 0x2d8); pub const XK_Ubreve = @as(c_int, 0x2dd); pub const XK_Scircumflex = @as(c_int, 0x2de); pub const XK_cabovedot = @as(c_int, 0x2e5); pub const XK_ccircumflex = @as(c_int, 0x2e6); pub const XK_gabovedot = @as(c_int, 0x2f5); pub const XK_gcircumflex = @as(c_int, 0x2f8); pub const XK_ubreve = @as(c_int, 0x2fd); pub const XK_scircumflex = @as(c_int, 0x2fe); pub const XK_kra = @as(c_int, 0x3a2); pub const XK_kappa = @as(c_int, 0x3a2); pub const XK_Rcedilla = @as(c_int, 0x3a3); pub const XK_Itilde = @as(c_int, 0x3a5); pub const XK_Lcedilla = @as(c_int, 0x3a6); pub const XK_Emacron = @as(c_int, 0x3aa); pub const XK_Gcedilla = @as(c_int, 0x3ab); pub const XK_Tslash = @as(c_int, 0x3ac); pub const XK_rcedilla = @as(c_int, 0x3b3); pub const XK_itilde = @as(c_int, 0x3b5); pub const XK_lcedilla = @as(c_int, 0x3b6); pub const XK_emacron = @as(c_int, 0x3ba); pub const XK_gcedilla = @as(c_int, 0x3bb); pub const XK_tslash = @as(c_int, 0x3bc); pub const XK_ENG = @as(c_int, 0x3bd); pub const XK_eng = @as(c_int, 0x3bf); pub const XK_Amacron = @as(c_int, 0x3c0); pub const XK_Iogonek = @as(c_int, 0x3c7); pub const XK_Eabovedot = @as(c_int, 0x3cc); pub const XK_Imacron = @as(c_int, 0x3cf); pub const XK_Ncedilla = @as(c_int, 0x3d1); pub const XK_Omacron = @as(c_int, 0x3d2); pub const XK_Kcedilla = @as(c_int, 0x3d3); pub const XK_Uogonek = @as(c_int, 0x3d9); pub const XK_Utilde = @as(c_int, 0x3dd); pub const XK_Umacron = @as(c_int, 0x3de); pub const XK_amacron = @as(c_int, 0x3e0); pub const XK_iogonek = @as(c_int, 0x3e7); pub const XK_eabovedot = @as(c_int, 0x3ec); pub const XK_imacron = @as(c_int, 0x3ef); pub const XK_ncedilla = @as(c_int, 0x3f1); pub const XK_omacron = @as(c_int, 0x3f2); pub const XK_kcedilla = @as(c_int, 0x3f3); pub const XK_uogonek = @as(c_int, 0x3f9); pub const XK_utilde = @as(c_int, 0x3fd); pub const XK_umacron = @as(c_int, 0x3fe); pub const XK_Greek_ALPHAaccent = @as(c_int, 0x7a1); pub const XK_Greek_EPSILONaccent = @as(c_int, 0x7a2); pub const XK_Greek_ETAaccent = @as(c_int, 0x7a3); pub const XK_Greek_IOTAaccent = @as(c_int, 0x7a4); pub const XK_Greek_IOTAdieresis = @as(c_int, 0x7a5); pub const XK_Greek_OMICRONaccent = @as(c_int, 0x7a7); pub const XK_Greek_UPSILONaccent = @as(c_int, 0x7a8); pub const XK_Greek_UPSILONdieresis = @as(c_int, 0x7a9); pub const XK_Greek_OMEGAaccent = @as(c_int, 0x7ab); pub const XK_Greek_accentdieresis = @as(c_int, 0x7ae); pub const XK_Greek_horizbar = @as(c_int, 0x7af); pub const XK_Greek_alphaaccent = @as(c_int, 0x7b1); pub const XK_Greek_epsilonaccent = @as(c_int, 0x7b2); pub const XK_Greek_etaaccent = @as(c_int, 0x7b3); pub const XK_Greek_iotaaccent = @as(c_int, 0x7b4); pub const XK_Greek_iotadieresis = @as(c_int, 0x7b5); pub const XK_Greek_iotaaccentdieresis = @as(c_int, 0x7b6); pub const XK_Greek_omicronaccent = @as(c_int, 0x7b7); pub const XK_Greek_upsilonaccent = @as(c_int, 0x7b8); pub const XK_Greek_upsilondieresis = @as(c_int, 0x7b9); pub const XK_Greek_upsilonaccentdieresis = @as(c_int, 0x7ba); pub const XK_Greek_omegaaccent = @as(c_int, 0x7bb); pub const XK_Greek_ALPHA = @as(c_int, 0x7c1); pub const XK_Greek_BETA = @as(c_int, 0x7c2); pub const XK_Greek_GAMMA = @as(c_int, 0x7c3); pub const XK_Greek_DELTA = @as(c_int, 0x7c4); pub const XK_Greek_EPSILON = @as(c_int, 0x7c5); pub const XK_Greek_ZETA = @as(c_int, 0x7c6); pub const XK_Greek_ETA = @as(c_int, 0x7c7); pub const XK_Greek_THETA = @as(c_int, 0x7c8); pub const XK_Greek_IOTA = @as(c_int, 0x7c9); pub const XK_Greek_KAPPA = @as(c_int, 0x7ca); pub const XK_Greek_LAMDA = @as(c_int, 0x7cb); pub const XK_Greek_LAMBDA = @as(c_int, 0x7cb); pub const XK_Greek_MU = @as(c_int, 0x7cc); pub const XK_Greek_NU = @as(c_int, 0x7cd); pub const XK_Greek_XI = @as(c_int, 0x7ce); pub const XK_Greek_OMICRON = @as(c_int, 0x7cf); pub const XK_Greek_PI = @as(c_int, 0x7d0); pub const XK_Greek_RHO = @as(c_int, 0x7d1); pub const XK_Greek_SIGMA = @as(c_int, 0x7d2); pub const XK_Greek_TAU = @as(c_int, 0x7d4); pub const XK_Greek_UPSILON = @as(c_int, 0x7d5); pub const XK_Greek_PHI = @as(c_int, 0x7d6); pub const XK_Greek_CHI = @as(c_int, 0x7d7); pub const XK_Greek_PSI = @as(c_int, 0x7d8); pub const XK_Greek_OMEGA = @as(c_int, 0x7d9); pub const XK_Greek_alpha = @as(c_int, 0x7e1); pub const XK_Greek_beta = @as(c_int, 0x7e2); pub const XK_Greek_gamma = @as(c_int, 0x7e3); pub const XK_Greek_delta = @as(c_int, 0x7e4); pub const XK_Greek_epsilon = @as(c_int, 0x7e5); pub const XK_Greek_zeta = @as(c_int, 0x7e6); pub const XK_Greek_eta = @as(c_int, 0x7e7); pub const XK_Greek_theta = @as(c_int, 0x7e8); pub const XK_Greek_iota = @as(c_int, 0x7e9); pub const XK_Greek_kappa = @as(c_int, 0x7ea); pub const XK_Greek_lamda = @as(c_int, 0x7eb); pub const XK_Greek_lambda = @as(c_int, 0x7eb); pub const XK_Greek_mu = @as(c_int, 0x7ec); pub const XK_Greek_nu = @as(c_int, 0x7ed); pub const XK_Greek_xi = @as(c_int, 0x7ee); pub const XK_Greek_omicron = @as(c_int, 0x7ef); pub const XK_Greek_pi = @as(c_int, 0x7f0); pub const XK_Greek_rho = @as(c_int, 0x7f1); pub const XK_Greek_sigma = @as(c_int, 0x7f2); pub const XK_Greek_finalsmallsigma = @as(c_int, 0x7f3); pub const XK_Greek_tau = @as(c_int, 0x7f4); pub const XK_Greek_upsilon = @as(c_int, 0x7f5); pub const XK_Greek_phi = @as(c_int, 0x7f6); pub const XK_Greek_chi = @as(c_int, 0x7f7); pub const XK_Greek_psi = @as(c_int, 0x7f8); pub const XK_Greek_omega = @as(c_int, 0x7f9); pub const XK_Greek_switch = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFF7E, .hexadecimal); pub const XK_EuroSign = @as(c_int, 0x20ac);
modules/platform/src/linux/X11/keysym.zig
const std = @import("std"); const stdx = @import("stdx"); const v8 = @import("v8"); const api = @import("api.zig"); const api_graphics = @import("api_graphics.zig"); const log = stdx.log.scoped(.js_gen); pub fn generate(alloc: std.mem.Allocator, path: []const u8) !void { const src = genApiSupplementJs(alloc); defer alloc.free(src); try std.fs.cwd().writeFile(path, src); } // cosmic /// Generates additional js code from api.zig declarations. /// - Generates async functions that return a v8.Promise. /// Errors from these promises should be recreated on the js side to create a proper stack trace. /// - TODO: Generate non native js functions. Basically the api functions in api_init.js fn genApiSupplementJs(alloc: std.mem.Allocator) []const u8 { var buf = std.ArrayList(u8).init(alloc); const writer = buf.writer(); const Packages: []const type = &.{ api, api_graphics, }; var pkg_to_ns = std.StringHashMap([]const u8).init(alloc); pkg_to_ns.put("cs_audio", "audio") catch unreachable; pkg_to_ns.put("cs_core", "core") catch unreachable; pkg_to_ns.put("cs_files", "files") catch unreachable; pkg_to_ns.put("cs_graphics", "graphics") catch unreachable; pkg_to_ns.put("cs_http", "http") catch unreachable; pkg_to_ns.put("cs_input", "input") catch unreachable; pkg_to_ns.put("cs_net", "net") catch unreachable; pkg_to_ns.put("cs_test", "test") catch unreachable; pkg_to_ns.put("cs_window", "window") catch unreachable; pkg_to_ns.put("cs_worker", "worker") catch unreachable; pkg_to_ns.put("cs_dev", "dev") catch unreachable; writer.print( \\"use strict"; \\ , .{}) catch unreachable; inline for (Packages) |Pkg| { const PkgDecls = comptime std.meta.declarations(Pkg); inline for (PkgDecls) |PkgDecl| { if (PkgDecl.is_pub) { const PkgDeclType = @field(Pkg, PkgDecl.name); if (@typeInfo(@TypeOf(PkgDeclType)) == .Type) { if (std.mem.startsWith(u8, PkgDecl.name, "cs_")) { const ns = pkg_to_ns.get(PkgDecl.name) orelse { log.debug("missing ns for {s}", .{PkgDecl.name}); unreachable; }; const CsPkg = PkgDeclType; const Decls = comptime std.meta.declarations(CsPkg); inline for (Decls) |Decl| { if (Decl.is_pub) { const DeclType = @TypeOf(@field(CsPkg, Decl.name)); if (@typeInfo(DeclType) == .Fn) { // If return type is a v8.Promise, wrap it as an async function. if (@typeInfo(DeclType).Fn.return_type.? == v8.Promise) { const NumParams = @typeInfo(DeclType).Fn.args.len; const Params = switch(NumParams) { 0 => "", 1 => "p1", 2 => "p1, p2", 3 => "p1, p2, p3", else => unreachable, }; writer.print( \\cs.{s}.{s} = async function({s}) {{ \\ try {{ return await cs.{s}._{s}({s}) }} catch (e) {{ throw new ApiError(e) }} \\}} \\ , .{ ns, Decl.name, Params, ns, Decl.name, Params, } ) catch unreachable; } } } } } } } } } return buf.toOwnedSlice(); }
runtime/js_gen.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const ast = std.zig.ast; const Node = ast.Node; const Tree = ast.Tree; const AstError = ast.Error; const TokenIndex = ast.TokenIndex; const Token = std.zig.Token; pub const Error = error{ParseError} || Allocator.Error; /// Result should be freed with tree.deinit() when there are /// no more references to any of the tokens or nodes. pub fn parse(gpa: *Allocator, source: []const u8) Allocator.Error!Tree { var tokens = ast.TokenList{}; defer tokens.deinit(gpa); // Empirically, the zig std lib has an 8:1 ratio of source bytes to token count. const estimated_token_count = source.len / 8; try tokens.ensureCapacity(gpa, estimated_token_count); var tokenizer = std.zig.Tokenizer.init(source); while (true) { const token = tokenizer.next(); try tokens.append(gpa, .{ .tag = token.tag, .start = @intCast(u32, token.loc.start), }); if (token.tag == .eof) break; } var parser: Parser = .{ .source = source, .gpa = gpa, .token_tags = tokens.items(.tag), .token_starts = tokens.items(.start), .errors = .{}, .nodes = .{}, .extra_data = .{}, .tok_i = 0, }; defer parser.errors.deinit(gpa); defer parser.nodes.deinit(gpa); defer parser.extra_data.deinit(gpa); // Empirically, Zig source code has a 2:1 ratio of tokens to AST nodes. // Make sure at least 1 so we can use appendAssumeCapacity on the root node below. const estimated_node_count = (tokens.len + 2) / 2; try parser.nodes.ensureCapacity(gpa, estimated_node_count); // Root node must be index 0. // Root <- skip ContainerMembers eof parser.nodes.appendAssumeCapacity(.{ .tag = .root, .main_token = 0, .data = undefined, }); const root_members = try parser.parseContainerMembers(); const root_decls = try root_members.toSpan(&parser); if (parser.token_tags[parser.tok_i] != .eof) { try parser.warnExpected(.eof); } parser.nodes.items(.data)[0] = .{ .lhs = root_decls.start, .rhs = root_decls.end, }; // TODO experiment with compacting the MultiArrayList slices here return Tree{ .source = source, .tokens = tokens.toOwnedSlice(), .nodes = parser.nodes.toOwnedSlice(), .extra_data = parser.extra_data.toOwnedSlice(gpa), .errors = parser.errors.toOwnedSlice(gpa), }; } const null_node: Node.Index = 0; /// Represents in-progress parsing, will be converted to an ast.Tree after completion. const Parser = struct { gpa: *Allocator, source: []const u8, token_tags: []const Token.Tag, token_starts: []const ast.ByteOffset, tok_i: TokenIndex, errors: std.ArrayListUnmanaged(AstError), nodes: ast.NodeList, extra_data: std.ArrayListUnmanaged(Node.Index), const SmallSpan = union(enum) { zero_or_one: Node.Index, multi: []Node.Index, fn deinit(self: SmallSpan, gpa: *Allocator) void { switch (self) { .zero_or_one => {}, .multi => |list| gpa.free(list), } } }; const Members = struct { len: usize, lhs: Node.Index, rhs: Node.Index, trailing: bool, fn toSpan(self: Members, p: *Parser) !Node.SubRange { if (self.len <= 2) { const nodes = [2]Node.Index{ self.lhs, self.rhs }; return p.listToSpan(nodes[0..self.len]); } else { return Node.SubRange{ .start = self.lhs, .end = self.rhs }; } } }; fn listToSpan(p: *Parser, list: []const Node.Index) !Node.SubRange { try p.extra_data.appendSlice(p.gpa, list); return Node.SubRange{ .start = @intCast(Node.Index, p.extra_data.items.len - list.len), .end = @intCast(Node.Index, p.extra_data.items.len), }; } fn addNode(p: *Parser, elem: ast.NodeList.Elem) Allocator.Error!Node.Index { const result = @intCast(Node.Index, p.nodes.len); try p.nodes.append(p.gpa, elem); return result; } fn setNode(p: *Parser, i: usize, elem: ast.NodeList.Elem) Node.Index { p.nodes.set(i, elem); return @intCast(Node.Index, i); } fn reserveNode(p: *Parser) !usize { try p.nodes.resize(p.gpa, p.nodes.len + 1); return p.nodes.len - 1; } fn addExtra(p: *Parser, extra: anytype) Allocator.Error!Node.Index { const fields = std.meta.fields(@TypeOf(extra)); try p.extra_data.ensureCapacity(p.gpa, p.extra_data.items.len + fields.len); const result = @intCast(u32, p.extra_data.items.len); inline for (fields) |field| { comptime assert(field.field_type == Node.Index); p.extra_data.appendAssumeCapacity(@field(extra, field.name)); } return result; } fn warn(p: *Parser, tag: ast.Error.Tag) error{OutOfMemory}!void { @setCold(true); try p.warnMsg(.{ .tag = tag, .token = p.tok_i }); } fn warnExpected(p: *Parser, expected_token: Token.Tag) error{OutOfMemory}!void { @setCold(true); try p.warnMsg(.{ .tag = .expected_token, .token = p.tok_i, .extra = .{ .expected_tag = expected_token }, }); } fn warnMsg(p: *Parser, msg: ast.Error) error{OutOfMemory}!void { @setCold(true); try p.errors.append(p.gpa, msg); } fn fail(p: *Parser, tag: ast.Error.Tag) error{ ParseError, OutOfMemory } { @setCold(true); return p.failMsg(.{ .tag = tag, .token = p.tok_i }); } fn failExpected(p: *Parser, expected_token: Token.Tag) error{ ParseError, OutOfMemory } { @setCold(true); return p.failMsg(.{ .tag = .expected_token, .token = p.tok_i, .extra = .{ .expected_tag = expected_token }, }); } fn failMsg(p: *Parser, msg: ast.Error) error{ ParseError, OutOfMemory } { @setCold(true); try p.warnMsg(msg); return error.ParseError; } /// ContainerMembers /// <- TestDecl ContainerMembers /// / TopLevelComptime ContainerMembers /// / KEYWORD_pub? TopLevelDecl ContainerMembers /// / ContainerField COMMA ContainerMembers /// / ContainerField /// / /// TopLevelComptime <- KEYWORD_comptime BlockExpr fn parseContainerMembers(p: *Parser) !Members { var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); var field_state: union(enum) { /// No fields have been seen. none, /// Currently parsing fields. seen, /// Saw fields and then a declaration after them. /// Payload is first token of previous declaration. end: Node.Index, /// There was a declaration between fields, don't report more errors. err, } = .none; // Skip container doc comments. while (p.eatToken(.container_doc_comment)) |_| {} var trailing = false; while (true) { const doc_comment = try p.eatDocComments(); switch (p.token_tags[p.tok_i]) { .keyword_test => { const test_decl_node = try p.expectTestDeclRecoverable(); if (test_decl_node != 0) { if (field_state == .seen) { field_state = .{ .end = test_decl_node }; } try list.append(test_decl_node); } trailing = false; }, .keyword_comptime => switch (p.token_tags[p.tok_i + 1]) { .identifier => { p.tok_i += 1; const container_field = try p.expectContainerFieldRecoverable(); if (container_field != 0) { switch (field_state) { .none => field_state = .seen, .err, .seen => {}, .end => |node| { try p.warnMsg(.{ .tag = .decl_between_fields, .token = p.nodes.items(.main_token)[node], }); // Continue parsing; error will be reported later. field_state = .err; }, } try list.append(container_field); switch (p.token_tags[p.tok_i]) { .comma => { p.tok_i += 1; trailing = true; continue; }, .r_brace, .eof => { trailing = false; break; }, else => {}, } // There is not allowed to be a decl after a field with no comma. // Report error but recover parser. try p.warnExpected(.comma); p.findNextContainerMember(); } }, .l_brace => { const comptime_token = p.nextToken(); const block = p.parseBlock() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => blk: { p.findNextContainerMember(); break :blk null_node; }, }; if (block != 0) { const comptime_node = try p.addNode(.{ .tag = .@"comptime", .main_token = comptime_token, .data = .{ .lhs = block, .rhs = undefined, }, }); if (field_state == .seen) { field_state = .{ .end = comptime_node }; } try list.append(comptime_node); } trailing = false; }, else => { p.tok_i += 1; try p.warn(.expected_block_or_field); }, }, .keyword_pub => { p.tok_i += 1; const top_level_decl = try p.expectTopLevelDeclRecoverable(); if (top_level_decl != 0) { if (field_state == .seen) { field_state = .{ .end = top_level_decl }; } try list.append(top_level_decl); } trailing = p.token_tags[p.tok_i - 1] == .semicolon; }, .keyword_usingnamespace => { const node = try p.expectUsingNamespaceRecoverable(); if (node != 0) { if (field_state == .seen) { field_state = .{ .end = node }; } try list.append(node); } trailing = p.token_tags[p.tok_i - 1] == .semicolon; }, .keyword_const, .keyword_var, .keyword_threadlocal, .keyword_export, .keyword_extern, .keyword_inline, .keyword_noinline, .keyword_fn, => { const top_level_decl = try p.expectTopLevelDeclRecoverable(); if (top_level_decl != 0) { if (field_state == .seen) { field_state = .{ .end = top_level_decl }; } try list.append(top_level_decl); } trailing = p.token_tags[p.tok_i - 1] == .semicolon; }, .identifier => { const container_field = try p.expectContainerFieldRecoverable(); if (container_field != 0) { switch (field_state) { .none => field_state = .seen, .err, .seen => {}, .end => |node| { try p.warnMsg(.{ .tag = .decl_between_fields, .token = p.nodes.items(.main_token)[node], }); // Continue parsing; error will be reported later. field_state = .err; }, } try list.append(container_field); switch (p.token_tags[p.tok_i]) { .comma => { p.tok_i += 1; trailing = true; continue; }, .r_brace, .eof => { trailing = false; break; }, else => {}, } // There is not allowed to be a decl after a field with no comma. // Report error but recover parser. try p.warnExpected(.comma); p.findNextContainerMember(); } }, .eof, .r_brace => { if (doc_comment) |tok| { try p.warnMsg(.{ .tag = .unattached_doc_comment, .token = tok, }); } break; }, else => { try p.warn(.expected_container_members); // This was likely not supposed to end yet; try to find the next declaration. p.findNextContainerMember(); }, } } switch (list.items.len) { 0 => return Members{ .len = 0, .lhs = 0, .rhs = 0, .trailing = trailing, }, 1 => return Members{ .len = 1, .lhs = list.items[0], .rhs = 0, .trailing = trailing, }, 2 => return Members{ .len = 2, .lhs = list.items[0], .rhs = list.items[1], .trailing = trailing, }, else => { const span = try p.listToSpan(list.items); return Members{ .len = list.items.len, .lhs = span.start, .rhs = span.end, .trailing = trailing, }; }, } } /// Attempts to find next container member by searching for certain tokens fn findNextContainerMember(p: *Parser) void { var level: u32 = 0; while (true) { const tok = p.nextToken(); switch (p.token_tags[tok]) { // Any of these can start a new top level declaration. .keyword_test, .keyword_comptime, .keyword_pub, .keyword_export, .keyword_extern, .keyword_inline, .keyword_noinline, .keyword_usingnamespace, .keyword_threadlocal, .keyword_const, .keyword_var, .keyword_fn, => { if (level == 0) { p.tok_i -= 1; return; } }, .identifier => { if (p.token_tags[tok + 1] == .comma and level == 0) { p.tok_i -= 1; return; } }, .comma, .semicolon => { // this decl was likely meant to end here if (level == 0) { return; } }, .l_paren, .l_bracket, .l_brace => level += 1, .r_paren, .r_bracket => { if (level != 0) level -= 1; }, .r_brace => { if (level == 0) { // end of container, exit p.tok_i -= 1; return; } level -= 1; }, .eof => { p.tok_i -= 1; return; }, else => {}, } } } /// Attempts to find the next statement by searching for a semicolon fn findNextStmt(p: *Parser) void { var level: u32 = 0; while (true) { const tok = p.nextToken(); switch (p.token_tags[tok]) { .l_brace => level += 1, .r_brace => { if (level == 0) { p.tok_i -= 1; return; } level -= 1; }, .semicolon => { if (level == 0) { return; } }, .eof => { p.tok_i -= 1; return; }, else => {}, } } } /// TestDecl <- KEYWORD_test STRINGLITERALSINGLE? Block fn expectTestDecl(p: *Parser) !Node.Index { const test_token = p.assertToken(.keyword_test); const name_token = p.eatToken(.string_literal); const block_node = try p.parseBlock(); if (block_node == 0) return p.fail(.expected_block); return p.addNode(.{ .tag = .test_decl, .main_token = test_token, .data = .{ .lhs = name_token orelse 0, .rhs = block_node, }, }); } fn expectTestDeclRecoverable(p: *Parser) error{OutOfMemory}!Node.Index { return p.expectTestDecl() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => { p.findNextContainerMember(); return null_node; }, }; } /// TopLevelDecl /// <- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / (KEYWORD_inline / KEYWORD_noinline))? FnProto (SEMICOLON / Block) /// / (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl /// / KEYWORD_usingnamespace Expr SEMICOLON fn expectTopLevelDecl(p: *Parser) !Node.Index { const extern_export_inline_token = p.nextToken(); var expect_fn: bool = false; var expect_var_or_fn: bool = false; switch (p.token_tags[extern_export_inline_token]) { .keyword_extern => { _ = p.eatToken(.string_literal); expect_var_or_fn = true; }, .keyword_export => expect_var_or_fn = true, .keyword_inline, .keyword_noinline => expect_fn = true, else => p.tok_i -= 1, } const fn_proto = try p.parseFnProto(); if (fn_proto != 0) { switch (p.token_tags[p.tok_i]) { .semicolon => { p.tok_i += 1; return fn_proto; }, .l_brace => { const fn_decl_index = try p.reserveNode(); const body_block = try p.parseBlock(); assert(body_block != 0); return p.setNode(fn_decl_index, .{ .tag = .fn_decl, .main_token = p.nodes.items(.main_token)[fn_proto], .data = .{ .lhs = fn_proto, .rhs = body_block, }, }); }, else => { // Since parseBlock only return error.ParseError on // a missing '}' we can assume this function was // supposed to end here. try p.warn(.expected_semi_or_lbrace); return null_node; }, } } if (expect_fn) { try p.warn(.expected_fn); return error.ParseError; } const thread_local_token = p.eatToken(.keyword_threadlocal); const var_decl = try p.parseVarDecl(); if (var_decl != 0) { const semicolon_token = try p.expectToken(.semicolon); return var_decl; } if (thread_local_token != null) { return p.fail(.expected_var_decl); } if (expect_var_or_fn) { return p.fail(.expected_var_decl_or_fn); } if (p.token_tags[p.tok_i] != .keyword_usingnamespace) { return p.fail(.expected_pub_item); } return p.expectUsingNamespace(); } fn expectTopLevelDeclRecoverable(p: *Parser) error{OutOfMemory}!Node.Index { return p.expectTopLevelDecl() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => { p.findNextContainerMember(); return null_node; }, }; } fn expectUsingNamespace(p: *Parser) !Node.Index { const usingnamespace_token = p.assertToken(.keyword_usingnamespace); const expr = try p.expectExpr(); const semicolon_token = try p.expectToken(.semicolon); return p.addNode(.{ .tag = .@"usingnamespace", .main_token = usingnamespace_token, .data = .{ .lhs = expr, .rhs = undefined, }, }); } fn expectUsingNamespaceRecoverable(p: *Parser) error{OutOfMemory}!Node.Index { return p.expectUsingNamespace() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => { p.findNextContainerMember(); return null_node; }, }; } /// FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? CallConv? EXCLAMATIONMARK? (Keyword_anytype / TypeExpr) fn parseFnProto(p: *Parser) !Node.Index { const fn_token = p.eatToken(.keyword_fn) orelse return null_node; // We want the fn proto node to be before its children in the array. const fn_proto_index = try p.reserveNode(); _ = p.eatToken(.identifier); const params = try p.parseParamDeclList(); defer params.deinit(p.gpa); const align_expr = try p.parseByteAlign(); const section_expr = try p.parseLinkSection(); const callconv_expr = try p.parseCallconv(); const bang_token = p.eatToken(.bang); const return_type_expr = try p.parseTypeExpr(); if (return_type_expr == 0) { // most likely the user forgot to specify the return type. // Mark return type as invalid and try to continue. try p.warn(.expected_return_type); } if (align_expr == 0 and section_expr == 0 and callconv_expr == 0) { switch (params) { .zero_or_one => |param| return p.setNode(fn_proto_index, .{ .tag = .fn_proto_simple, .main_token = fn_token, .data = .{ .lhs = param, .rhs = return_type_expr, }, }), .multi => |list| { const span = try p.listToSpan(list); return p.setNode(fn_proto_index, .{ .tag = .fn_proto_multi, .main_token = fn_token, .data = .{ .lhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), .rhs = return_type_expr, }, }); }, } } switch (params) { .zero_or_one => |param| return p.setNode(fn_proto_index, .{ .tag = .fn_proto_one, .main_token = fn_token, .data = .{ .lhs = try p.addExtra(Node.FnProtoOne{ .param = param, .align_expr = align_expr, .section_expr = section_expr, .callconv_expr = callconv_expr, }), .rhs = return_type_expr, }, }), .multi => |list| { const span = try p.listToSpan(list); return p.setNode(fn_proto_index, .{ .tag = .fn_proto, .main_token = fn_token, .data = .{ .lhs = try p.addExtra(Node.FnProto{ .params_start = span.start, .params_end = span.end, .align_expr = align_expr, .section_expr = section_expr, .callconv_expr = callconv_expr, }), .rhs = return_type_expr, }, }); }, } } /// VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON fn parseVarDecl(p: *Parser) !Node.Index { const mut_token = p.eatToken(.keyword_const) orelse p.eatToken(.keyword_var) orelse return null_node; _ = try p.expectToken(.identifier); const type_node: Node.Index = if (p.eatToken(.colon) == null) 0 else try p.expectTypeExpr(); const align_node = try p.parseByteAlign(); const section_node = try p.parseLinkSection(); const init_node: Node.Index = if (p.eatToken(.equal) == null) 0 else try p.expectExpr(); if (section_node == 0) { if (align_node == 0) { return p.addNode(.{ .tag = .simple_var_decl, .main_token = mut_token, .data = .{ .lhs = type_node, .rhs = init_node, }, }); } else if (type_node == 0) { return p.addNode(.{ .tag = .aligned_var_decl, .main_token = mut_token, .data = .{ .lhs = align_node, .rhs = init_node, }, }); } else { return p.addNode(.{ .tag = .local_var_decl, .main_token = mut_token, .data = .{ .lhs = try p.addExtra(Node.LocalVarDecl{ .type_node = type_node, .align_node = align_node, }), .rhs = init_node, }, }); } } else { return p.addNode(.{ .tag = .global_var_decl, .main_token = mut_token, .data = .{ .lhs = try p.addExtra(Node.GlobalVarDecl{ .type_node = type_node, .align_node = align_node, .section_node = section_node, }), .rhs = init_node, }, }); } } /// ContainerField <- KEYWORD_comptime? IDENTIFIER (COLON TypeExpr ByteAlign?)? (EQUAL Expr)? fn expectContainerField(p: *Parser) !Node.Index { const comptime_token = p.eatToken(.keyword_comptime); const name_token = p.assertToken(.identifier); var align_expr: Node.Index = 0; var type_expr: Node.Index = 0; if (p.eatToken(.colon)) |_| { if (p.eatToken(.keyword_anytype)) |anytype_tok| { type_expr = try p.addNode(.{ .tag = .@"anytype", .main_token = anytype_tok, .data = .{ .lhs = undefined, .rhs = undefined, }, }); } else { type_expr = try p.expectTypeExpr(); align_expr = try p.parseByteAlign(); } } const value_expr: Node.Index = if (p.eatToken(.equal) == null) 0 else try p.expectExpr(); if (align_expr == 0) { return p.addNode(.{ .tag = .container_field_init, .main_token = name_token, .data = .{ .lhs = type_expr, .rhs = value_expr, }, }); } else if (value_expr == 0) { return p.addNode(.{ .tag = .container_field_align, .main_token = name_token, .data = .{ .lhs = type_expr, .rhs = align_expr, }, }); } else { return p.addNode(.{ .tag = .container_field, .main_token = name_token, .data = .{ .lhs = type_expr, .rhs = try p.addExtra(Node.ContainerField{ .value_expr = value_expr, .align_expr = align_expr, }), }, }); } } fn expectContainerFieldRecoverable(p: *Parser) error{OutOfMemory}!Node.Index { return p.expectContainerField() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => { p.findNextContainerMember(); return null_node; }, }; } /// Statement /// <- KEYWORD_comptime? VarDecl /// / KEYWORD_comptime BlockExprStatement /// / KEYWORD_nosuspend BlockExprStatement /// / KEYWORD_suspend BlockExprStatement /// / KEYWORD_defer BlockExprStatement /// / KEYWORD_errdefer Payload? BlockExprStatement /// / IfStatement /// / LabeledStatement /// / SwitchExpr /// / AssignExpr SEMICOLON fn parseStatement(p: *Parser) Error!Node.Index { const comptime_token = p.eatToken(.keyword_comptime); const var_decl = try p.parseVarDecl(); if (var_decl != 0) { _ = try p.expectTokenRecoverable(.semicolon); return var_decl; } if (comptime_token) |token| { return p.addNode(.{ .tag = .@"comptime", .main_token = token, .data = .{ .lhs = try p.expectBlockExprStatement(), .rhs = undefined, }, }); } switch (p.token_tags[p.tok_i]) { .keyword_nosuspend => { return p.addNode(.{ .tag = .@"nosuspend", .main_token = p.nextToken(), .data = .{ .lhs = try p.expectBlockExprStatement(), .rhs = undefined, }, }); }, .keyword_suspend => { const token = p.nextToken(); // TODO remove this special case when 0.9.0 is released. const block_expr: Node.Index = if (p.eatToken(.semicolon) != null) 0 else try p.expectBlockExprStatement(); return p.addNode(.{ .tag = .@"suspend", .main_token = token, .data = .{ .lhs = block_expr, .rhs = undefined, }, }); }, .keyword_defer => return p.addNode(.{ .tag = .@"defer", .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = try p.expectBlockExprStatement(), }, }), .keyword_errdefer => return p.addNode(.{ .tag = .@"errdefer", .main_token = p.nextToken(), .data = .{ .lhs = try p.parsePayload(), .rhs = try p.expectBlockExprStatement(), }, }), .keyword_switch => return p.expectSwitchExpr(), .keyword_if => return p.expectIfStatement(), else => {}, } const labeled_statement = try p.parseLabeledStatement(); if (labeled_statement != 0) return labeled_statement; const assign_expr = try p.parseAssignExpr(); if (assign_expr != 0) { _ = try p.expectTokenRecoverable(.semicolon); return assign_expr; } return null_node; } fn expectStatement(p: *Parser) !Node.Index { const statement = try p.parseStatement(); if (statement == 0) { return p.fail(.expected_statement); } return statement; } /// If a parse error occurs, reports an error, but then finds the next statement /// and returns that one instead. If a parse error occurs but there is no following /// statement, returns 0. fn expectStatementRecoverable(p: *Parser) Error!Node.Index { while (true) { return p.expectStatement() catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseError => { p.findNextStmt(); // Try to skip to the next statement. switch (p.token_tags[p.tok_i]) { .r_brace => return null_node, .eof => return error.ParseError, else => continue, } }, }; } } /// IfStatement /// <- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )? /// / IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) fn expectIfStatement(p: *Parser) !Node.Index { const if_token = p.assertToken(.keyword_if); _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); const then_payload = try p.parsePtrPayload(); // TODO propose to change the syntax so that semicolons are always required // inside if statements, even if there is an `else`. var else_required = false; const then_expr = blk: { const block_expr = try p.parseBlockExpr(); if (block_expr != 0) break :blk block_expr; const assign_expr = try p.parseAssignExpr(); if (assign_expr == 0) { return p.fail(.expected_block_or_assignment); } if (p.eatToken(.semicolon)) |_| { return p.addNode(.{ .tag = .if_simple, .main_token = if_token, .data = .{ .lhs = condition, .rhs = assign_expr, }, }); } else_required = true; break :blk assign_expr; }; const else_token = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } return p.addNode(.{ .tag = .if_simple, .main_token = if_token, .data = .{ .lhs = condition, .rhs = then_expr, }, }); }; const else_payload = try p.parsePayload(); const else_expr = try p.expectStatement(); return p.addNode(.{ .tag = .@"if", .main_token = if_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.If{ .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// LabeledStatement <- BlockLabel? (Block / LoopStatement) fn parseLabeledStatement(p: *Parser) !Node.Index { const label_token = p.parseBlockLabel(); const block = try p.parseBlock(); if (block != 0) return block; const loop_stmt = try p.parseLoopStatement(); if (loop_stmt != 0) return loop_stmt; if (label_token != 0) { return p.fail(.expected_labelable); } return null_node; } /// LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement) fn parseLoopStatement(p: *Parser) !Node.Index { const inline_token = p.eatToken(.keyword_inline); const for_statement = try p.parseForStatement(); if (for_statement != 0) return for_statement; const while_statement = try p.parseWhileStatement(); if (while_statement != 0) return while_statement; if (inline_token == null) return null_node; // If we've seen "inline", there should have been a "for" or "while" return p.fail(.expected_inlinable); } /// ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload /// ForStatement /// <- ForPrefix BlockExpr ( KEYWORD_else Statement )? /// / ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement ) fn parseForStatement(p: *Parser) !Node.Index { const for_token = p.eatToken(.keyword_for) orelse return null_node; _ = try p.expectToken(.l_paren); const array_expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); const found_payload = try p.parsePtrIndexPayload(); if (found_payload == 0) try p.warn(.expected_loop_payload); // TODO propose to change the syntax so that semicolons are always required // inside while statements, even if there is an `else`. var else_required = false; const then_expr = blk: { const block_expr = try p.parseBlockExpr(); if (block_expr != 0) break :blk block_expr; const assign_expr = try p.parseAssignExpr(); if (assign_expr == 0) { return p.fail(.expected_block_or_assignment); } if (p.eatToken(.semicolon)) |_| { return p.addNode(.{ .tag = .for_simple, .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = assign_expr, }, }); } else_required = true; break :blk assign_expr; }; const else_token = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } return p.addNode(.{ .tag = .for_simple, .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = then_expr, }, }); }; return p.addNode(.{ .tag = .@"for", .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = try p.addExtra(Node.If{ .then_expr = then_expr, .else_expr = try p.expectStatement(), }), }, }); } /// WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? /// WhileStatement /// <- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )? /// / WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) fn parseWhileStatement(p: *Parser) !Node.Index { const while_token = p.eatToken(.keyword_while) orelse return null_node; _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); const then_payload = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); // TODO propose to change the syntax so that semicolons are always required // inside while statements, even if there is an `else`. var else_required = false; const then_expr = blk: { const block_expr = try p.parseBlockExpr(); if (block_expr != 0) break :blk block_expr; const assign_expr = try p.parseAssignExpr(); if (assign_expr == 0) { return p.fail(.expected_block_or_assignment); } if (p.eatToken(.semicolon)) |_| { if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, .main_token = while_token, .data = .{ .lhs = condition, .rhs = assign_expr, }, }); } else { return p.addNode(.{ .tag = .while_cont, .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.WhileCont{ .cont_expr = cont_expr, .then_expr = assign_expr, }), }, }); } } else_required = true; break :blk assign_expr; }; const else_token = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, .main_token = while_token, .data = .{ .lhs = condition, .rhs = then_expr, }, }); } else { return p.addNode(.{ .tag = .while_cont, .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.WhileCont{ .cont_expr = cont_expr, .then_expr = then_expr, }), }, }); } }; const else_payload = try p.parsePayload(); const else_expr = try p.expectStatement(); return p.addNode(.{ .tag = .@"while", .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.While{ .cont_expr = cont_expr, .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// BlockExprStatement /// <- BlockExpr /// / AssignExpr SEMICOLON fn parseBlockExprStatement(p: *Parser) !Node.Index { const block_expr = try p.parseBlockExpr(); if (block_expr != 0) { return block_expr; } const assign_expr = try p.parseAssignExpr(); if (assign_expr != 0) { _ = try p.expectTokenRecoverable(.semicolon); return assign_expr; } return null_node; } fn expectBlockExprStatement(p: *Parser) !Node.Index { const node = try p.parseBlockExprStatement(); if (node == 0) { return p.fail(.expected_block_or_expr); } return node; } /// BlockExpr <- BlockLabel? Block fn parseBlockExpr(p: *Parser) Error!Node.Index { switch (p.token_tags[p.tok_i]) { .identifier => { if (p.token_tags[p.tok_i + 1] == .colon and p.token_tags[p.tok_i + 2] == .l_brace) { p.tok_i += 2; return p.parseBlock(); } else { return null_node; } }, .l_brace => return p.parseBlock(), else => return null_node, } } /// AssignExpr <- Expr (AssignOp Expr)? /// AssignOp /// <- ASTERISKEQUAL /// / SLASHEQUAL /// / PERCENTEQUAL /// / PLUSEQUAL /// / MINUSEQUAL /// / LARROW2EQUAL /// / RARROW2EQUAL /// / AMPERSANDEQUAL /// / CARETEQUAL /// / PIPEEQUAL /// / ASTERISKPERCENTEQUAL /// / PLUSPERCENTEQUAL /// / MINUSPERCENTEQUAL /// / EQUAL fn parseAssignExpr(p: *Parser) !Node.Index { const expr = try p.parseExpr(); if (expr == 0) return null_node; const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .asterisk_equal => .assign_mul, .slash_equal => .assign_div, .percent_equal => .assign_mod, .plus_equal => .assign_add, .minus_equal => .assign_sub, .angle_bracket_angle_bracket_left_equal => .assign_bit_shift_left, .angle_bracket_angle_bracket_right_equal => .assign_bit_shift_right, .ampersand_equal => .assign_bit_and, .caret_equal => .assign_bit_xor, .pipe_equal => .assign_bit_or, .asterisk_percent_equal => .assign_mul_wrap, .plus_percent_equal => .assign_add_wrap, .minus_percent_equal => .assign_sub_wrap, .equal => .assign, else => return expr, }; return p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = expr, .rhs = try p.expectExpr(), }, }); } fn expectAssignExpr(p: *Parser) !Node.Index { const expr = try p.parseAssignExpr(); if (expr == 0) { return p.fail(.expected_expr_or_assignment); } return expr; } /// Expr <- BoolOrExpr fn parseExpr(p: *Parser) Error!Node.Index { return p.parseBoolOrExpr(); } fn expectExpr(p: *Parser) Error!Node.Index { const node = try p.parseExpr(); if (node == 0) { return p.fail(.expected_expr); } else { return node; } } /// BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)* fn parseBoolOrExpr(p: *Parser) Error!Node.Index { var res = try p.parseBoolAndExpr(); if (res == 0) return null_node; while (true) { switch (p.token_tags[p.tok_i]) { .keyword_or => { const or_token = p.nextToken(); const rhs = try p.parseBoolAndExpr(); if (rhs == 0) { return p.fail(.invalid_token); } res = try p.addNode(.{ .tag = .bool_or, .main_token = or_token, .data = .{ .lhs = res, .rhs = rhs, }, }); }, else => return res, } } } /// BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)* fn parseBoolAndExpr(p: *Parser) !Node.Index { var res = try p.parseCompareExpr(); if (res == 0) return null_node; while (true) { switch (p.token_tags[p.tok_i]) { .keyword_and => { const and_token = p.nextToken(); const rhs = try p.parseCompareExpr(); if (rhs == 0) { return p.fail(.invalid_token); } res = try p.addNode(.{ .tag = .bool_and, .main_token = and_token, .data = .{ .lhs = res, .rhs = rhs, }, }); }, .invalid_ampersands => { try p.warn(.invalid_and); p.tok_i += 1; return p.parseCompareExpr(); }, else => return res, } } } /// CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)? /// CompareOp /// <- EQUALEQUAL /// / EXCLAMATIONMARKEQUAL /// / LARROW /// / RARROW /// / LARROWEQUAL /// / RARROWEQUAL fn parseCompareExpr(p: *Parser) !Node.Index { const expr = try p.parseBitwiseExpr(); if (expr == 0) return null_node; const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .equal_equal => .equal_equal, .bang_equal => .bang_equal, .angle_bracket_left => .less_than, .angle_bracket_right => .greater_than, .angle_bracket_left_equal => .less_or_equal, .angle_bracket_right_equal => .greater_or_equal, else => return expr, }; return p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = expr, .rhs = try p.expectBitwiseExpr(), }, }); } /// BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)* /// BitwiseOp /// <- AMPERSAND /// / CARET /// / PIPE /// / KEYWORD_orelse /// / KEYWORD_catch Payload? fn parseBitwiseExpr(p: *Parser) !Node.Index { var res = try p.parseBitShiftExpr(); if (res == 0) return null_node; while (true) { const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .ampersand => .bit_and, .caret => .bit_xor, .pipe => .bit_or, .keyword_orelse => .@"orelse", .keyword_catch => { const catch_token = p.nextToken(); _ = try p.parsePayload(); const rhs = try p.parseBitShiftExpr(); if (rhs == 0) { return p.fail(.invalid_token); } res = try p.addNode(.{ .tag = .@"catch", .main_token = catch_token, .data = .{ .lhs = res, .rhs = rhs, }, }); continue; }, else => return res, }; res = try p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = res, .rhs = try p.expectBitShiftExpr(), }, }); } } fn expectBitwiseExpr(p: *Parser) Error!Node.Index { const node = try p.parseBitwiseExpr(); if (node == 0) { return p.fail(.invalid_token); } else { return node; } } /// BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)* /// BitShiftOp /// <- LARROW2 /// / RARROW2 fn parseBitShiftExpr(p: *Parser) Error!Node.Index { var res = try p.parseAdditionExpr(); if (res == 0) return null_node; while (true) { const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .angle_bracket_angle_bracket_left => .bit_shift_left, .angle_bracket_angle_bracket_right => .bit_shift_right, else => return res, }; res = try p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = res, .rhs = try p.expectAdditionExpr(), }, }); } } fn expectBitShiftExpr(p: *Parser) Error!Node.Index { const node = try p.parseBitShiftExpr(); if (node == 0) { return p.fail(.invalid_token); } else { return node; } } /// AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)* /// AdditionOp /// <- PLUS /// / MINUS /// / PLUS2 /// / PLUSPERCENT /// / MINUSPERCENT fn parseAdditionExpr(p: *Parser) Error!Node.Index { var res = try p.parseMultiplyExpr(); if (res == 0) return null_node; while (true) { const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .plus => .add, .minus => .sub, .plus_plus => .array_cat, .plus_percent => .add_wrap, .minus_percent => .sub_wrap, else => return res, }; res = try p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = res, .rhs = try p.expectMultiplyExpr(), }, }); } } fn expectAdditionExpr(p: *Parser) Error!Node.Index { const node = try p.parseAdditionExpr(); if (node == 0) { return p.fail(.invalid_token); } return node; } /// MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)* /// MultiplyOp /// <- PIPE2 /// / ASTERISK /// / SLASH /// / PERCENT /// / ASTERISK2 /// / ASTERISKPERCENT fn parseMultiplyExpr(p: *Parser) Error!Node.Index { var res = try p.parsePrefixExpr(); if (res == 0) return null_node; while (true) { const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .pipe_pipe => .merge_error_sets, .asterisk => .mul, .slash => .div, .percent => .mod, .asterisk_asterisk => .array_mult, .asterisk_percent => .mul_wrap, else => return res, }; res = try p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = res, .rhs = try p.expectPrefixExpr(), }, }); } } fn expectMultiplyExpr(p: *Parser) Error!Node.Index { const node = try p.parseMultiplyExpr(); if (node == 0) { return p.fail(.invalid_token); } return node; } /// PrefixExpr <- PrefixOp* PrimaryExpr /// PrefixOp /// <- EXCLAMATIONMARK /// / MINUS /// / TILDE /// / MINUSPERCENT /// / AMPERSAND /// / KEYWORD_try /// / KEYWORD_await fn parsePrefixExpr(p: *Parser) Error!Node.Index { const tag: Node.Tag = switch (p.token_tags[p.tok_i]) { .bang => .bool_not, .minus => .negation, .tilde => .bit_not, .minus_percent => .negation_wrap, .ampersand => .address_of, .keyword_try => .@"try", .keyword_await => .@"await", else => return p.parsePrimaryExpr(), }; return p.addNode(.{ .tag = tag, .main_token = p.nextToken(), .data = .{ .lhs = try p.expectPrefixExpr(), .rhs = undefined, }, }); } fn expectPrefixExpr(p: *Parser) Error!Node.Index { const node = try p.parsePrefixExpr(); if (node == 0) { return p.fail(.expected_prefix_expr); } return node; } /// TypeExpr <- PrefixTypeOp* ErrorUnionExpr /// PrefixTypeOp /// <- QUESTIONMARK /// / KEYWORD_anyframe MINUSRARROW /// / SliceTypeStart (ByteAlign / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* /// / PtrTypeStart (KEYWORD_align LPAREN Expr (COLON INTEGER COLON INTEGER)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* /// / ArrayTypeStart /// SliceTypeStart <- LBRACKET (COLON Expr)? RBRACKET /// PtrTypeStart /// <- ASTERISK /// / ASTERISK2 /// / LBRACKET ASTERISK (LETTERC / COLON Expr)? RBRACKET /// ArrayTypeStart <- LBRACKET Expr (COLON Expr)? RBRACKET fn parseTypeExpr(p: *Parser) Error!Node.Index { switch (p.token_tags[p.tok_i]) { .question_mark => return p.addNode(.{ .tag = .optional_type, .main_token = p.nextToken(), .data = .{ .lhs = try p.expectTypeExpr(), .rhs = undefined, }, }), .keyword_anyframe => switch (p.token_tags[p.tok_i + 1]) { .arrow => return p.addNode(.{ .tag = .anyframe_type, .main_token = p.nextToken(), .data = .{ .lhs = p.nextToken(), .rhs = try p.expectTypeExpr(), }, }), else => return p.parseErrorUnionExpr(), }, .asterisk => { const asterisk = p.nextToken(); const mods = try p.parsePtrModifiers(); const elem_type = try p.expectTypeExpr(); if (mods.bit_range_start == 0) { return p.addNode(.{ .tag = .ptr_type_aligned, .main_token = asterisk, .data = .{ .lhs = mods.align_node, .rhs = elem_type, }, }); } else { return p.addNode(.{ .tag = .ptr_type_bit_range, .main_token = asterisk, .data = .{ .lhs = try p.addExtra(Node.PtrTypeBitRange{ .sentinel = 0, .align_node = mods.align_node, .bit_range_start = mods.bit_range_start, .bit_range_end = mods.bit_range_end, }), .rhs = elem_type, }, }); } }, .asterisk_asterisk => { const asterisk = p.nextToken(); const mods = try p.parsePtrModifiers(); const elem_type = try p.expectTypeExpr(); const inner: Node.Index = inner: { if (mods.bit_range_start == 0) { break :inner try p.addNode(.{ .tag = .ptr_type_aligned, .main_token = asterisk, .data = .{ .lhs = mods.align_node, .rhs = elem_type, }, }); } else { break :inner try p.addNode(.{ .tag = .ptr_type_bit_range, .main_token = asterisk, .data = .{ .lhs = try p.addExtra(Node.PtrTypeBitRange{ .sentinel = 0, .align_node = mods.align_node, .bit_range_start = mods.bit_range_start, .bit_range_end = mods.bit_range_end, }), .rhs = elem_type, }, }); } }; return p.addNode(.{ .tag = .ptr_type_aligned, .main_token = asterisk, .data = .{ .lhs = 0, .rhs = inner, }, }); }, .l_bracket => switch (p.token_tags[p.tok_i + 1]) { .asterisk => { const lbracket = p.nextToken(); const asterisk = p.nextToken(); var sentinel: Node.Index = 0; prefix: { if (p.eatToken(.identifier)) |ident| { const token_slice = p.source[p.token_starts[ident]..][0..2]; if (!std.mem.eql(u8, token_slice, "c]")) { p.tok_i -= 1; } else { break :prefix; } } if (p.eatToken(.colon)) |_| { sentinel = try p.expectExpr(); } } _ = try p.expectToken(.r_bracket); const mods = try p.parsePtrModifiers(); const elem_type = try p.expectTypeExpr(); if (mods.bit_range_start == 0) { if (sentinel == 0) { return p.addNode(.{ .tag = .ptr_type_aligned, .main_token = asterisk, .data = .{ .lhs = mods.align_node, .rhs = elem_type, }, }); } else if (mods.align_node == 0) { return p.addNode(.{ .tag = .ptr_type_sentinel, .main_token = asterisk, .data = .{ .lhs = sentinel, .rhs = elem_type, }, }); } else { return p.addNode(.{ .tag = .ptr_type, .main_token = asterisk, .data = .{ .lhs = try p.addExtra(Node.PtrType{ .sentinel = sentinel, .align_node = mods.align_node, }), .rhs = elem_type, }, }); } } else { return p.addNode(.{ .tag = .ptr_type_bit_range, .main_token = asterisk, .data = .{ .lhs = try p.addExtra(Node.PtrTypeBitRange{ .sentinel = sentinel, .align_node = mods.align_node, .bit_range_start = mods.bit_range_start, .bit_range_end = mods.bit_range_end, }), .rhs = elem_type, }, }); } }, else => { const lbracket = p.nextToken(); const len_expr = try p.parseExpr(); const sentinel: Node.Index = if (p.eatToken(.colon)) |_| try p.expectExpr() else 0; _ = try p.expectToken(.r_bracket); if (len_expr == 0) { const mods = try p.parsePtrModifiers(); const elem_type = try p.expectTypeExpr(); if (mods.bit_range_start != 0) { try p.warnMsg(.{ .tag = .invalid_bit_range, .token = p.nodes.items(.main_token)[mods.bit_range_start], }); } if (sentinel == 0) { return p.addNode(.{ .tag = .ptr_type_aligned, .main_token = lbracket, .data = .{ .lhs = mods.align_node, .rhs = elem_type, }, }); } else if (mods.align_node == 0) { return p.addNode(.{ .tag = .ptr_type_sentinel, .main_token = lbracket, .data = .{ .lhs = sentinel, .rhs = elem_type, }, }); } else { return p.addNode(.{ .tag = .ptr_type, .main_token = lbracket, .data = .{ .lhs = try p.addExtra(Node.PtrType{ .sentinel = sentinel, .align_node = mods.align_node, }), .rhs = elem_type, }, }); } } else { switch (p.token_tags[p.tok_i]) { .keyword_align, .keyword_const, .keyword_volatile, .keyword_allowzero, => return p.fail(.ptr_mod_on_array_child_type), else => {}, } const elem_type = try p.expectTypeExpr(); if (sentinel == 0) { return p.addNode(.{ .tag = .array_type, .main_token = lbracket, .data = .{ .lhs = len_expr, .rhs = elem_type, }, }); } else { return p.addNode(.{ .tag = .array_type_sentinel, .main_token = lbracket, .data = .{ .lhs = len_expr, .rhs = try p.addExtra(.{ .elem_type = elem_type, .sentinel = sentinel, }), }, }); } } }, }, else => return p.parseErrorUnionExpr(), } } fn expectTypeExpr(p: *Parser) Error!Node.Index { const node = try p.parseTypeExpr(); if (node == 0) { return p.fail(.expected_type_expr); } return node; } /// PrimaryExpr /// <- AsmExpr /// / IfExpr /// / KEYWORD_break BreakLabel? Expr? /// / KEYWORD_comptime Expr /// / KEYWORD_nosuspend Expr /// / KEYWORD_continue BreakLabel? /// / KEYWORD_resume Expr /// / KEYWORD_return Expr? /// / BlockLabel? LoopExpr /// / Block /// / CurlySuffixExpr fn parsePrimaryExpr(p: *Parser) !Node.Index { switch (p.token_tags[p.tok_i]) { .keyword_asm => return p.expectAsmExpr(), .keyword_if => return p.parseIfExpr(), .keyword_break => { p.tok_i += 1; return p.addNode(.{ .tag = .@"break", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.parseBreakLabel(), .rhs = try p.parseExpr(), }, }); }, .keyword_continue => { p.tok_i += 1; return p.addNode(.{ .tag = .@"continue", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.parseBreakLabel(), .rhs = undefined, }, }); }, .keyword_comptime => { p.tok_i += 1; return p.addNode(.{ .tag = .@"comptime", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.expectExpr(), .rhs = undefined, }, }); }, .keyword_nosuspend => { p.tok_i += 1; return p.addNode(.{ .tag = .@"nosuspend", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.expectExpr(), .rhs = undefined, }, }); }, .keyword_resume => { p.tok_i += 1; return p.addNode(.{ .tag = .@"resume", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.expectExpr(), .rhs = undefined, }, }); }, .keyword_return => { p.tok_i += 1; return p.addNode(.{ .tag = .@"return", .main_token = p.tok_i - 1, .data = .{ .lhs = try p.parseExpr(), .rhs = undefined, }, }); }, .identifier => { if (p.token_tags[p.tok_i + 1] == .colon) { switch (p.token_tags[p.tok_i + 2]) { .keyword_inline => { p.tok_i += 3; switch (p.token_tags[p.tok_i]) { .keyword_for => return p.parseForExpr(), .keyword_while => return p.parseWhileExpr(), else => return p.fail(.expected_inlinable), } }, .keyword_for => { p.tok_i += 2; return p.parseForExpr(); }, .keyword_while => { p.tok_i += 2; return p.parseWhileExpr(); }, .l_brace => { p.tok_i += 2; return p.parseBlock(); }, else => return p.parseCurlySuffixExpr(), } } else { return p.parseCurlySuffixExpr(); } }, .keyword_inline => { p.tok_i += 1; switch (p.token_tags[p.tok_i]) { .keyword_for => return p.parseForExpr(), .keyword_while => return p.parseWhileExpr(), else => return p.fail(.expected_inlinable), } }, .keyword_for => return p.parseForExpr(), .keyword_while => return p.parseWhileExpr(), .l_brace => return p.parseBlock(), else => return p.parseCurlySuffixExpr(), } } /// IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)? fn parseIfExpr(p: *Parser) !Node.Index { return p.parseIf(parseExpr); } /// Block <- LBRACE Statement* RBRACE fn parseBlock(p: *Parser) !Node.Index { const lbrace = p.eatToken(.l_brace) orelse return null_node; if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = .block_two, .main_token = lbrace, .data = .{ .lhs = 0, .rhs = 0, }, }); } const stmt_one = try p.expectStatementRecoverable(); if (p.eatToken(.r_brace)) |_| { const semicolon = p.token_tags[p.tok_i - 2] == .semicolon; return p.addNode(.{ .tag = if (semicolon) .block_two_semicolon else .block_two, .main_token = lbrace, .data = .{ .lhs = stmt_one, .rhs = 0, }, }); } const stmt_two = try p.expectStatementRecoverable(); if (p.eatToken(.r_brace)) |_| { const semicolon = p.token_tags[p.tok_i - 2] == .semicolon; return p.addNode(.{ .tag = if (semicolon) .block_two_semicolon else .block_two, .main_token = lbrace, .data = .{ .lhs = stmt_one, .rhs = stmt_two, }, }); } var statements = std.ArrayList(Node.Index).init(p.gpa); defer statements.deinit(); try statements.appendSlice(&.{ stmt_one, stmt_two }); while (true) { const statement = try p.expectStatementRecoverable(); if (statement == 0) break; try statements.append(statement); if (p.token_tags[p.tok_i] == .r_brace) break; } _ = try p.expectToken(.r_brace); const semicolon = p.token_tags[p.tok_i - 2] == .semicolon; const statements_span = try p.listToSpan(statements.items); return p.addNode(.{ .tag = if (semicolon) .block_semicolon else .block, .main_token = lbrace, .data = .{ .lhs = statements_span.start, .rhs = statements_span.end, }, }); } /// ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload /// ForExpr <- ForPrefix Expr (KEYWORD_else Expr)? fn parseForExpr(p: *Parser) !Node.Index { const for_token = p.eatToken(.keyword_for) orelse return null_node; _ = try p.expectToken(.l_paren); const array_expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); const found_payload = try p.parsePtrIndexPayload(); if (found_payload == 0) try p.warn(.expected_loop_payload); const then_expr = try p.expectExpr(); const else_token = p.eatToken(.keyword_else) orelse { return p.addNode(.{ .tag = .for_simple, .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = then_expr, }, }); }; const else_expr = try p.expectExpr(); return p.addNode(.{ .tag = .@"for", .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = try p.addExtra(Node.If{ .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? /// WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)? fn parseWhileExpr(p: *Parser) !Node.Index { const while_token = p.eatToken(.keyword_while) orelse return null_node; _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); const then_payload = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); const then_expr = try p.expectExpr(); const else_token = p.eatToken(.keyword_else) orelse { if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, .main_token = while_token, .data = .{ .lhs = condition, .rhs = then_expr, }, }); } else { return p.addNode(.{ .tag = .while_cont, .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.WhileCont{ .cont_expr = cont_expr, .then_expr = then_expr, }), }, }); } }; const else_payload = try p.parsePayload(); const else_expr = try p.expectExpr(); return p.addNode(.{ .tag = .@"while", .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.While{ .cont_expr = cont_expr, .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// CurlySuffixExpr <- TypeExpr InitList? /// InitList /// <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE /// / LBRACE Expr (COMMA Expr)* COMMA? RBRACE /// / LBRACE RBRACE fn parseCurlySuffixExpr(p: *Parser) !Node.Index { const lhs = try p.parseTypeExpr(); if (lhs == 0) return null_node; const lbrace = p.eatToken(.l_brace) orelse return lhs; // If there are 0 or 1 items, we can use ArrayInitOne/StructInitOne; // otherwise we use the full ArrayInit/StructInit. if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = .struct_init_one, .main_token = lbrace, .data = .{ .lhs = lhs, .rhs = 0, }, }); } const field_init = try p.parseFieldInit(); if (field_init != 0) { const comma_one = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_one != null) .struct_init_one_comma else .struct_init_one, .main_token = lbrace, .data = .{ .lhs = lhs, .rhs = field_init, }, }); } var init_list = std.ArrayList(Node.Index).init(p.gpa); defer init_list.deinit(); try init_list.append(field_init); while (true) { const next = try p.expectFieldInit(); try init_list.append(next); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_brace)) |_| break; continue; }, .r_brace => break, .colon, .r_paren, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_brace); }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } } const span = try p.listToSpan(init_list.items); return p.addNode(.{ .tag = if (p.token_tags[p.tok_i - 2] == .comma) .struct_init_comma else .struct_init, .main_token = lbrace, .data = .{ .lhs = lhs, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); } const elem_init = try p.expectExpr(); const comma_one = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_one != null) .array_init_one_comma else .array_init_one, .main_token = lbrace, .data = .{ .lhs = lhs, .rhs = elem_init, }, }); } if (comma_one == null) { try p.warnExpected(.comma); } var init_list = std.ArrayList(Node.Index).init(p.gpa); defer init_list.deinit(); try init_list.append(elem_init); var trailing_comma = true; var next = try p.parseExpr(); while (next != 0) : (next = try p.parseExpr()) { try init_list.append(next); if (p.eatToken(.comma) == null) { trailing_comma = false; break; } } _ = try p.expectToken(.r_brace); const span = try p.listToSpan(init_list.items); return p.addNode(.{ .tag = if (trailing_comma) .array_init_comma else .array_init, .main_token = lbrace, .data = .{ .lhs = lhs, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); } /// ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)? fn parseErrorUnionExpr(p: *Parser) !Node.Index { const suffix_expr = try p.parseSuffixExpr(); if (suffix_expr == 0) return null_node; const bang = p.eatToken(.bang) orelse return suffix_expr; return p.addNode(.{ .tag = .error_union, .main_token = bang, .data = .{ .lhs = suffix_expr, .rhs = try p.expectTypeExpr(), }, }); } /// SuffixExpr /// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments /// / PrimaryTypeExpr (SuffixOp / FnCallArguments)* /// FnCallArguments <- LPAREN ExprList RPAREN /// ExprList <- (Expr COMMA)* Expr? fn parseSuffixExpr(p: *Parser) !Node.Index { if (p.eatToken(.keyword_async)) |async_token| { var res = try p.expectPrimaryTypeExpr(); while (true) { const node = try p.parseSuffixOp(res); if (node == 0) break; res = node; } const lparen = p.nextToken(); if (p.token_tags[lparen] != .l_paren) { p.tok_i -= 1; try p.warn(.expected_param_list); return res; } if (p.eatToken(.r_paren)) |_| { return p.addNode(.{ .tag = .async_call_one, .main_token = lparen, .data = .{ .lhs = res, .rhs = 0, }, }); } const param_one = try p.expectExpr(); const comma_one = p.eatToken(.comma); if (p.eatToken(.r_paren)) |_| { return p.addNode(.{ .tag = if (comma_one == null) .async_call_one else .async_call_one_comma, .main_token = lparen, .data = .{ .lhs = res, .rhs = param_one, }, }); } if (comma_one == null) { try p.warnExpected(.comma); } var param_list = std.ArrayList(Node.Index).init(p.gpa); defer param_list.deinit(); try param_list.append(param_one); while (true) { const next = try p.expectExpr(); try param_list.append(next); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { const span = try p.listToSpan(param_list.items); return p.addNode(.{ .tag = .async_call_comma, .main_token = lparen, .data = .{ .lhs = res, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); } else { continue; } }, .r_paren => { const span = try p.listToSpan(param_list.items); return p.addNode(.{ .tag = .async_call, .main_token = lparen, .data = .{ .lhs = res, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); }, .colon, .r_brace, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_paren); }, else => { p.tok_i -= 1; try p.warnExpected(.comma); }, } } } var res = try p.parsePrimaryTypeExpr(); if (res == 0) return res; while (true) { const suffix_op = try p.parseSuffixOp(res); if (suffix_op != 0) { res = suffix_op; continue; } res = res: { const lparen = p.eatToken(.l_paren) orelse return res; if (p.eatToken(.r_paren)) |_| { break :res try p.addNode(.{ .tag = .call_one, .main_token = lparen, .data = .{ .lhs = res, .rhs = 0, }, }); } const param_one = try p.expectExpr(); const comma_one = p.eatToken(.comma); if (p.eatToken(.r_paren)) |_| { break :res try p.addNode(.{ .tag = if (comma_one == null) .call_one else .call_one_comma, .main_token = lparen, .data = .{ .lhs = res, .rhs = param_one, }, }); } if (comma_one == null) { try p.warnExpected(.comma); } var param_list = std.ArrayList(Node.Index).init(p.gpa); defer param_list.deinit(); try param_list.append(param_one); while (true) { const next = try p.expectExpr(); try param_list.append(next); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { const span = try p.listToSpan(param_list.items); break :res try p.addNode(.{ .tag = .call_comma, .main_token = lparen, .data = .{ .lhs = res, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); } else { continue; } }, .r_paren => { const span = try p.listToSpan(param_list.items); break :res try p.addNode(.{ .tag = .call, .main_token = lparen, .data = .{ .lhs = res, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); }, .colon, .r_brace, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_paren); }, else => { p.tok_i -= 1; try p.warnExpected(.comma); }, } } }; } } /// PrimaryTypeExpr /// <- BUILTINIDENTIFIER FnCallArguments /// / CHAR_LITERAL /// / ContainerDecl /// / DOT IDENTIFIER /// / DOT InitList /// / ErrorSetDecl /// / FLOAT /// / FnProto /// / GroupedExpr /// / LabeledTypeExpr /// / IDENTIFIER /// / IfTypeExpr /// / INTEGER /// / KEYWORD_comptime TypeExpr /// / KEYWORD_error DOT IDENTIFIER /// / KEYWORD_false /// / KEYWORD_null /// / KEYWORD_anyframe /// / KEYWORD_true /// / KEYWORD_undefined /// / KEYWORD_unreachable /// / STRINGLITERAL /// / SwitchExpr /// ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto /// ContainerDeclAuto <- ContainerDeclType LBRACE ContainerMembers RBRACE /// InitList /// <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE /// / LBRACE Expr (COMMA Expr)* COMMA? RBRACE /// / LBRACE RBRACE /// ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE /// GroupedExpr <- LPAREN Expr RPAREN /// IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? /// LabeledTypeExpr /// <- BlockLabel Block /// / BlockLabel? LoopTypeExpr /// LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr) fn parsePrimaryTypeExpr(p: *Parser) !Node.Index { switch (p.token_tags[p.tok_i]) { .char_literal => return p.addNode(.{ .tag = .char_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .integer_literal => return p.addNode(.{ .tag = .integer_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .float_literal => return p.addNode(.{ .tag = .float_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_false => return p.addNode(.{ .tag = .false_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_true => return p.addNode(.{ .tag = .true_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_null => return p.addNode(.{ .tag = .null_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_undefined => return p.addNode(.{ .tag = .undefined_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_unreachable => return p.addNode(.{ .tag = .unreachable_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .keyword_anyframe => return p.addNode(.{ .tag = .anyframe_literal, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), .string_literal => { const main_token = p.nextToken(); return p.addNode(.{ .tag = .string_literal, .main_token = main_token, .data = .{ .lhs = undefined, .rhs = undefined, }, }); }, .builtin => return p.parseBuiltinCall(), .keyword_fn => return p.parseFnProto(), .keyword_if => return p.parseIf(parseTypeExpr), .keyword_switch => return p.expectSwitchExpr(), .keyword_extern, .keyword_packed, => { p.tok_i += 1; return p.parseContainerDeclAuto(); }, .keyword_struct, .keyword_opaque, .keyword_enum, .keyword_union, => return p.parseContainerDeclAuto(), .keyword_comptime => return p.addNode(.{ .tag = .@"comptime", .main_token = p.nextToken(), .data = .{ .lhs = try p.expectTypeExpr(), .rhs = undefined, }, }), .multiline_string_literal_line => { const first_line = p.nextToken(); while (p.token_tags[p.tok_i] == .multiline_string_literal_line) { p.tok_i += 1; } return p.addNode(.{ .tag = .multiline_string_literal, .main_token = first_line, .data = .{ .lhs = first_line, .rhs = p.tok_i - 1, }, }); }, .identifier => switch (p.token_tags[p.tok_i + 1]) { .colon => switch (p.token_tags[p.tok_i + 2]) { .keyword_inline => { p.tok_i += 3; switch (p.token_tags[p.tok_i]) { .keyword_for => return p.parseForTypeExpr(), .keyword_while => return p.parseWhileTypeExpr(), else => return p.fail(.expected_inlinable), } }, .keyword_for => { p.tok_i += 2; return p.parseForTypeExpr(); }, .keyword_while => { p.tok_i += 2; return p.parseWhileTypeExpr(); }, .l_brace => { p.tok_i += 2; return p.parseBlock(); }, else => return p.addNode(.{ .tag = .identifier, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), }, else => return p.addNode(.{ .tag = .identifier, .main_token = p.nextToken(), .data = .{ .lhs = undefined, .rhs = undefined, }, }), }, .keyword_inline => { p.tok_i += 1; switch (p.token_tags[p.tok_i]) { .keyword_for => return p.parseForTypeExpr(), .keyword_while => return p.parseWhileTypeExpr(), else => return p.fail(.expected_inlinable), } }, .keyword_for => return p.parseForTypeExpr(), .keyword_while => return p.parseWhileTypeExpr(), .period => switch (p.token_tags[p.tok_i + 1]) { .identifier => return p.addNode(.{ .tag = .enum_literal, .data = .{ .lhs = p.nextToken(), // dot .rhs = undefined, }, .main_token = p.nextToken(), // identifier }), .l_brace => { const lbrace = p.tok_i + 1; p.tok_i = lbrace + 1; // If there are 0, 1, or 2 items, we can use ArrayInitDotTwo/StructInitDotTwo; // otherwise we use the full ArrayInitDot/StructInitDot. if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = .struct_init_dot_two, .main_token = lbrace, .data = .{ .lhs = 0, .rhs = 0, }, }); } const field_init_one = try p.parseFieldInit(); if (field_init_one != 0) { const comma_one = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_one != null) .struct_init_dot_two_comma else .struct_init_dot_two, .main_token = lbrace, .data = .{ .lhs = field_init_one, .rhs = 0, }, }); } if (comma_one == null) { try p.warnExpected(.comma); } const field_init_two = try p.expectFieldInit(); const comma_two = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_two != null) .struct_init_dot_two_comma else .struct_init_dot_two, .main_token = lbrace, .data = .{ .lhs = field_init_one, .rhs = field_init_two, }, }); } if (comma_two == null) { try p.warnExpected(.comma); } var init_list = std.ArrayList(Node.Index).init(p.gpa); defer init_list.deinit(); try init_list.appendSlice(&.{ field_init_one, field_init_two }); while (true) { const next = try p.expectFieldInit(); assert(next != 0); try init_list.append(next); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_brace)) |_| break; continue; }, .r_brace => break, .colon, .r_paren, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_brace); }, else => { p.tok_i -= 1; try p.warnExpected(.comma); }, } } const span = try p.listToSpan(init_list.items); const trailing_comma = p.token_tags[p.tok_i - 2] == .comma; return p.addNode(.{ .tag = if (trailing_comma) .struct_init_dot_comma else .struct_init_dot, .main_token = lbrace, .data = .{ .lhs = span.start, .rhs = span.end, }, }); } const elem_init_one = try p.expectExpr(); const comma_one = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_one != null) .array_init_dot_two_comma else .array_init_dot_two, .main_token = lbrace, .data = .{ .lhs = elem_init_one, .rhs = 0, }, }); } if (comma_one == null) { try p.warnExpected(.comma); } const elem_init_two = try p.expectExpr(); const comma_two = p.eatToken(.comma); if (p.eatToken(.r_brace)) |_| { return p.addNode(.{ .tag = if (comma_two != null) .array_init_dot_two_comma else .array_init_dot_two, .main_token = lbrace, .data = .{ .lhs = elem_init_one, .rhs = elem_init_two, }, }); } if (comma_two == null) { try p.warnExpected(.comma); } var init_list = std.ArrayList(Node.Index).init(p.gpa); defer init_list.deinit(); try init_list.appendSlice(&.{ elem_init_one, elem_init_two }); while (true) { const next = try p.expectExpr(); if (next == 0) break; try init_list.append(next); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_brace)) |_| break; continue; }, .r_brace => break, .colon, .r_paren, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_brace); }, else => { p.tok_i -= 1; try p.warnExpected(.comma); }, } } const span = try p.listToSpan(init_list.items); return p.addNode(.{ .tag = if (p.token_tags[p.tok_i - 2] == .comma) .array_init_dot_comma else .array_init_dot, .main_token = lbrace, .data = .{ .lhs = span.start, .rhs = span.end, }, }); }, else => return null_node, }, .keyword_error => switch (p.token_tags[p.tok_i + 1]) { .l_brace => { const error_token = p.tok_i; p.tok_i += 2; if (p.eatToken(.r_brace)) |rbrace| { return p.addNode(.{ .tag = .error_set_decl, .main_token = error_token, .data = .{ .lhs = undefined, .rhs = rbrace, }, }); } while (true) { const doc_comment = try p.eatDocComments(); const identifier = try p.expectToken(.identifier); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_brace)) |_| break; continue; }, .r_brace => break, .colon, .r_paren, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_brace); }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } } return p.addNode(.{ .tag = .error_set_decl, .main_token = error_token, .data = .{ .lhs = undefined, .rhs = p.tok_i - 1, // rbrace }, }); }, else => { const main_token = p.nextToken(); const period = p.eatToken(.period); if (period == null) try p.warnExpected(.period); const identifier = p.eatToken(.identifier); if (identifier == null) try p.warnExpected(.identifier); return p.addNode(.{ .tag = .error_value, .main_token = main_token, .data = .{ .lhs = period orelse 0, .rhs = identifier orelse 0, }, }); }, }, .l_paren => return p.addNode(.{ .tag = .grouped_expression, .main_token = p.nextToken(), .data = .{ .lhs = try p.expectExpr(), .rhs = try p.expectToken(.r_paren), }, }), else => return null_node, } } fn expectPrimaryTypeExpr(p: *Parser) !Node.Index { const node = try p.parsePrimaryTypeExpr(); if (node == 0) { return p.fail(.expected_primary_type_expr); } return node; } /// ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload /// ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)? fn parseForTypeExpr(p: *Parser) !Node.Index { const for_token = p.eatToken(.keyword_for) orelse return null_node; _ = try p.expectToken(.l_paren); const array_expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); const found_payload = try p.parsePtrIndexPayload(); if (found_payload == 0) try p.warn(.expected_loop_payload); const then_expr = try p.expectExpr(); const else_token = p.eatToken(.keyword_else) orelse { return p.addNode(.{ .tag = .for_simple, .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = then_expr, }, }); }; const else_expr = try p.expectTypeExpr(); return p.addNode(.{ .tag = .@"for", .main_token = for_token, .data = .{ .lhs = array_expr, .rhs = try p.addExtra(Node.If{ .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? /// WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? fn parseWhileTypeExpr(p: *Parser) !Node.Index { const while_token = p.eatToken(.keyword_while) orelse return null_node; _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); const then_payload = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); const then_expr = try p.expectTypeExpr(); const else_token = p.eatToken(.keyword_else) orelse { if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, .main_token = while_token, .data = .{ .lhs = condition, .rhs = then_expr, }, }); } else { return p.addNode(.{ .tag = .while_cont, .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.WhileCont{ .cont_expr = cont_expr, .then_expr = then_expr, }), }, }); } }; const else_payload = try p.parsePayload(); const else_expr = try p.expectTypeExpr(); return p.addNode(.{ .tag = .@"while", .main_token = while_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.While{ .cont_expr = cont_expr, .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE fn expectSwitchExpr(p: *Parser) !Node.Index { const switch_token = p.assertToken(.keyword_switch); _ = try p.expectToken(.l_paren); const expr_node = try p.expectExpr(); _ = try p.expectToken(.r_paren); _ = try p.expectToken(.l_brace); const cases = try p.parseSwitchProngList(); const trailing_comma = p.token_tags[p.tok_i - 1] == .comma; _ = try p.expectToken(.r_brace); return p.addNode(.{ .tag = if (trailing_comma) .switch_comma else .@"switch", .main_token = switch_token, .data = .{ .lhs = expr_node, .rhs = try p.addExtra(Node.SubRange{ .start = cases.start, .end = cases.end, }), }, }); } /// AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN Expr AsmOutput? RPAREN /// AsmOutput <- COLON AsmOutputList AsmInput? /// AsmInput <- COLON AsmInputList AsmClobbers? /// AsmClobbers <- COLON StringList /// StringList <- (STRINGLITERAL COMMA)* STRINGLITERAL? /// AsmOutputList <- (AsmOutputItem COMMA)* AsmOutputItem? /// AsmInputList <- (AsmInputItem COMMA)* AsmInputItem? fn expectAsmExpr(p: *Parser) !Node.Index { const asm_token = p.assertToken(.keyword_asm); _ = p.eatToken(.keyword_volatile); _ = try p.expectToken(.l_paren); const template = try p.expectExpr(); if (p.eatToken(.r_paren)) |rparen| { return p.addNode(.{ .tag = .asm_simple, .main_token = asm_token, .data = .{ .lhs = template, .rhs = rparen, }, }); } _ = try p.expectToken(.colon); var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); while (true) { const output_item = try p.parseAsmOutputItem(); if (output_item == 0) break; try list.append(output_item); switch (p.token_tags[p.tok_i]) { .comma => p.tok_i += 1, .colon, .r_paren, .r_brace, .r_bracket => break, // All possible delimiters. else => { // This is likely just a missing comma; // give an error but continue parsing this list. try p.warnExpected(.comma); }, } } if (p.eatToken(.colon)) |_| { while (true) { const input_item = try p.parseAsmInputItem(); if (input_item == 0) break; try list.append(input_item); switch (p.token_tags[p.tok_i]) { .comma => p.tok_i += 1, .colon, .r_paren, .r_brace, .r_bracket => break, // All possible delimiters. else => { // This is likely just a missing comma; // give an error but continue parsing this list. try p.warnExpected(.comma); }, } } if (p.eatToken(.colon)) |_| { while (p.eatToken(.string_literal)) |_| { switch (p.token_tags[p.tok_i]) { .comma => p.tok_i += 1, .colon, .r_paren, .r_brace, .r_bracket => break, else => { // This is likely just a missing comma; // give an error but continue parsing this list. try p.warnExpected(.comma); }, } } } } const rparen = try p.expectToken(.r_paren); const span = try p.listToSpan(list.items); return p.addNode(.{ .tag = .@"asm", .main_token = asm_token, .data = .{ .lhs = template, .rhs = try p.addExtra(Node.Asm{ .items_start = span.start, .items_end = span.end, .rparen = rparen, }), }, }); } /// AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN fn parseAsmOutputItem(p: *Parser) !Node.Index { _ = p.eatToken(.l_bracket) orelse return null_node; const identifier = try p.expectToken(.identifier); _ = try p.expectToken(.r_bracket); _ = try p.expectToken(.string_literal); _ = try p.expectToken(.l_paren); const type_expr: Node.Index = blk: { if (p.eatToken(.arrow)) |_| { break :blk try p.expectTypeExpr(); } else { _ = try p.expectToken(.identifier); break :blk null_node; } }; const rparen = try p.expectToken(.r_paren); return p.addNode(.{ .tag = .asm_output, .main_token = identifier, .data = .{ .lhs = type_expr, .rhs = rparen, }, }); } /// AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN fn parseAsmInputItem(p: *Parser) !Node.Index { _ = p.eatToken(.l_bracket) orelse return null_node; const identifier = try p.expectToken(.identifier); _ = try p.expectToken(.r_bracket); _ = try p.expectToken(.string_literal); _ = try p.expectToken(.l_paren); const expr = try p.expectExpr(); const rparen = try p.expectToken(.r_paren); return p.addNode(.{ .tag = .asm_input, .main_token = identifier, .data = .{ .lhs = expr, .rhs = rparen, }, }); } /// BreakLabel <- COLON IDENTIFIER fn parseBreakLabel(p: *Parser) !TokenIndex { _ = p.eatToken(.colon) orelse return @as(TokenIndex, 0); return p.expectToken(.identifier); } /// BlockLabel <- IDENTIFIER COLON fn parseBlockLabel(p: *Parser) TokenIndex { if (p.token_tags[p.tok_i] == .identifier and p.token_tags[p.tok_i + 1] == .colon) { const identifier = p.tok_i; p.tok_i += 2; return identifier; } return 0; } /// FieldInit <- DOT IDENTIFIER EQUAL Expr fn parseFieldInit(p: *Parser) !Node.Index { if (p.token_tags[p.tok_i + 0] == .period and p.token_tags[p.tok_i + 1] == .identifier and p.token_tags[p.tok_i + 2] == .equal) { p.tok_i += 3; return p.expectExpr(); } else { return null_node; } } fn expectFieldInit(p: *Parser) !Node.Index { _ = try p.expectToken(.period); _ = try p.expectToken(.identifier); _ = try p.expectToken(.equal); return p.expectExpr(); } /// WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN fn parseWhileContinueExpr(p: *Parser) !Node.Index { _ = p.eatToken(.colon) orelse return null_node; _ = try p.expectToken(.l_paren); const node = try p.parseAssignExpr(); if (node == 0) return p.fail(.expected_expr_or_assignment); _ = try p.expectToken(.r_paren); return node; } /// LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN fn parseLinkSection(p: *Parser) !Node.Index { _ = p.eatToken(.keyword_linksection) orelse return null_node; _ = try p.expectToken(.l_paren); const expr_node = try p.expectExpr(); _ = try p.expectToken(.r_paren); return expr_node; } /// CallConv <- KEYWORD_callconv LPAREN Expr RPAREN fn parseCallconv(p: *Parser) !Node.Index { _ = p.eatToken(.keyword_callconv) orelse return null_node; _ = try p.expectToken(.l_paren); const expr_node = try p.expectExpr(); _ = try p.expectToken(.r_paren); return expr_node; } /// ParamDecl /// <- (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType /// / DOT3 /// ParamType /// <- Keyword_anytype /// / TypeExpr /// This function can return null nodes and then still return nodes afterwards, /// such as in the case of anytype and `...`. Caller must look for rparen to find /// out when there are no more param decls left. fn expectParamDecl(p: *Parser) !Node.Index { _ = try p.eatDocComments(); switch (p.token_tags[p.tok_i]) { .keyword_noalias, .keyword_comptime => p.tok_i += 1, .ellipsis3 => { p.tok_i += 1; return null_node; }, else => {}, } if (p.token_tags[p.tok_i] == .identifier and p.token_tags[p.tok_i + 1] == .colon) { p.tok_i += 2; } switch (p.token_tags[p.tok_i]) { .keyword_anytype => { p.tok_i += 1; return null_node; }, else => return p.expectTypeExpr(), } } /// Payload <- PIPE IDENTIFIER PIPE fn parsePayload(p: *Parser) !TokenIndex { _ = p.eatToken(.pipe) orelse return @as(TokenIndex, 0); const identifier = try p.expectToken(.identifier); _ = try p.expectToken(.pipe); return identifier; } /// PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE fn parsePtrPayload(p: *Parser) !TokenIndex { _ = p.eatToken(.pipe) orelse return @as(TokenIndex, 0); _ = p.eatToken(.asterisk); const identifier = try p.expectToken(.identifier); _ = try p.expectToken(.pipe); return identifier; } /// PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE /// Returns the first identifier token, if any. fn parsePtrIndexPayload(p: *Parser) !TokenIndex { _ = p.eatToken(.pipe) orelse return @as(TokenIndex, 0); _ = p.eatToken(.asterisk); const identifier = try p.expectToken(.identifier); if (p.eatToken(.comma) != null) { _ = try p.expectToken(.identifier); } _ = try p.expectToken(.pipe); return identifier; } /// SwitchProng <- SwitchCase EQUALRARROW PtrPayload? AssignExpr /// SwitchCase /// <- SwitchItem (COMMA SwitchItem)* COMMA? /// / KEYWORD_else fn parseSwitchProng(p: *Parser) !Node.Index { if (p.eatToken(.keyword_else)) |_| { const arrow_token = try p.expectToken(.equal_angle_bracket_right); _ = try p.parsePtrPayload(); return p.addNode(.{ .tag = .switch_case_one, .main_token = arrow_token, .data = .{ .lhs = 0, .rhs = try p.expectAssignExpr(), }, }); } const first_item = try p.parseSwitchItem(); if (first_item == 0) return null_node; if (p.eatToken(.equal_angle_bracket_right)) |arrow_token| { _ = try p.parsePtrPayload(); return p.addNode(.{ .tag = .switch_case_one, .main_token = arrow_token, .data = .{ .lhs = first_item, .rhs = try p.expectAssignExpr(), }, }); } var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); try list.append(first_item); while (p.eatToken(.comma)) |_| { const next_item = try p.parseSwitchItem(); if (next_item == 0) break; try list.append(next_item); } const span = try p.listToSpan(list.items); const arrow_token = try p.expectToken(.equal_angle_bracket_right); _ = try p.parsePtrPayload(); return p.addNode(.{ .tag = .switch_case, .main_token = arrow_token, .data = .{ .lhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), .rhs = try p.expectAssignExpr(), }, }); } /// SwitchItem <- Expr (DOT3 Expr)? fn parseSwitchItem(p: *Parser) !Node.Index { const expr = try p.parseExpr(); if (expr == 0) return null_node; if (p.eatToken(.ellipsis3)) |token| { return p.addNode(.{ .tag = .switch_range, .main_token = token, .data = .{ .lhs = expr, .rhs = try p.expectExpr(), }, }); } return expr; } const PtrModifiers = struct { align_node: Node.Index, bit_range_start: Node.Index, bit_range_end: Node.Index, }; fn parsePtrModifiers(p: *Parser) !PtrModifiers { var result: PtrModifiers = .{ .align_node = 0, .bit_range_start = 0, .bit_range_end = 0, }; var saw_const = false; var saw_volatile = false; var saw_allowzero = false; while (true) { switch (p.token_tags[p.tok_i]) { .keyword_align => { if (result.align_node != 0) { try p.warn(.extra_align_qualifier); } p.tok_i += 1; _ = try p.expectToken(.l_paren); result.align_node = try p.expectExpr(); if (p.eatToken(.colon)) |_| { result.bit_range_start = try p.expectExpr(); _ = try p.expectToken(.colon); result.bit_range_end = try p.expectExpr(); } _ = try p.expectToken(.r_paren); }, .keyword_const => { if (saw_const) { try p.warn(.extra_const_qualifier); } p.tok_i += 1; saw_const = true; }, .keyword_volatile => { if (saw_volatile) { try p.warn(.extra_volatile_qualifier); } p.tok_i += 1; saw_volatile = true; }, .keyword_allowzero => { if (saw_allowzero) { try p.warn(.extra_allowzero_qualifier); } p.tok_i += 1; saw_allowzero = true; }, else => return result, } } } /// SuffixOp /// <- LBRACKET Expr (DOT2 (Expr? (COLON Expr)?)?)? RBRACKET /// / DOT IDENTIFIER /// / DOTASTERISK /// / DOTQUESTIONMARK fn parseSuffixOp(p: *Parser, lhs: Node.Index) !Node.Index { switch (p.token_tags[p.tok_i]) { .l_bracket => { const lbracket = p.nextToken(); const index_expr = try p.expectExpr(); if (p.eatToken(.ellipsis2)) |_| { const end_expr = try p.parseExpr(); if (p.eatToken(.colon)) |_| { const sentinel = try p.parseExpr(); _ = try p.expectToken(.r_bracket); return p.addNode(.{ .tag = .slice_sentinel, .main_token = lbracket, .data = .{ .lhs = lhs, .rhs = try p.addExtra(Node.SliceSentinel{ .start = index_expr, .end = end_expr, .sentinel = sentinel, }), }, }); } _ = try p.expectToken(.r_bracket); if (end_expr == 0) { return p.addNode(.{ .tag = .slice_open, .main_token = lbracket, .data = .{ .lhs = lhs, .rhs = index_expr, }, }); } return p.addNode(.{ .tag = .slice, .main_token = lbracket, .data = .{ .lhs = lhs, .rhs = try p.addExtra(Node.Slice{ .start = index_expr, .end = end_expr, }), }, }); } _ = try p.expectToken(.r_bracket); return p.addNode(.{ .tag = .array_access, .main_token = lbracket, .data = .{ .lhs = lhs, .rhs = index_expr, }, }); }, .period_asterisk => return p.addNode(.{ .tag = .deref, .main_token = p.nextToken(), .data = .{ .lhs = lhs, .rhs = undefined, }, }), .invalid_periodasterisks => { try p.warn(.asterisk_after_ptr_deref); return p.addNode(.{ .tag = .deref, .main_token = p.nextToken(), .data = .{ .lhs = lhs, .rhs = undefined, }, }); }, .period => switch (p.token_tags[p.tok_i + 1]) { .identifier => return p.addNode(.{ .tag = .field_access, .main_token = p.nextToken(), .data = .{ .lhs = lhs, .rhs = p.nextToken(), }, }), .question_mark => return p.addNode(.{ .tag = .unwrap_optional, .main_token = p.nextToken(), .data = .{ .lhs = lhs, .rhs = p.nextToken(), }, }), else => { p.tok_i += 1; try p.warn(.expected_suffix_op); return null_node; }, }, else => return null_node, } } /// Caller must have already verified the first token. /// ContainerDeclType /// <- KEYWORD_struct /// / KEYWORD_enum (LPAREN Expr RPAREN)? /// / KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)? /// / KEYWORD_opaque fn parseContainerDeclAuto(p: *Parser) !Node.Index { const main_token = p.nextToken(); const arg_expr = switch (p.token_tags[main_token]) { .keyword_struct, .keyword_opaque => null_node, .keyword_enum => blk: { if (p.eatToken(.l_paren)) |_| { const expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); break :blk expr; } else { break :blk null_node; } }, .keyword_union => blk: { if (p.eatToken(.l_paren)) |_| { if (p.eatToken(.keyword_enum)) |_| { if (p.eatToken(.l_paren)) |_| { const enum_tag_expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); _ = try p.expectToken(.r_paren); _ = try p.expectToken(.l_brace); const members = try p.parseContainerMembers(); const members_span = try members.toSpan(p); _ = try p.expectToken(.r_brace); return p.addNode(.{ .tag = switch (members.trailing) { true => .tagged_union_enum_tag_trailing, false => .tagged_union_enum_tag, }, .main_token = main_token, .data = .{ .lhs = enum_tag_expr, .rhs = try p.addExtra(members_span), }, }); } else { _ = try p.expectToken(.r_paren); _ = try p.expectToken(.l_brace); const members = try p.parseContainerMembers(); _ = try p.expectToken(.r_brace); if (members.len <= 2) { return p.addNode(.{ .tag = switch (members.trailing) { true => .tagged_union_two_trailing, false => .tagged_union_two, }, .main_token = main_token, .data = .{ .lhs = members.lhs, .rhs = members.rhs, }, }); } else { const span = try members.toSpan(p); return p.addNode(.{ .tag = switch (members.trailing) { true => .tagged_union_trailing, false => .tagged_union, }, .main_token = main_token, .data = .{ .lhs = span.start, .rhs = span.end, }, }); } } } else { const expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); break :blk expr; } } else { break :blk null_node; } }, else => { p.tok_i -= 1; return p.fail(.expected_container); }, }; _ = try p.expectToken(.l_brace); const members = try p.parseContainerMembers(); _ = try p.expectToken(.r_brace); if (arg_expr == 0) { if (members.len <= 2) { return p.addNode(.{ .tag = switch (members.trailing) { true => .container_decl_two_trailing, false => .container_decl_two, }, .main_token = main_token, .data = .{ .lhs = members.lhs, .rhs = members.rhs, }, }); } else { const span = try members.toSpan(p); return p.addNode(.{ .tag = switch (members.trailing) { true => .container_decl_trailing, false => .container_decl, }, .main_token = main_token, .data = .{ .lhs = span.start, .rhs = span.end, }, }); } } else { const span = try members.toSpan(p); return p.addNode(.{ .tag = switch (members.trailing) { true => .container_decl_arg_trailing, false => .container_decl_arg, }, .main_token = main_token, .data = .{ .lhs = arg_expr, .rhs = try p.addExtra(Node.SubRange{ .start = span.start, .end = span.end, }), }, }); } } /// Holds temporary data until we are ready to construct the full ContainerDecl AST node. /// ByteAlign <- KEYWORD_align LPAREN Expr RPAREN fn parseByteAlign(p: *Parser) !Node.Index { _ = p.eatToken(.keyword_align) orelse return null_node; _ = try p.expectToken(.l_paren); const expr = try p.expectExpr(); _ = try p.expectToken(.r_paren); return expr; } /// SwitchProngList <- (SwitchProng COMMA)* SwitchProng? fn parseSwitchProngList(p: *Parser) !Node.SubRange { return ListParseFn(parseSwitchProng)(p); } /// ParamDeclList <- (ParamDecl COMMA)* ParamDecl? fn parseParamDeclList(p: *Parser) !SmallSpan { _ = try p.expectToken(.l_paren); if (p.eatToken(.r_paren)) |_| { return SmallSpan{ .zero_or_one = 0 }; } const param_one = while (true) { const param = try p.expectParamDecl(); if (param != 0) break param; switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { return SmallSpan{ .zero_or_one = 0 }; } }, .r_paren => return SmallSpan{ .zero_or_one = 0 }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } } else unreachable; const param_two = while (true) { switch (p.token_tags[p.nextToken()]) { .comma => {}, .r_paren => return SmallSpan{ .zero_or_one = param_one }, .colon, .r_brace, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_paren); }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } if (p.eatToken(.r_paren)) |_| { return SmallSpan{ .zero_or_one = param_one }; } const param = try p.expectParamDecl(); if (param != 0) break param; } else unreachable; var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); try list.appendSlice(&.{ param_one, param_two }); while (true) { switch (p.token_tags[p.nextToken()]) { .comma => {}, .r_paren => return SmallSpan{ .multi = list.toOwnedSlice() }, .colon, .r_brace, .r_bracket => { p.tok_i -= 1; return p.failExpected(.r_paren); }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } if (p.eatToken(.r_paren)) |_| { return SmallSpan{ .multi = list.toOwnedSlice() }; } const param = try p.expectParamDecl(); if (param != 0) try list.append(param); } } const NodeParseFn = fn (p: *Parser) Error!Node.Index; fn ListParseFn(comptime nodeParseFn: anytype) (fn (p: *Parser) Error!Node.SubRange) { return struct { pub fn parse(p: *Parser) Error!Node.SubRange { var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); while (true) { const item = try nodeParseFn(p); if (item == 0) break; try list.append(item); switch (p.token_tags[p.tok_i]) { .comma => p.tok_i += 1, // all possible delimiters .colon, .r_paren, .r_brace, .r_bracket => break, else => { // This is likely just a missing comma; // give an error but continue parsing this list. try p.warnExpected(.comma); }, } } return p.listToSpan(list.items); } }.parse; } /// FnCallArguments <- LPAREN ExprList RPAREN /// ExprList <- (Expr COMMA)* Expr? fn parseBuiltinCall(p: *Parser) !Node.Index { const builtin_token = p.assertToken(.builtin); if (p.token_tags[p.nextToken()] != .l_paren) { p.tok_i -= 1; try p.warn(.expected_param_list); // Pretend this was an identifier so we can continue parsing. return p.addNode(.{ .tag = .identifier, .main_token = builtin_token, .data = .{ .lhs = undefined, .rhs = undefined, }, }); } if (p.eatToken(.r_paren)) |_| { return p.addNode(.{ .tag = .builtin_call_two, .main_token = builtin_token, .data = .{ .lhs = 0, .rhs = 0, }, }); } const param_one = try p.expectExpr(); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { return p.addNode(.{ .tag = .builtin_call_two_comma, .main_token = builtin_token, .data = .{ .lhs = param_one, .rhs = 0, }, }); } }, .r_paren => return p.addNode(.{ .tag = .builtin_call_two, .main_token = builtin_token, .data = .{ .lhs = param_one, .rhs = 0, }, }), else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } const param_two = try p.expectExpr(); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { return p.addNode(.{ .tag = .builtin_call_two_comma, .main_token = builtin_token, .data = .{ .lhs = param_one, .rhs = param_two, }, }); } }, .r_paren => return p.addNode(.{ .tag = .builtin_call_two, .main_token = builtin_token, .data = .{ .lhs = param_one, .rhs = param_two, }, }), else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } var list = std.ArrayList(Node.Index).init(p.gpa); defer list.deinit(); try list.appendSlice(&.{ param_one, param_two }); while (true) { const param = try p.expectExpr(); try list.append(param); switch (p.token_tags[p.nextToken()]) { .comma => { if (p.eatToken(.r_paren)) |_| { const params = try p.listToSpan(list.items); return p.addNode(.{ .tag = .builtin_call_comma, .main_token = builtin_token, .data = .{ .lhs = params.start, .rhs = params.end, }, }); } continue; }, .r_paren => { const params = try p.listToSpan(list.items); return p.addNode(.{ .tag = .builtin_call, .main_token = builtin_token, .data = .{ .lhs = params.start, .rhs = params.end, }, }); }, else => { // This is likely just a missing comma; // give an error but continue parsing this list. p.tok_i -= 1; try p.warnExpected(.comma); }, } } } // string literal or multiline string literal fn parseStringLiteral(p: *Parser) !Node.Index { switch (p.token_tags[p.tok_i]) { .string_literal => { const main_token = p.nextToken(); return p.addNode(.{ .tag = .string_literal, .main_token = main_token, .data = .{ .lhs = undefined, .rhs = undefined, }, }); }, .multiline_string_literal_line => { const first_line = p.nextToken(); while (p.token_tags[p.tok_i] == .multiline_string_literal_line) { p.tok_i += 1; } return p.addNode(.{ .tag = .multiline_string_literal, .main_token = first_line, .data = .{ .lhs = first_line, .rhs = p.tok_i - 1, }, }); }, else => return null_node, } } fn expectStringLiteral(p: *Parser) !Node.Index { const node = try p.parseStringLiteral(); if (node == 0) { return p.fail(.expected_string_literal); } return node; } fn expectIntegerLiteral(p: *Parser) !Node.Index { return p.addNode(.{ .tag = .integer_literal, .main_token = try p.expectToken(.integer_literal), .data = .{ .lhs = undefined, .rhs = undefined, }, }); } /// KEYWORD_if LPAREN Expr RPAREN PtrPayload? Body (KEYWORD_else Payload? Body)? fn parseIf(p: *Parser, bodyParseFn: NodeParseFn) !Node.Index { const if_token = p.eatToken(.keyword_if) orelse return null_node; _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); const then_payload = try p.parsePtrPayload(); const then_expr = try bodyParseFn(p); if (then_expr == 0) return p.fail(.invalid_token); const else_token = p.eatToken(.keyword_else) orelse return p.addNode(.{ .tag = .if_simple, .main_token = if_token, .data = .{ .lhs = condition, .rhs = then_expr, }, }); const else_payload = try p.parsePayload(); const else_expr = try bodyParseFn(p); if (else_expr == 0) return p.fail(.invalid_token); return p.addNode(.{ .tag = .@"if", .main_token = if_token, .data = .{ .lhs = condition, .rhs = try p.addExtra(Node.If{ .then_expr = then_expr, .else_expr = else_expr, }), }, }); } /// Skips over doc comment tokens. Returns the first one, if any. fn eatDocComments(p: *Parser) !?TokenIndex { if (p.eatToken(.doc_comment)) |tok| { var first_line = tok; if (tok > 0 and tokensOnSameLine(p, tok - 1, tok)) { try p.warnMsg(.{ .tag = .same_line_doc_comment, .token = tok, }); first_line = p.eatToken(.doc_comment) orelse return null; } while (p.eatToken(.doc_comment)) |_| {} return first_line; } return null; } fn tokensOnSameLine(p: *Parser, token1: TokenIndex, token2: TokenIndex) bool { return std.mem.indexOfScalar(u8, p.source[p.token_starts[token1]..p.token_starts[token2]], '\n') == null; } fn eatToken(p: *Parser, tag: Token.Tag) ?TokenIndex { return if (p.token_tags[p.tok_i] == tag) p.nextToken() else null; } fn assertToken(p: *Parser, tag: Token.Tag) TokenIndex { const token = p.nextToken(); assert(p.token_tags[token] == tag); return token; } fn expectToken(p: *Parser, tag: Token.Tag) Error!TokenIndex { const token = p.nextToken(); if (p.token_tags[token] != tag) { p.tok_i -= 1; // Go back so that we can recover properly. return p.failMsg(.{ .tag = .expected_token, .token = token, .extra = .{ .expected_tag = tag }, }); } return token; } fn expectTokenRecoverable(p: *Parser, tag: Token.Tag) !?TokenIndex { if (p.token_tags[p.tok_i] != tag) { try p.warnExpected(tag); return null; } else { return p.nextToken(); } } fn nextToken(p: *Parser) TokenIndex { const result = p.tok_i; p.tok_i += 1; return result; } }; test { _ = @import("parser_test.zig"); }
lib/std/zig/parse.zig
const std = @import("std"); const expect = std.testing.expect; const maxInt = std.math.maxInt; const minInt = std.math.minInt; const builtin = @import("builtin"); test "uint128" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO var buff: u128 = maxInt(u128); try expect(buff == maxInt(u128)); const magic_const = 0x12341234123412341234123412341234; buff = magic_const; try expect(buff == magic_const); try expect(magic_const == 0x12341234123412341234123412341234); buff = 0; try expect(buff == @as(u128, 0)); } test "undefined 128 bit int" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO @setRuntimeSafety(true); // TODO implement @setRuntimeSafety in stage2 if (builtin.zig_backend != .stage1 and builtin.mode != .Debug and builtin.mode != .ReleaseSafe) { return error.SkipZigTest; } var undef: u128 = undefined; var undef_signed: i128 = undefined; try expect(undef == 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and @bitCast(u128, undef_signed) == undef); } test "int128" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO var buff: i128 = -1; try expect(buff < 0 and (buff + 1) == 0); try expect(@intCast(i8, buff) == @as(i8, -1)); buff = minInt(i128); try expect(buff < 0); buff = -0x12341234123412341234123412341234; try expect(-buff == 0x12341234123412341234123412341234); } test "truncate int128" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO var buff: u128 = maxInt(u128); try expect(@truncate(u64, buff) == maxInt(u64)); }
test/behavior/int128.zig
const Tokenizer = @This(); const std = @import("std"); const log = std.log.scoped(.tapi); const testing = std.testing; buffer: []const u8, index: usize = 0, pub const Token = struct { id: Id, start: usize, end: usize, pub const Id = enum { Eof, NewLine, DocStart, // --- DocEnd, // ... SeqItemInd, // - MapValueInd, // : FlowMapStart, // { FlowMapEnd, // } FlowSeqStart, // [ FlowSeqEnd, // ] Comma, Space, Tab, Comment, // # Alias, // * Anchor, // & Tag, // ! SingleQuote, // ' DoubleQuote, // " Literal, }; }; pub const TokenIndex = usize; pub const TokenIterator = struct { buffer: []const Token, pos: TokenIndex = 0, pub fn next(self: *TokenIterator) Token { const token = self.buffer[self.pos]; self.pos += 1; return token; } pub fn peek(self: TokenIterator) ?Token { if (self.pos >= self.buffer.len) return null; return self.buffer[self.pos]; } pub fn reset(self: *TokenIterator) void { self.pos = 0; } pub fn seekTo(self: *TokenIterator, pos: TokenIndex) void { self.pos = pos; } pub fn seekBy(self: *TokenIterator, offset: isize) void { const new_pos = @bitCast(isize, self.pos) + offset; if (new_pos < 0) { self.pos = 0; } else { self.pos = @intCast(usize, new_pos); } } }; pub fn next(self: *Tokenizer) Token { var result = Token{ .id = .Eof, .start = self.index, .end = undefined, }; var state: union(enum) { Start, NewLine, Space, Tab, Hyphen: usize, Dot: usize, Literal, } = .Start; while (self.index < self.buffer.len) : (self.index += 1) { const c = self.buffer[self.index]; switch (state) { .Start => switch (c) { ' ' => { state = .Space; }, '\t' => { state = .Tab; }, '\n' => { result.id = .NewLine; self.index += 1; break; }, '\r' => { state = .NewLine; }, '-' => { state = .{ .Hyphen = 1 }; }, '.' => { state = .{ .Dot = 1 }; }, ',' => { result.id = .Comma; self.index += 1; break; }, '#' => { result.id = .Comment; self.index += 1; break; }, '*' => { result.id = .Alias; self.index += 1; break; }, '&' => { result.id = .Anchor; self.index += 1; break; }, '!' => { result.id = .Tag; self.index += 1; break; }, '\'' => { result.id = .SingleQuote; self.index += 1; break; }, '"' => { result.id = .DoubleQuote; self.index += 1; break; }, '[' => { result.id = .FlowSeqStart; self.index += 1; break; }, ']' => { result.id = .FlowSeqEnd; self.index += 1; break; }, ':' => { result.id = .MapValueInd; self.index += 1; break; }, '{' => { result.id = .FlowMapStart; self.index += 1; break; }, '}' => { result.id = .FlowMapEnd; self.index += 1; break; }, else => { state = .Literal; }, }, .Space => switch (c) { ' ' => {}, else => { result.id = .Space; break; }, }, .Tab => switch (c) { '\t' => {}, else => { result.id = .Tab; break; }, }, .NewLine => switch (c) { '\n' => { result.id = .NewLine; self.index += 1; break; }, else => {}, // TODO this should be an error condition }, .Hyphen => |*count| switch (c) { ' ' => { result.id = .SeqItemInd; self.index += 1; break; }, '-' => { count.* += 1; if (count.* == 3) { result.id = .DocStart; self.index += 1; break; } }, else => { state = .Literal; }, }, .Dot => |*count| switch (c) { '.' => { count.* += 1; if (count.* == 3) { result.id = .DocEnd; self.index += 1; break; } }, else => { state = .Literal; }, }, .Literal => switch (c) { '\r', '\n', ' ', '\'', '"', ',', ':', ']', '}' => { result.id = .Literal; break; }, else => { result.id = .Literal; }, }, } } if (state == .Literal and result.id == .Eof) { result.id = .Literal; } result.end = self.index; log.debug("{any}", .{result}); log.debug(" | {s}", .{self.buffer[result.start..result.end]}); return result; } fn testExpected(source: []const u8, expected: []const Token.Id) !void { var tokenizer = Tokenizer{ .buffer = source, }; var token_len: usize = 0; for (expected) |exp| { token_len += 1; const token = tokenizer.next(); try testing.expectEqual(exp, token.id); } while (tokenizer.next().id != .Eof) { token_len += 1; // consume all tokens } try testing.expectEqual(expected.len, token_len); } test "empty doc" { try testExpected("", &[_]Token.Id{.Eof}); } test "empty doc with explicit markers" { try testExpected( \\--- \\... , &[_]Token.Id{ .DocStart, .NewLine, .DocEnd, .Eof, }); } test "sequence of values" { try testExpected( \\- 0 \\- 1 \\- 2 , &[_]Token.Id{ .SeqItemInd, .Literal, .NewLine, .SeqItemInd, .Literal, .NewLine, .SeqItemInd, .Literal, .Eof, }); } test "sequence of sequences" { try testExpected( \\- [ val1, val2] \\- [val3, val4 ] , &[_]Token.Id{ .SeqItemInd, .FlowSeqStart, .Space, .Literal, .Comma, .Space, .Literal, .FlowSeqEnd, .NewLine, .SeqItemInd, .FlowSeqStart, .Literal, .Comma, .Space, .Literal, .Space, .FlowSeqEnd, .Eof, }); } test "mappings" { try testExpected( \\key1: value1 \\key2: value2 , &[_]Token.Id{ .Literal, .MapValueInd, .Space, .Literal, .NewLine, .Literal, .MapValueInd, .Space, .Literal, .Eof, }); } test "inline mapped sequence of values" { try testExpected( \\key : [ val1, \\ val2 ] , &[_]Token.Id{ .Literal, .Space, .MapValueInd, .Space, .FlowSeqStart, .Space, .Literal, .Comma, .Space, .NewLine, .Space, .Literal, .Space, .FlowSeqEnd, .Eof, }); } test "part of tbd" { try testExpected( \\--- !tapi-tbd \\tbd-version: 4 \\targets: [ x86_64-macos ] \\ \\uuids: \\ - target: x86_64-macos \\ value: F86CC732-D5E4-30B5-AA7D-167DF5EC2708 \\ \\install-name: '/usr/lib/libSystem.B.dylib' \\... , &[_]Token.Id{ .DocStart, .Space, .Tag, .Literal, .NewLine, .Literal, .MapValueInd, .Space, .Literal, .NewLine, .Literal, .MapValueInd, .Space, .FlowSeqStart, .Space, .Literal, .Space, .FlowSeqEnd, .NewLine, .NewLine, .Literal, .MapValueInd, .NewLine, .Space, .SeqItemInd, .Literal, .MapValueInd, .Space, .Literal, .NewLine, .Space, .Literal, .MapValueInd, .Space, .Literal, .NewLine, .NewLine, .Literal, .MapValueInd, .Space, .SingleQuote, .Literal, .SingleQuote, .NewLine, .DocEnd, .Eof, }); } test "Unindented list" { try testExpected( \\b: \\- foo: 1 \\c: 1 , &[_]Token.Id{ .Literal, .MapValueInd, .NewLine, .SeqItemInd, .Literal, .MapValueInd, .Space, .Literal, .NewLine, .Literal, .MapValueInd, .Space, .Literal, }); }
src/link/tapi/Tokenizer.zig
const std = @import("std"); const mem = std.mem; const ModifierSymbol = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 94, hi: u21 = 127999, pub fn init(allocator: *mem.Allocator) !ModifierSymbol { var instance = ModifierSymbol{ .allocator = allocator, .array = try allocator.alloc(bool, 127906), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; instance.array[2] = true; instance.array[74] = true; instance.array[81] = true; instance.array[86] = true; instance.array[90] = true; index = 612; while (index <= 615) : (index += 1) { instance.array[index] = true; } index = 628; while (index <= 641) : (index += 1) { instance.array[index] = true; } index = 647; while (index <= 653) : (index += 1) { instance.array[index] = true; } instance.array[655] = true; index = 657; while (index <= 673) : (index += 1) { instance.array[index] = true; } instance.array[791] = true; index = 806; while (index <= 807) : (index += 1) { instance.array[index] = true; } instance.array[8031] = true; index = 8033; while (index <= 8035) : (index += 1) { instance.array[index] = true; } index = 8047; while (index <= 8049) : (index += 1) { instance.array[index] = true; } index = 8063; while (index <= 8065) : (index += 1) { instance.array[index] = true; } index = 8079; while (index <= 8081) : (index += 1) { instance.array[index] = true; } index = 8095; while (index <= 8096) : (index += 1) { instance.array[index] = true; } index = 12349; while (index <= 12350) : (index += 1) { instance.array[index] = true; } index = 42658; while (index <= 42680) : (index += 1) { instance.array[index] = true; } index = 42690; while (index <= 42691) : (index += 1) { instance.array[index] = true; } index = 42795; while (index <= 42796) : (index += 1) { instance.array[index] = true; } instance.array[43773] = true; index = 43788; while (index <= 43789) : (index += 1) { instance.array[index] = true; } index = 64340; while (index <= 64355) : (index += 1) { instance.array[index] = true; } instance.array[65248] = true; instance.array[65250] = true; instance.array[65413] = true; index = 127901; while (index <= 127905) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *ModifierSymbol) void { self.allocator.free(self.array); } // isModifierSymbol checks if cp is of the kind Modifier_Symbol. pub fn isModifierSymbol(self: ModifierSymbol, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedGeneralCategory/ModifierSymbol.zig
const std = @import("std"); const mem = std.mem; const crypto = std.crypto; fn fieldElement(comptime Field: type) type { const fiat = Field.fiat; return struct { const Self = @This(); limbs: Field.Limbs, pub const bytes = Field.bytes; pub fn invert(a: Self) Self { const iterations = (49 * Field.len_prime + if (Field.len_prime < 46) 80 else 57) / 17; const XLimbs = [a.limbs.len + 1]Field.Word; var d: Field.Word = 1; var f: XLimbs = undefined; fiat.msat(&f); var g = mem.zeroes(XLimbs); fiat.fromMontgomery(g[0..a.limbs.len], a.limbs); // Assume input in Montgomery domain var r = one.limbs; var v = mem.zeroes(Field.Limbs); var precomp: Field.Limbs = undefined; fiat.divstepPrecomp(&precomp); var out1: Field.Word = undefined; var out2: XLimbs = undefined; var out3: XLimbs = undefined; var out4: Field.Limbs = undefined; var out5: Field.Limbs = undefined; var i: usize = 0; while (i < iterations - iterations % 2) : (i += 2) { fiat.divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r); fiat.divstep(&d, &f, &g, &v, &r, out1, out2, out3, out4, out5); } if (iterations % 2 != 0) { fiat.divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r); v = out4; f = out2; } var v_opp: Field.Limbs = undefined; fiat.opp(&v_opp, v); fiat.selectznz(&v, @truncate(u1, f[f.len - 1] >> (std.meta.bitCount(Field.Word) - 1)), v, v_opp); var fe: Self = undefined; fiat.mul(&fe.limbs, v, precomp); return fe; } pub const one = comptime one: { var fe: Self = undefined; fiat.setOne(&fe.limbs); break :one fe; }; pub fn fromBytes(s: [Field.bytes]u8) Self { var limbs_z: Field.Limbs = undefined; fiat.fromBytes(&limbs_z, s); var limbs: Field.Limbs = undefined; fiat.toMontgomery(&limbs, limbs_z); return Self{ .limbs = limbs }; } pub fn mul(a: Self, b: Self) Self { var fe: Self = undefined; fiat.mul(&fe.limbs, a.limbs, b.limbs); return fe; } pub fn eql(a: Self, b: Self) bool { return crypto.utils.timingSafeEql(Field.Limbs, a.limbs, b.limbs); } }; } test "Field inversion" { const Fe = fieldElement(struct { const fiat = @import("p256_64.zig"); const Word = u64; const Limbs = [4]Word; const len_prime = 256; const bytes = 32; }); var s: [Fe.bytes]u8 = undefined; crypto.random.bytes(&s); const x = Fe.fromBytes(s); const xinv = x.invert(); try std.testing.expect(x.mul(xinv).eql(Fe.one)); }
inversion/zig/inversion.zig
const std = @import("std"); const fs = std.fs; const mem = std.mem; const xml = @import("xml.zig"); const gpa = &allocator_instance.allocator; var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){}; pub fn scan(root_dir: fs.Dir, out_path: []const u8, wayland_xml: []const u8, protocols: []const []const u8) !void { var out_dir = try root_dir.makeOpenPath(out_path, .{}); defer out_dir.close(); const wayland_file = try out_dir.createFile("wayland.zig", .{}); try wayland_file.writeAll(@embedFile("wayland.zig")); defer wayland_file.close(); var scanner = Scanner{}; try scanner.scanProtocol(root_dir, out_dir, wayland_xml); for (protocols) |xml_path| try scanner.scanProtocol(root_dir, out_dir, xml_path); { const client_core_file = try out_dir.createFile("wayland_client_core.zig", .{}); defer client_core_file.close(); try client_core_file.writeAll(@embedFile("wayland_client_core.zig")); const client_file = try out_dir.createFile("client.zig", .{}); defer client_file.close(); const writer = client_file.writer(); var iter = scanner.client.iterator(); while (iter.next()) |entry| { try writer.print("pub const {s} = struct {{", .{entry.key}); if (mem.eql(u8, entry.key, "wl")) try writer.writeAll("pub usingnamespace @import(\"wayland_client_core.zig\");\n"); for (entry.value.items) |generated_file| try writer.print("pub usingnamespace @import(\"{s}\");", .{generated_file}); try writer.writeAll("};\n"); } } { const server_core_file = try out_dir.createFile("wayland_server_core.zig", .{}); defer server_core_file.close(); try server_core_file.writeAll(@embedFile("wayland_server_core.zig")); const server_file = try out_dir.createFile("server.zig", .{}); defer server_file.close(); const writer = server_file.writer(); var iter = scanner.server.iterator(); while (iter.next()) |entry| { try writer.print("pub const {s} = struct {{", .{entry.key}); if (mem.eql(u8, entry.key, "wl")) try writer.writeAll("pub usingnamespace @import(\"wayland_server_core.zig\");\n"); for (entry.value.items) |generated_file| try writer.print("pub usingnamespace @import(\"{s}\");", .{generated_file}); try writer.writeAll("};\n"); } } { const common_file = try out_dir.createFile("common.zig", .{}); defer common_file.close(); const writer = common_file.writer(); try writer.writeAll(@embedFile("common_core.zig")); var iter = scanner.common.iterator(); while (iter.next()) |entry| { try writer.print("pub const {s} = struct {{", .{entry.key}); for (entry.value.items) |generated_file| try writer.print("pub usingnamespace @import(\"{s}\");", .{generated_file}); try writer.writeAll("};\n"); } } } const Side = enum { client, server, }; const Scanner = struct { /// Map from namespace to list of generated files const Map = std.hash_map.StringHashMap(std.ArrayListUnmanaged([]const u8)); client: Map = Map.init(gpa), server: Map = Map.init(gpa), common: Map = Map.init(gpa), fn scanProtocol(scanner: *Scanner, root_dir: fs.Dir, out_dir: fs.Dir, xml_path: []const u8) !void { const xml_file = try root_dir.openFile(xml_path, .{}); defer xml_file.close(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const xml_bytes = try xml_file.readToEndAlloc(&arena.allocator, 512 * 4096); const protocol = try Protocol.parseXML(&arena.allocator, xml_bytes); const protocol_name = try gpa.dupe(u8, protocol.name); const protocol_namespace = try gpa.dupe(u8, protocol.namespace); { const client_filename = try mem.concat(gpa, u8, &[_][]const u8{ protocol_name, "_client.zig" }); const client_file = try out_dir.createFile(client_filename, .{}); defer client_file.close(); try protocol.emitClient(client_file.writer()); try (try scanner.client.getOrPutValue(protocol_namespace, .{})).value.append(gpa, client_filename); } { const server_filename = try mem.concat(gpa, u8, &[_][]const u8{ protocol_name, "_server.zig" }); const server_file = try out_dir.createFile(server_filename, .{}); defer server_file.close(); try protocol.emitServer(server_file.writer()); try (try scanner.server.getOrPutValue(protocol_namespace, .{})).value.append(gpa, server_filename); } { const common_filename = try mem.concat(gpa, u8, &[_][]const u8{ protocol_name, "_common.zig" }); const common_file = try out_dir.createFile(common_filename, .{}); defer common_file.close(); try protocol.emitCommon(common_file.writer()); try (try scanner.common.getOrPutValue(protocol_namespace, .{})).value.append(gpa, common_filename); } } }; const Protocol = struct { name: []const u8, namespace: []const u8, copyright: ?[]const u8, toplevel_description: ?[]const u8, interfaces: std.ArrayList(Interface), fn parseXML(allocator: *mem.Allocator, xml_bytes: []const u8) !Protocol { var parser = xml.Parser.init(xml_bytes); while (parser.next()) |ev| switch (ev) { .open_tag => |tag| if (mem.eql(u8, tag, "protocol")) return parse(allocator, &parser), else => {}, }; return error.UnexpectedEndOfFile; } fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Protocol { var name: ?[]const u8 = null; var copyright: ?[]const u8 = null; var toplevel_description: ?[]const u8 = null; var interfaces = std.ArrayList(Interface).init(allocator); while (parser.next()) |ev| switch (ev) { .open_tag => |tag| { if (mem.eql(u8, tag, "copyright")) { if (copyright != null) return error.DuplicateCopyright; const e = parser.next() orelse return error.UnexpectedEndOfFile; switch (e) { .character_data => |data| copyright = try allocator.dupe(u8, data), else => return error.BadCopyright, } } else if (mem.eql(u8, tag, "description")) { if (toplevel_description != null) return error.DuplicateToplevelDescription; while (parser.next()) |e| { switch (e) { .character_data => |data| { toplevel_description = try allocator.dupe(u8, data); break; }, .attribute => continue, else => return error.BadToplevelDescription, } } else { return error.UnexpectedEndOfFile; } } else if (mem.eql(u8, tag, "interface")) { try interfaces.append(try Interface.parse(allocator, parser)); } }, .attribute => |attr| if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); }, .close_tag => |tag| if (mem.eql(u8, tag, "protocol")) { if (interfaces.items.len == 0) return error.NoInterfaces; return Protocol{ .name = name orelse return error.MissingName, // TODO: support mixing namespaces in a protocol .namespace = prefix(interfaces.items[0].name) orelse return error.NoNamespace, .interfaces = interfaces, // Missing copyright or toplevel description is bad style, but not illegal. .copyright = copyright, .toplevel_description = toplevel_description, }; }, else => {}, }; return error.UnexpectedEndOfFile; } fn emitCopyrightAndToplevelDescription(protocol: Protocol, writer: anytype) !void { try writer.writeAll("// Generated by zig-wayland\n\n"); if (protocol.copyright) |copyright| { var it = mem.split(copyright, "\n"); while (it.next()) |line| { try writer.print("// {s}\n", .{mem.trim(u8, line, &std.ascii.spaces)}); } try writer.writeByte('\n'); } if (protocol.toplevel_description) |toplevel_description| { var it = mem.split(toplevel_description, "\n"); while (it.next()) |line| { try writer.print("// {s}\n", .{mem.trim(u8, line, &std.ascii.spaces)}); } try writer.writeByte('\n'); } } fn emitClient(protocol: Protocol, writer: anytype) !void { try protocol.emitCopyrightAndToplevelDescription(writer); try writer.writeAll( \\const os = @import("std").os; \\const client = @import("wayland.zig").client; \\const common = @import("common.zig"); ); for (protocol.interfaces.items) |interface| try interface.emit(.client, protocol.namespace, writer); } fn emitServer(protocol: Protocol, writer: anytype) !void { try protocol.emitCopyrightAndToplevelDescription(writer); try writer.writeAll( \\const os = @import("std").os; \\const server = @import("wayland.zig").server; \\const common = @import("common.zig"); ); for (protocol.interfaces.items) |interface| try interface.emit(.server, protocol.namespace, writer); } fn emitCommon(protocol: Protocol, writer: anytype) !void { try protocol.emitCopyrightAndToplevelDescription(writer); try writer.writeAll( \\const common = @import("common.zig"); ); for (protocol.interfaces.items) |interface| try interface.emitCommon(writer); } }; const Interface = struct { name: []const u8, version: u32, requests: std.ArrayList(Message), events: std.ArrayList(Message), enums: std.ArrayList(Enum), fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Interface { var name: ?[]const u8 = null; var version: ?u32 = null; var requests = std.ArrayList(Message).init(allocator); var events = std.ArrayList(Message).init(allocator); var enums = std.ArrayList(Enum).init(allocator); while (parser.next()) |ev| switch (ev) { .open_tag => |tag| { // TODO: parse description if (mem.eql(u8, tag, "request")) try requests.append(try Message.parse(allocator, parser)) else if (mem.eql(u8, tag, "event")) try events.append(try Message.parse(allocator, parser)) else if (mem.eql(u8, tag, "enum")) try enums.append(try Enum.parse(allocator, parser)); }, .attribute => |attr| { if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "version")) { if (version != null) return error.DuplicateVersion; version = try std.fmt.parseInt(u32, try attr.dupeValue(allocator), 10); } }, .close_tag => |tag| if (mem.eql(u8, tag, "interface")) { return Interface{ .name = name orelse return error.MissingName, .version = version orelse return error.MissingVersion, .requests = requests, .events = events, .enums = enums, }; }, else => {}, }; return error.UnexpectedEndOfFile; } fn emit(interface: Interface, side: Side, namespace: []const u8, writer: anytype) !void { var buf: [1024]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); try printIdentifier(fbs.writer(), case(.title, trimPrefix(interface.name))); const title_case = fbs.getWritten(); try printIdentifier(fbs.writer(), trimPrefix(interface.name)); const snake_case = fbs.getWritten()[title_case.len..]; try writer.print( \\pub const {s} = opaque {{ \\ pub const getInterface = common.{s}.{s}.getInterface; , .{ title_case, namespace, snake_case }); for (interface.enums.items) |e| { try writer.writeAll("pub const "); try printIdentifier(writer, case(.title, e.name)); try writer.print(" = common.{s}.{s}.", .{ namespace, snake_case }); try printIdentifier(writer, case(.title, e.name)); try writer.writeAll(";\n"); } if (side == .client) { if (interface.events.items.len > 0) { try writer.writeAll("pub const Event = union(enum) {"); for (interface.events.items) |event| try event.emitField(.client, writer); try writer.writeAll("};\n"); try writer.print( \\pub fn setListener( \\ _{s}: *{s}, \\ comptime T: type, \\ _listener: fn ({s}: *{s}, event: Event, data: T) void, \\ _data: T, \\) callconv(.Inline) void {{ \\ const _proxy = @ptrCast(*client.wl.Proxy, _{s}); \\ const _mut_data = @intToPtr(?*c_void, @ptrToInt(_data)); \\ _proxy.addDispatcher(common.Dispatcher({s}, T).dispatcher, _listener, _mut_data); \\}} , .{ snake_case, title_case, snake_case, title_case, snake_case, title_case }); } for (interface.requests.items) |request, opcode| try request.emitFn(side, writer, interface, opcode); if (mem.eql(u8, interface.name, "wl_display")) try writer.writeAll(@embedFile("client_display_functions.zig")); } else { try writer.print( \\pub fn create(_client: *server.wl.Client, _version: u32, _id: u32) !*{s} {{ \\ return @ptrCast(*{s}, try server.wl.Resource.create(_client, {s}, _version, _id)); \\}} , .{ title_case, title_case, title_case }); try writer.print( \\pub fn destroy(_{s}: *{s}) void {{ \\ return @ptrCast(*server.wl.Resource, _{s}).destroy(); \\}} , .{ snake_case, title_case, snake_case }); try writer.print( \\pub fn fromLink(_link: *server.wl.list.Link) *{s} {{ \\ return @ptrCast(*{s}, server.wl.Resource.fromLink(_link)); \\}} , .{ title_case, title_case }); for ([_][2][]const u8{ .{ "getLink", "*server.wl.list.Link" }, .{ "getClient", "*server.wl.Client" }, .{ "getId", "u32" }, .{ "getVersion", "u32" }, .{ "postNoMemory", "void" }, }) |func| try writer.print( \\pub fn {s}(_{s}: *{s}) {s} {{ \\ return @ptrCast(*server.wl.Resource, _{s}).{s}(); \\}} , .{ func[0], snake_case, title_case, func[1], snake_case, func[0] }); const has_error = for (interface.enums.items) |e| { if (mem.eql(u8, e.name, "error")) break true; } else false; if (has_error) { try writer.print( \\pub fn postError({s}: *{s}, _err: Error, _message: [*:0]const u8) void {{ \\ return @ptrCast(*server.wl.Resource, {s}).postError(@intCast(u32, @enumToInt(_err)), _message); \\}} , .{ snake_case, title_case, snake_case }); } if (interface.requests.items.len > 0) { try writer.writeAll("pub const Request = union(enum) {"); for (interface.requests.items) |request| try request.emitField(.server, writer); try writer.writeAll("};\n"); @setEvalBranchQuota(2500); try writer.print( \\pub fn setHandler( \\ _{s}: *{s}, \\ comptime T: type, \\ handle_request: fn ({s}: *{s}, request: Request, data: T) void, \\ comptime handle_destroy: ?fn ({s}: *{s}, data: T) void, \\ _data: T, \\) callconv(.Inline) void {{ \\ const _resource = @ptrCast(*server.wl.Resource, _{s}); \\ _resource.setDispatcher( \\ common.Dispatcher({s}, T).dispatcher, \\ handle_request, \\ @intToPtr(?*c_void, @ptrToInt(_data)), \\ if (handle_destroy) |_handler| struct {{ \\ fn _wrapper(__resource: *server.wl.Resource) callconv(.C) void {{ \\ @call(.{{ .modifier = .always_inline }}, _handler, .{{ \\ @ptrCast(*{s}, __resource), \\ @intToPtr(T, @ptrToInt(__resource.getUserData())), \\ }}); \\ }} \\ }}._wrapper else null, \\ ); \\}} , .{ snake_case, title_case, snake_case, title_case, snake_case, title_case, snake_case, title_case, title_case }); } else { try writer.print( \\pub fn setHandler( \\ _{s}: *{s}, \\ comptime T: type, \\ comptime handle_destroy: ?fn ({s}: *{s}, data: T) void, \\ _data: T, \\) callconv(.Inline) void {{ \\ const _resource = @ptrCast(*server.wl.Resource, {s}); \\ _resource.setDispatcher( \\ null, \\ null, \\ @intToPtr(?*c_void, @ptrToInt(_data)), \\ if (handle_destroy) |_handler| struct {{ \\ fn _wrapper(__resource: *server.wl.Resource) callconv(.C) void {{ \\ @call(.{{ .modifier = .always_inline }}, _handler, .{{ \\ @ptrCast(*{s}, __resource), \\ @intToPtr(T, @ptrToInt(__resource.getUserData())), \\ }}); \\ }} \\ }}._wrapper else null, \\ ); \\}} , .{ snake_case, title_case, snake_case, title_case, snake_case, title_case }); } for (interface.events.items) |event, opcode| try event.emitFn(side, writer, interface, opcode); } try writer.writeAll("};\n"); } fn emitCommon(interface: Interface, writer: anytype) !void { try writer.writeAll("pub const "); try printIdentifier(writer, trimPrefix(interface.name)); // TODO: stop linking libwayland generated interface structs when // https://github.com/ziglang/zig/issues/131 is implemented // //try writer.print( // \\ = struct {{ // \\ pub const interface = common.Interface{{ // \\ .name = "{}", // \\ .version = {}, // \\ .method_count = {}, //, .{ // interface.name, // interface.version, // interface.requests.items.len, //}); //if (interface.requests.items.len > 0) { // try writer.writeAll(".methods = &[_]common.Message{"); // for (interface.requests.items) |request| try request.emitMessage(writer); // try writer.writeAll("},"); //} else { // try writer.writeAll(".methods = null,"); //} //try writer.print(".event_count = {},", .{interface.events.items.len}); //if (interface.events.items.len > 0) { // try writer.writeAll(".events = &[_]common.Message{"); // for (interface.events.items) |event| try event.emitMessage(writer); // try writer.writeAll("},"); //} else { // try writer.writeAll(".events = null,"); //} //try writer.writeAll("};"); try writer.print( \\ = struct {{ \\ extern const {s}_interface: common.Interface; \\ pub fn getInterface() callconv(.Inline) *const common.Interface {{ \\ return &{s}_interface; \\ }} , .{ interface.name, interface.name }); for (interface.enums.items) |e| try e.emit(writer); try writer.writeAll("};"); } }; const Message = struct { name: []const u8, since: u32, args: std.ArrayList(Arg) = std.ArrayList(Arg), kind: union(enum) { normal: void, constructor: ?[]const u8, destructor: void, }, fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Message { var name: ?[]const u8 = null; var since: ?u32 = null; var args = std.ArrayList(Arg).init(allocator); var destructor = false; while (parser.next()) |ev| switch (ev) { .open_tag => |tag| { // TODO: parse description if (mem.eql(u8, tag, "arg")) try args.append(try Arg.parse(allocator, parser)); }, .attribute => |attr| { if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "since")) { if (since != null) return error.DuplicateSince; since = try std.fmt.parseInt(u32, try attr.dupeValue(allocator), 10); } else if (mem.eql(u8, attr.name, "type")) { if (attr.valueEql("destructor")) { destructor = true; } else { return error.InvalidType; } } }, .close_tag => |tag| if (mem.eql(u8, tag, "request") or mem.eql(u8, tag, "event")) { return Message{ .name = name orelse return error.MissingName, .since = since orelse 1, .args = args, .kind = blk: { if (destructor) break :blk .destructor; for (args.items) |arg| if (arg.kind == .new_id) break :blk .{ .constructor = arg.kind.new_id }; break :blk .normal; }, }; }, else => {}, }; return error.UnexpectedEndOfFile; } // TODO: restore this code when zig issue #131 is resoleved //fn emitMessage(message: Message, writer: anytype) !void { // try writer.print(".{{ .name = \"{}\", .signature = \"", .{message.name}); // for (message.args.items) |arg| try arg.emitSignature(writer); // try writer.writeAll("\", .types = "); // if (message.args.items.len > 0) { // try writer.writeAll("&[_]?*const common.Interface{"); // for (message.args.items) |arg| { // switch (arg.kind) { // .object, .new_id => |interface| if (interface) |i| // try writer.print("&common.{}.{}.interface,", .{ prefix(i), trimPrefix(i) }) // else // try writer.writeAll("null,"), // else => try writer.writeAll("null,"), // } // } // try writer.writeAll("},"); // } else { // try writer.writeAll("null,"); // } // try writer.writeAll("},"); //} fn emitField(message: Message, side: Side, writer: anytype) !void { try printIdentifier(writer, message.name); if (message.args.items.len == 0) { try writer.writeAll(": void,"); return; } try writer.writeAll(": struct {"); for (message.args.items) |arg| { if (side == .server and arg.kind == .new_id and arg.kind.new_id == null) { try writer.writeAll("interface_name: [*:0]const u8, version: u32,"); try printIdentifier(writer, arg.name); try writer.writeAll(": u32"); } else if (side == .client and arg.kind == .new_id) { try printIdentifier(writer, arg.name); try writer.writeAll(": *"); try printAbsolute(.client, writer, arg.kind.new_id.?); std.debug.assert(!arg.allow_null); } else { try printIdentifier(writer, arg.name); try writer.writeByte(':'); // See notes on NULL in doc comment for wl_message in wayland-util.h if (side == .client and arg.kind == .object and !arg.allow_null) try writer.writeByte('?'); try arg.emitType(side, writer); } try writer.writeByte(','); } try writer.writeAll("},\n"); } fn emitFn(message: Message, side: Side, writer: anytype, interface: Interface, opcode: usize) !void { try writer.writeAll("pub fn "); if (side == .server) { try writer.writeAll("send"); try printIdentifier(writer, case(.title, message.name)); } else { try printIdentifier(writer, case(.camel, message.name)); } try writer.writeAll("(_"); try printIdentifier(writer, trimPrefix(interface.name)); try writer.writeAll(": *"); try printIdentifier(writer, case(.title, trimPrefix(interface.name))); for (message.args.items) |arg| { if (side == .server and arg.kind == .new_id) { try writer.writeAll(", _"); try printIdentifier(writer, arg.name); try writer.writeByte(':'); if (arg.allow_null) try writer.writeByte('?'); try writer.writeByte('*'); if (arg.kind.new_id) |iface| try printIdentifier(writer, case(.title, trimPrefix(iface))) else try writer.writeAll("server.wl.Resource"); } else if (side == .client and arg.kind == .new_id) { if (arg.kind.new_id == null) try writer.writeAll(", comptime T: type, _version: u32"); } else { try writer.writeAll(", _"); try printIdentifier(writer, arg.name); try writer.writeByte(':'); try arg.emitType(side, writer); } } if (side == .server or message.kind != .constructor) { try writer.writeAll(") void {"); } else if (message.kind.constructor) |new_iface| { try writer.writeAll(") !*"); try printIdentifier(writer, case(.title, trimPrefix(new_iface))); try writer.writeAll("{"); } else { try writer.writeAll(") !*T {"); } if (side == .server) try writer.writeAll("const _resource = @ptrCast(*server.wl.Resource,_") else try writer.writeAll("const _proxy = @ptrCast(*client.wl.Proxy,_"); try printIdentifier(writer, trimPrefix(interface.name)); try writer.writeAll(");"); if (message.args.items.len > 0) { try writer.writeAll("var _args = [_]common.Argument{"); for (message.args.items) |arg| { switch (arg.kind) { .int, .uint, .fixed, .string, .array, .fd => { try writer.writeAll(".{ ."); try arg.emitSignature(writer); try writer.writeAll(" = "); if (arg.enum_name != null) { try writer.writeAll("switch (@typeInfo("); try arg.emitType(side, writer); // TODO We know the type of the enum at scanning time, but it's // currently a bit difficult to access it. const c_type = if (arg.kind == .uint) "u32" else "i32"; try writer.print( \\ )) {{ \\ .Enum => @intCast({s}, @enumToInt(_{s})), \\ .Struct => @bitCast(u32, _{s}), \\ else => unreachable, \\ }} , .{ c_type, arg.name, arg.name }); } else { try writer.writeByte('_'); try printIdentifier(writer, arg.name); } try writer.writeAll("},"); }, .object, .new_id => |new_iface| { if (arg.kind == .object or side == .server) { if (arg.allow_null) { try writer.writeAll(".{ .o = @ptrCast(?*common.Object, _"); } else { try writer.writeAll(".{ .o = @ptrCast(*common.Object, _"); } try printIdentifier(writer, arg.name); try writer.writeAll(") },"); } else { if (new_iface == null) { try writer.writeAll( \\.{ .s = T.getInterface().name }, \\.{ .u = _version }, ); } try writer.writeAll(".{ .o = null },"); } }, } } try writer.writeAll("};\n"); } const args = if (message.args.items.len > 0) "&_args" else "null"; if (side == .server) { try writer.print("_resource.postEvent({}, {s});", .{ opcode, args }); } else switch (message.kind) { .normal, .destructor => { try writer.print("_proxy.marshal({}, {s});", .{ opcode, args }); if (message.kind == .destructor) try writer.writeAll("_proxy.destroy();"); }, .constructor => |new_iface| { if (new_iface) |i| { try writer.writeAll("return @ptrCast(*"); try printIdentifier(writer, case(.title, trimPrefix(i))); try writer.print(", try _proxy.marshalConstructor({}, &_args, ", .{opcode}); try printIdentifier(writer, case(.title, trimPrefix(i))); try writer.writeAll(".getInterface()));"); } else { try writer.print("return @ptrCast(*T, try _proxy.marshalConstructorVersioned({}, &_args, T.getInterface(), _version));", .{opcode}); } }, } try writer.writeAll("}\n"); } }; const Arg = struct { const Type = union(enum) { int, uint, fixed, string, new_id: ?[]const u8, object: ?[]const u8, array, fd, }; name: []const u8, kind: Type, allow_null: bool, enum_name: ?[]const u8, fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Arg { var name: ?[]const u8 = null; var kind: ?std.meta.Tag(Type) = null; var interface: ?[]const u8 = null; var allow_null: ?bool = null; var enum_name: ?[]const u8 = null; while (parser.next()) |ev| switch (ev) { .attribute => |attr| { if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "type")) { if (kind != null) return error.DuplicateType; kind = std.meta.stringToEnum(std.meta.Tag(Type), try attr.dupeValue(allocator)) orelse return error.InvalidType; } else if (mem.eql(u8, attr.name, "interface")) { if (interface != null) return error.DuplicateInterface; interface = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "allow-null")) { if (allow_null != null) return error.DuplicateAllowNull; if (!attr.valueEql("true") and !attr.valueEql("false")) return error.InvalidBoolValue; allow_null = attr.valueEql("true"); } else if (mem.eql(u8, attr.name, "enum")) { if (enum_name != null) return error.DuplicateEnum; enum_name = try attr.dupeValue(allocator); } }, .close_tag => |tag| if (mem.eql(u8, tag, "arg")) { return Arg{ .name = name orelse return error.MissingName, .kind = switch (kind orelse return error.MissingType) { .object => .{ .object = interface }, .new_id => .{ .new_id = interface }, .int => .int, .uint => .uint, .fixed => .fixed, .string => .string, .array => .array, .fd => .fd, }, .allow_null = allow_null orelse false, .enum_name = enum_name, }; }, else => {}, }; return error.UnexpectedEndOfFile; } fn emitSignature(arg: Arg, writer: anytype) !void { switch (arg.kind) { .int => try writer.writeByte('i'), .uint => try writer.writeByte('u'), .fixed => try writer.writeByte('f'), .string => try writer.writeByte('s'), .new_id => |interface| if (interface == null) try writer.writeAll("sun") else try writer.writeByte('n'), .object => try writer.writeByte('o'), .array => try writer.writeByte('a'), .fd => try writer.writeByte('h'), } } fn emitType(arg: Arg, side: Side, writer: anytype) !void { switch (arg.kind) { .int, .uint => { if (arg.enum_name) |name| { if (mem.indexOfScalar(u8, name, '.')) |dot_index| { // Turn a reference like wl_shm.format into common.wl.shm.Format try writer.writeAll("common."); const us_index = mem.indexOfScalar(u8, name, '_') orelse 0; try writer.writeAll(name[0..us_index]); try writer.writeAll("."); try writer.writeAll(name[us_index + 1 .. dot_index + 1]); try writer.writeAll(case(.title, name[dot_index + 1 ..])); } else { try writer.writeAll(case(.title, name)); } } else if (arg.kind == .int) { try writer.writeAll("i32"); } else { try writer.writeAll("u32"); } }, .new_id => try writer.writeAll("u32"), .fixed => try writer.writeAll("common.Fixed"), .string => { if (arg.allow_null) try writer.writeByte('?'); try writer.writeAll("[*:0]const u8"); }, .object => |interface| if (interface) |i| { if (arg.allow_null) try writer.writeAll("?*") else try writer.writeByte('*'); try printAbsolute(side, writer, i); } else { if (arg.allow_null) try writer.writeByte('?'); try writer.writeAll("*common.Object"); }, .array => { if (arg.allow_null) try writer.writeByte('?'); try writer.writeAll("*common.Array"); }, .fd => try writer.writeAll("i32"), } } }; const Enum = struct { name: []const u8, since: u32, entries: std.ArrayList(Entry), bitfield: bool, fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Enum { var name: ?[]const u8 = null; var since: ?u32 = null; var entries = std.ArrayList(Entry).init(allocator); var bitfield: ?bool = null; while (parser.next()) |ev| switch (ev) { .open_tag => |tag| { // TODO: parse description if (mem.eql(u8, tag, "entry")) try entries.append(try Entry.parse(allocator, parser)); }, .attribute => |attr| { if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "since")) { if (since != null) return error.DuplicateSince; since = try std.fmt.parseInt(u32, try attr.dupeValue(allocator), 10); } else if (mem.eql(u8, attr.name, "bitfield")) { if (bitfield != null) return error.DuplicateBitfield; if (!attr.valueEql("true") and !attr.valueEql("false")) return error.InvalidBoolValue; bitfield = attr.valueEql("true"); } }, .close_tag => |tag| if (mem.eql(u8, tag, "enum")) { return Enum{ .name = name orelse return error.MissingName, .since = since orelse 1, .entries = entries, .bitfield = bitfield orelse false, }; }, else => {}, }; return error.UnexpectedEndOfFile; } fn emit(e: Enum, writer: anytype) !void { try writer.writeAll("pub const "); try printIdentifier(writer, case(.title, e.name)); if (e.bitfield) { var entries_emitted: u8 = 0; try writer.writeAll(" = packed struct {"); for (e.entries.items) |entry| { const value = entry.intValue(); if (value != 0 and std.math.isPowerOfTwo(value)) { try printIdentifier(writer, entry.name); if (entries_emitted == 0) { // Align the first field to ensure the entire packed // struct matches the alignment of a u32. This allows // using the packed struct as the field of an extern // struct where a u32 is expected. try writer.writeAll(": bool align(@alignOf(u32)) = false,"); } else { try writer.writeAll(": bool = false,"); } entries_emitted += 1; } } // Pad to 32 bits. Use only bools to avoid zig stage1 packed // struct bugs. while (entries_emitted < 32) : (entries_emitted += 1) { try writer.print("_paddding{}: bool = false,\n", .{entries_emitted}); } // Emit the normal C abi enum as well as it may be needed to interface // with C code. try writer.writeAll("pub const Enum "); } try writer.writeAll(" = extern enum(c_int) {"); for (e.entries.items) |entry| { try printIdentifier(writer, entry.name); try writer.print("= {s},", .{entry.value}); } // Always generate non-exhaustive enums to ensure forward compatability. // Entries have been added to wl_shm.format without bumping the version. try writer.writeAll("_,};\n"); if (e.bitfield) try writer.writeAll("};\n"); } }; const Entry = struct { name: []const u8, since: u32, value: []const u8, fn parse(allocator: *mem.Allocator, parser: *xml.Parser) !Entry { var name: ?[]const u8 = null; var since: ?u32 = null; var value: ?[]const u8 = null; while (parser.next()) |ev| switch (ev) { .attribute => |attr| { if (mem.eql(u8, attr.name, "name")) { if (name != null) return error.DuplicateName; name = try attr.dupeValue(allocator); } else if (mem.eql(u8, attr.name, "since")) { if (since != null) return error.DuplicateSince; since = try std.fmt.parseInt(u32, try attr.dupeValue(allocator), 10); } else if (mem.eql(u8, attr.name, "value")) { if (value != null) return error.DuplicateName; value = try attr.dupeValue(allocator); } }, .close_tag => |tag| if (mem.eql(u8, tag, "entry")) { return Entry{ .name = name orelse return error.MissingName, .since = since orelse 1, .value = value orelse return error.MissingValue, }; }, else => {}, }; return error.UnexpectedEndOfFile; } // Return numeric value of enum entry. Can be base 10 and hexadecimal notation. fn intValue(e: Entry) u32 { return std.fmt.parseInt(u32, e.value, 10) catch blk: { const index = mem.indexOfScalar(u8, e.value, 'x').?; break :blk std.fmt.parseInt(u32, e.value[index + 1 ..], 16) catch @panic("Can't parse enum entry."); }; } }; fn prefix(s: []const u8) ?[]const u8 { return s[0 .. mem.indexOfScalar(u8, s, '_') orelse return null]; } fn trimPrefix(s: []const u8) []const u8 { return s[mem.indexOfScalar(u8, s, '_').? + 1 ..]; } var case_buf: [512]u8 = undefined; fn case(out_case: enum { title, camel }, snake_case: []const u8) []const u8 { var i: usize = 0; var upper = out_case == .title; for (snake_case) |ch| { if (ch == '_') { upper = true; continue; } case_buf[i] = if (upper) std.ascii.toUpper(ch) else ch; i += 1; upper = false; } return case_buf[0..i]; } fn printAbsolute(side: Side, writer: anytype, interface: []const u8) !void { try writer.writeAll(@tagName(side)); try writer.writeByte('.'); try printIdentifier(writer, prefix(interface) orelse return error.MissingPrefix); try writer.writeByte('.'); try printIdentifier(writer, case(.title, trimPrefix(interface))); } fn printIdentifier(writer: anytype, identifier: []const u8) !void { if (isValidIdentifier(identifier)) try writer.writeAll(identifier) else try writer.print("@\"{s}\"", .{identifier}); } fn isValidIdentifier(identifier: []const u8) bool { // !keyword [A-Za-z_] [A-Za-z0-9_]* if (identifier.len == 0) return false; for (identifier) |ch, i| switch (ch) { 'A'...'Z', 'a'...'z', '_' => {}, '0'...'9' => if (i == 0) return false, else => return false, }; return std.zig.Token.getKeyword(identifier) == null; } test "parsing" { const testing = std.testing; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const protocol = try Protocol.parseXML(&arena.allocator, @embedFile("../protocol/wayland.xml")); testing.expectEqualSlices(u8, "wayland", protocol.name); testing.expectEqual(@as(usize, 22), protocol.interfaces.items.len); { const wl_display = protocol.interfaces.items[0]; testing.expectEqualSlices(u8, "wl_display", wl_display.name); testing.expectEqual(@as(u32, 1), wl_display.version); testing.expectEqual(@as(usize, 2), wl_display.requests.items.len); testing.expectEqual(@as(usize, 2), wl_display.events.items.len); testing.expectEqual(@as(usize, 1), wl_display.enums.items.len); { const sync = wl_display.requests.items[0]; testing.expectEqualSlices(u8, "sync", sync.name); testing.expectEqual(@as(u32, 1), sync.since); testing.expectEqual(@as(usize, 1), sync.args.items.len); { const callback = sync.args.items[0]; testing.expectEqualSlices(u8, "callback", callback.name); testing.expect(callback.kind == .new_id); testing.expectEqualSlices(u8, "wl_callback", callback.kind.new_id.?); testing.expectEqual(false, callback.allow_null); testing.expectEqual(@as(?[]const u8, null), callback.enum_name); } testing.expect(sync.kind == .constructor); } { const error_event = wl_display.events.items[0]; testing.expectEqualSlices(u8, "error", error_event.name); testing.expectEqual(@as(u32, 1), error_event.since); testing.expectEqual(@as(usize, 3), error_event.args.items.len); { const object_id = error_event.args.items[0]; testing.expectEqualSlices(u8, "object_id", object_id.name); testing.expectEqual(Arg.Type{ .object = null }, object_id.kind); testing.expectEqual(false, object_id.allow_null); testing.expectEqual(@as(?[]const u8, null), object_id.enum_name); } { const code = error_event.args.items[1]; testing.expectEqualSlices(u8, "code", code.name); testing.expectEqual(Arg.Type.uint, code.kind); testing.expectEqual(false, code.allow_null); testing.expectEqual(@as(?[]const u8, null), code.enum_name); } { const message = error_event.args.items[2]; testing.expectEqualSlices(u8, "message", message.name); testing.expectEqual(Arg.Type.string, message.kind); testing.expectEqual(false, message.allow_null); testing.expectEqual(@as(?[]const u8, null), message.enum_name); } } { const error_enum = wl_display.enums.items[0]; testing.expectEqualSlices(u8, "error", error_enum.name); testing.expectEqual(@as(u32, 1), error_enum.since); testing.expectEqual(@as(usize, 4), error_enum.entries.items.len); { const invalid_object = error_enum.entries.items[0]; testing.expectEqualSlices(u8, "invalid_object", invalid_object.name); testing.expectEqual(@as(u32, 1), invalid_object.since); testing.expectEqualSlices(u8, "0", invalid_object.value); } { const invalid_method = error_enum.entries.items[1]; testing.expectEqualSlices(u8, "invalid_method", invalid_method.name); testing.expectEqual(@as(u32, 1), invalid_method.since); testing.expectEqualSlices(u8, "1", invalid_method.value); } { const no_memory = error_enum.entries.items[2]; testing.expectEqualSlices(u8, "no_memory", no_memory.name); testing.expectEqual(@as(u32, 1), no_memory.since); testing.expectEqualSlices(u8, "2", no_memory.value); } { const implementation = error_enum.entries.items[3]; testing.expectEqualSlices(u8, "implementation", implementation.name); testing.expectEqual(@as(u32, 1), implementation.since); testing.expectEqualSlices(u8, "3", implementation.value); } testing.expectEqual(false, error_enum.bitfield); } } { const wl_data_offer = protocol.interfaces.items[7]; testing.expectEqualSlices(u8, "wl_data_offer", wl_data_offer.name); testing.expectEqual(@as(u32, 3), wl_data_offer.version); testing.expectEqual(@as(usize, 5), wl_data_offer.requests.items.len); testing.expectEqual(@as(usize, 3), wl_data_offer.events.items.len); testing.expectEqual(@as(usize, 1), wl_data_offer.enums.items.len); { const accept = wl_data_offer.requests.items[0]; testing.expectEqualSlices(u8, "accept", accept.name); testing.expectEqual(@as(u32, 1), accept.since); testing.expectEqual(@as(usize, 2), accept.args.items.len); { const serial = accept.args.items[0]; testing.expectEqualSlices(u8, "serial", serial.name); testing.expectEqual(Arg.Type.uint, serial.kind); testing.expectEqual(false, serial.allow_null); } { const mime_type = accept.args.items[1]; testing.expectEqualSlices(u8, "mime_type", mime_type.name); testing.expectEqual(Arg.Type.string, mime_type.kind); testing.expectEqual(true, mime_type.allow_null); } } } }
src/scanner.zig
const std = @import("std"); const fs = std.fs; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_09_1.txt", std.math.maxInt(usize)); var lines = std.mem.tokenize(input, "\n"); var vals = std.ArrayList(usize).init(allocator); defer vals.deinit(); while (lines.next()) |raw_line| { var line = std.mem.trim(u8, raw_line, " \r\n"); if (line.len == 0) break; try vals.append(try std.fmt.parseInt(usize, line, 10)); } var solution1: usize = 0; { // Solution 1 var index: usize = 25; outer: while (index < vals.items.len) : (index += 1) { const prevs1 = vals.items[index - 25..index - 1]; var prevs2 = vals.items[index - 24..index]; for (prevs1) |prev1| { for (prevs2) |prev2| { if (prev1 + prev2 == vals.items[index]) { continue :outer; } } } solution1 = vals.items[index]; std.debug.print("Day 09 - Solution 1: {}\n", .{solution1}); break; } } { // Solution 2 var temp_sums = try std.ArrayList(usize).initCapacity(allocator, vals.items.len - 1); defer temp_sums.deinit(); try temp_sums.resize(vals.items.len); std.mem.copy(usize, temp_sums.items, vals.items); var solution2: usize = 0; var distance: usize = 1; outer: while (distance < (vals.items.len - 1)) { var i: usize = 0; var end = vals.items.len - distance; while (i < end) : (i += 1) { temp_sums.items[i] += vals.items[i + distance]; if (temp_sums.items[i] == solution1) { var min: usize = solution1; var max: usize = 0; const to_sum = vals.items[i..i + distance + 1]; for (to_sum) |v| { min = std.math.min(min, v); max = std.math.max(max, v); } solution2 = max + min; break :outer; } } distance += 1; } std.debug.print("Day 09 - Solution 2: {}\n", .{solution2}); } }
2020/src/day_09.zig
const std = @import("std"); const util = @import("aoc_util"); const print = std.debug.print; const fmt = std.fmt; const mem = std.mem; //const input = @embedFile("../../input/day_02.txt"); const instruction = enum{fwd, up, down}; const forward = "forward"; const up = "up"; const down = "down"; const sub_cmd = struct{ inst: instruction, value: u16, }; const sub_pos = struct{ depth: i64 = 0, distance: i64 = 0, }; pub fn main() !void { print("---Part 1 result---\n", .{}); print("{}\n", .{try part1()}); print("---Part 2 result---\n", .{}); print("{}", .{try part2()}); } pub fn part1() !i64{ //initialize sub position var position = sub_pos{}; //pull and tokenize the file input, each line is one command const input: []u8 = try util.getInputLines(2, 0x2FFF); var commands = mem.tokenize(u8, input, "\n"); //cycle through the lines in the file while(commands.next()) |command_str| { //tokenize the line var command = mem.tokenize(u8, command_str, " "); var inst_str = command.next().?; var val_str = command.next().?; // and use it to populate a struct var cur_cmd = sub_cmd{ .inst = parse: { if (mem.eql(u8, forward[0..], inst_str)){ break :parse instruction.fwd; } else if (mem.eql(u8, up[0..], inst_str)){ break :parse instruction.up; } else if (mem.eql(u8, down[0..], inst_str)){ break :parse instruction.down; } else unreachable; }, .value = try fmt.parseInt(u16, val_str, 10), }; switch(cur_cmd.inst){ instruction.fwd => position.distance += cur_cmd.value, instruction.up => position.depth -= cur_cmd.value, instruction.down => position.depth += cur_cmd.value, } } return position.depth * position.distance; } pub fn part2() !i128{ //initialize sub position var position = sub_pos{}; var aim :i32 = 0; //pull and tokenize the file input, each line is one command const input: []u8 = try util.getInputLines(2, 0x2FFF); var commands = mem.tokenize(u8, input, "\n"); //cycle through the lines in the file while(commands.next()) |command_str| { //tokenize the line var command = mem.tokenize(u8, command_str, " "); var inst_str = command.next().?; var val_str = command.next().?; // and use it to populate a struct var cur_cmd = sub_cmd{ .inst = parse: { if (mem.eql(u8, forward[0..], inst_str)){ break :parse instruction.fwd; } else if (mem.eql(u8, up[0..], inst_str)){ break :parse instruction.up; } else if (mem.eql(u8, down[0..], inst_str)){ break :parse instruction.down; } else unreachable; }, .value = try fmt.parseInt(u16, val_str, 10), }; switch(cur_cmd.inst){ instruction.fwd => { position.distance += cur_cmd.value; position.depth += (cur_cmd.value * aim); }, instruction.up => aim += cur_cmd.value, instruction.down => aim -= cur_cmd.value, } print("aim: {}\n", .{aim}); } return position.depth * position.distance; }
src/day-02/dive.zig
const std = @import("std"); const print = std.debug.print; const assert = std.debug.assert; const threads = @import("threads.zig"); const config = @import("config.zig"); pub const Camera = struct { ctx: threads.CameraContext, child: std.ChildProcess, pub fn start(self: *Camera) bool {} pub fn stop(self: *Camera) bool {} pub fn restart(self: *Camera) bool {} }; pub fn init(ctx: threads.CameraContext) Camera { return Camera{ .ctx = ctx }; } fn build_argv(ctx: threads.CameraContext) !std.ArrayList([]const u8) { var argv = std.ArrayList([]const u8).init(ctx.allocator); try argv.appendSlice(&[_][]const u8{ "setarch", "linux32" }); try argv.append("$HOME/capable_camera_firmware/camera/build/libcamera-bridge"); try argv.appendSlice(&[_][]const u8{ "--codec", "mjpeg" }); try argv.appendSlice(&[_][]const u8{ "--segment", "0" }); try argv.appendSlice(&[_][]const u8{ "--timeout", "0" }); std.log.info("socket {s}", .{ctx.socket}); const sock_path = try std.fmt.allocPrint(ctx.allocator, "sck://{s}", .{ctx.socket}); try argv.appendSlice(&[_][]const u8{ "-o", sock_path }); return argv; } pub fn bridge_thread(ctx: threads.CameraContext) void { var argv = build_argv(ctx) catch |err| { std.log.err("Could not build argv for camera bridge: {s}", .{err}); return; }; defer argv.deinit(); std.log.info("starting camera bridge: {s}", .{argv.toOwnedSlice()}); while (true) { var proc = std.ChildProcess.init(argv.items, ctx.allocator) catch |err| { std.log.err("Could not init camera bridge child process: {s}", .{err}); return; }; defer proc.deinit(); proc.spawn() catch |err| { std.log.err("Could not spawn camera bridge child process: {s}", .{err}); continue; }; wait_for_child(proc) catch |err| { std.log.err("Could not wait for camera bridge child process: {s}", .{err}); continue; }; std.time.sleep(1 * std.time.ns_per_s); } } fn wait_for_child(proc: *std.ChildProcess) !void { while (true) { switch (try proc.spawnAndWait()) { .Exited => |code| { std.log.err("[restarter] child process exited with {}", .{code}); return; }, .Stopped => |sig| std.log.err("[restarter] child process has stopped ({})", .{sig}), .Signal => |sig| std.log.info("[restarter] child process signal ({})", .{sig}), .Unknown => |sig| std.log.info("[restarter] child process unknown ({})", .{sig}), } } }
src/camera.zig
const uefi = @import("std").os.uefi; const Guid = uefi.Guid; /// UEFI Specification, Version 2.8, 12.9 pub const GraphicsOutputProtocol = extern struct { _query_mode: extern fn (*const GraphicsOutputProtocol, u32, *usize, **GraphicsOutputModeInformation) usize, _set_mode: extern fn (*const GraphicsOutputProtocol, u32) usize, _blt: extern fn (*const GraphicsOutputProtocol, ?[*]GraphicsOutputBltPixel, GraphicsOutputBltOperation, usize, usize, usize, usize, usize, usize, usize) usize, mode: *GraphicsOutputProtocolMode, pub fn queryMode(self: *const GraphicsOutputProtocol, mode: u32, size_of_info: *usize, info: **GraphicsOutputModeInformation) usize { return self._query_mode(self, mode, size_of_info, info); } pub fn setMode(self: *const GraphicsOutputProtocol, mode: u32) usize { return self._set_mode(self, mode); } pub fn blt(self: *const GraphicsOutputProtocol, blt_buffer: ?[*]GraphicsOutputBltPixel, blt_operation: GraphicsOutputBltOperation, source_x: usize, source_y: usize, destination_x: usize, destination_y: usize, width: usize, height: usize, delta: usize) usize { return self._blt(self, blt_buffer, blt_operation, source_x, source_y, destination_x, destination_y, width, height, delta); } pub const guid align(8) = Guid{ .time_low = 0x9042a9de, .time_mid = 0x23dc, .time_high_and_version = 0x4a38, .clock_seq_high_and_reserved = 0x96, .clock_seq_low = 0xfb, .node = [_]u8{ 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a }, }; }; pub const GraphicsOutputProtocolMode = extern struct { max_mode: u32, mode: u32, info: *GraphicsOutputModeInformation, size_of_info: usize, frame_buffer_base: u64, frame_buffer_size: usize, }; pub const GraphicsOutputModeInformation = extern struct { version: u32 = undefined, horizontal_resolution: u32 = undefined, vertical_resolution: u32 = undefined, pixel_format: GraphicsPixelFormat = undefined, pixel_information: PixelBitmask = undefined, pixels_per_scan_line: u32 = undefined, }; pub const GraphicsPixelFormat = extern enum(u32) { PixelRedGreenBlueReserved8BitPerColor, PixelBlueGreenRedReserved8BitPerColor, PixelBitMask, PixelBltOnly, PixelFormatMax, }; pub const PixelBitmask = extern struct { red_mask: u32, green_mask: u32, blue_mask: u32, reserved_mask: u32, }; pub const GraphicsOutputBltPixel = extern struct { blue: u8, green: u8, red: u8, reserved: u8 = undefined, }; pub const GraphicsOutputBltOperation = extern enum(u32) { BltVideoFill, BltVideoToBltBuffer, BltBufferToVideo, BltVideoToVideo, GraphicsOutputBltOperationMax, };
lib/std/os/uefi/protocols/graphics_output_protocol.zig
const std = @import("../std.zig"); const Cpu = std.Target.Cpu; pub const Feature = enum { atomics, bulk_memory, exception_handling, multivalue, mutable_globals, nontrapping_fptoint, sign_ext, simd128, tail_call, unimplemented_simd128, }; pub usingnamespace Cpu.Feature.feature_set_fns(Feature); pub const all_features = blk: { const len = @typeInfo(Feature).Enum.fields.len; std.debug.assert(len <= Cpu.Feature.Set.needed_bit_count); var result: [len]Cpu.Feature = undefined; result[@enumToInt(Feature.atomics)] = .{ .llvm_name = "atomics", .description = "Enable Atomics", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.bulk_memory)] = .{ .llvm_name = "bulk-memory", .description = "Enable bulk memory operations", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.exception_handling)] = .{ .llvm_name = "exception-handling", .description = "Enable Wasm exception handling", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.multivalue)] = .{ .llvm_name = "multivalue", .description = "Enable multivalue blocks, instructions, and functions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.mutable_globals)] = .{ .llvm_name = "mutable-globals", .description = "Enable mutable globals", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.nontrapping_fptoint)] = .{ .llvm_name = "nontrapping-fptoint", .description = "Enable non-trapping float-to-int conversion operators", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sign_ext)] = .{ .llvm_name = "sign-ext", .description = "Enable sign extension operators", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.simd128)] = .{ .llvm_name = "simd128", .description = "Enable 128-bit SIMD", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.tail_call)] = .{ .llvm_name = "tail-call", .description = "Enable tail call instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.unimplemented_simd128)] = .{ .llvm_name = "unimplemented-simd128", .description = "Enable 128-bit SIMD not yet implemented in engines", .dependencies = featureSet(&[_]Feature{ .simd128, }), }; const ti = @typeInfo(Feature); for (result) |*elem, i| { elem.index = i; elem.name = ti.Enum.fields[i].name; } break :blk result; }; pub const cpu = struct { pub const bleeding_edge = Cpu{ .name = "bleeding_edge", .llvm_name = "bleeding-edge", .features = featureSet(&[_]Feature{ .atomics, .mutable_globals, .nontrapping_fptoint, .sign_ext, .simd128, }), }; pub const generic = Cpu{ .name = "generic", .llvm_name = "generic", .features = featureSet(&[_]Feature{}), }; pub const mvp = Cpu{ .name = "mvp", .llvm_name = "mvp", .features = featureSet(&[_]Feature{}), }; }; /// All wasm CPUs, sorted alphabetically by name. /// TODO: Replace this with usage of `std.meta.declList`. It does work, but stage1 /// compiler has inefficient memory and CPU usage, affecting build times. pub const all_cpus = &[_]*const Cpu{ &cpu.bleeding_edge, &cpu.generic, &cpu.mvp, };
lib/std/target/wasm.zig
const std = @import("std"); const assert = std.debug.assert; const warn = std.debug.warn; const Allocator = std.mem.Allocator; usingnamespace @import("../main/util.zig"); const system = @import("system.zig"); const EntityComponentDataList = struct { hash: Hash, tmp_ids: []Entity, data_list: Variant, }; const EntityCreateHierarchy = struct { tmp_ids: []Entity, child_offsets: []u32, child_counts: []u32, depth_offsets: []u32, }; const entityCreateBakeFunc = fn (sys: *system.SystemSelf, params: VariantMap, ents: []Entity, data: EntityComponentDataList) void; pub fn entityCreateWrapper(comptime SystemT: type, comptime sysFunc: var, comptime ContextT: type, comptime DataT: type) entityCreateBakeFunc { return struct { fn func(self: *system.SystemSelf, params: VariantMap, ents: []Entity, data: EntityComponentDataList) void { var sys = @ptrCast(*SystemT, @alignCast(@alignOf(*SystemT), self)); var context = fillContext(params, ContextT); var dataSlice = data.data_list.get_slice(DataT, TagUnset); sysFunc(sys, context, ents, dataSlice); } }.func; } const EntityCreateCallback = struct { user_data: Variant, pass: u8, component_tags: []Tag, component_indices: []u16 = undefined, component_variants: []Variant = undefined, }; const EntityCreateData = struct { count: u64, component_datas: EntityComponentDataList, }; const EntityDestroyData = struct { tag: Tag, entities: ArrayList(Entity), pub fn init(allocator: *Allocator, tag: Tag, once: bool) EntityDestroyData { return .{ .tag = tag, .entities = ArrayList(Entity).init(allocator), .allocator = allocator, }; } pub fn deinit(self: *EntityDestroyData) void { self.entities.free(); } }; const EntityDestroyData = struct { entities: std.ArrayList(Entity), }; const ComponentCreateData = struct { entities: std.ArrayList(Entity), component_data: std.ArrayList(u8), components:Variant, tag: FullTag, pub fn init(tag_string:String, allocator:*Allocator) ComponentCreateData{ var component_data = ArrayList(u8).init(Allocator); var tag = FullTag.init(tag_string); return .{ .entities = ArrayList(Entity).init(allocator), .component_data = component_data, .component = Variant.create_slice(component_data.toSlice(), tag.tag), .tag = tag, }; } }; const EntityManager = struct { max_entity_count: Entity, idlol: Entity = 1, create_data: [2]EntityCreateData, destroy_data: [2]EntityDestroyData, entities_to_create: []std.ArrayList(Entity), entities_to_destroy: []std.ArrayList(Entity), comps_to_create: std.ArrayList(ComponentCreateData), entity_create_callbacks: std.ArrayList(EntityCreateCallback), allocator: *Allocator, max_passes = 0, passes: []std.ArrayList(entityCreateBakeFunc), entity_create_buffers: DoubleBuffer(ArrayList(EntityCreateData)), entity_destroy_buffers: DoubleBuffer(EntityDestroyData), pub fn init(allocator: *Allocator) !EntityManager { return try EntityManager{ .allocator = allocator, .entity_create_buffers = DoubleBuffer(Variant).init(allocator), .entity_destroy_buffers = DoubleBuffer(EntityDestroyData).init(allocator), }; } pub fn deinit(self: EntityManager) void { self.entity_create_buffers.deinit(); } pub fn registerComponent(self: *EntityManager, comptime CompT: type, tag_string: String) void { for (self.entity_create_buffers.buffers) |buf| { var comp_create_data = EntityCreateData.init(CompT, tag_string, self.allocator); buf.add(comp_create_data); } } // pub fn addEntitiesDestroyedNotification(self: *EntityManager, entities: []Entity, tag: Tag) void {} // pub fn registerCreateCallback(self: *EntityManager, comptime CompT: type, callback: EntityCreateCallback) void { // var component_indices = self.allocator.alloc(u16, callback.component_tags.len); // var component_variants = self.allocator.alloc(Variant, callback.component_tags.len); // var component_count = 0; // for (self.comps_to_create) |variant, index| { // if (variant.tag == callback.component_tag) { // component_indices[component_count] = index; // component_variants[component_count] = variant; // component_count += 1; // } // }asdas // assert(component_count == callback.component_tags.len); // sadfdadasdas // for (self.entity_create_callbacks) |cb, index| { // if (callback.pass < cb.pass) { // var cb_new = callback; // cb_new.component_indices = component_indices; // cb_new.component_variants = component_variants; // self.entity_create_callbacks.insert(index, callback); // return; // } // } // var cb_new = callback; // cb_new.component_indices = component_indices; // cb_new.component_variants = component_variants; // self.entity_create_callbacks.append(cb_new); // } pub fn commitPending(self: *EntityManager) void { while (self.entity_destroy_buffers.currHasData() || self.entity_create_buffers.currHasData()) { while (self.entities_to_destroy.count() > 0) { // while (self.entity_destroy_buffers.currHasData()) { for (self.comp_datas) |comp| { comp.destroyed_entities.resize(0); for (self.entities_to_destroy) |ent| { if (comp.tracked_entities[ent]) { comp.destroyed_entities.append(ent); } } } self.entities_to_destroy.resize(0); var params = VariantMap.init(self.allocator); params.putNoClobber("allocator", Variant.create_ptr(self.allocator, 0)); for (self.comp_datas) |comp| { params.putNoClobber(comp.tag, Variant.create_slice(comp.destroyed_entities.toSlice(), comp.tag)); } self.system_manager.runSystemFunc("destroyEntities", params); } while (self.entity_create_buffers.currHasData()) { var create_datas = self.entity_create_buffers.currSlice(); self.entity_create_buffers.swap(); var params = VariantMap.init(self.allocator); params.putNoClobber("allocator", self.allocator); for (self.entity_create_buffers.currSlice()) |comp_variant| { params.putNoClobber(comp_create_data.components.tag, comp_create_data); } self.system_manager.runSystemFunc("createEntities", params); } } } // fn createEntities(hierarchy: EntityCreateHierarchy, comp_datas: []EntityComponentDataList, out_ents: []Entity) void { // for (out_ents) |*ent| { // ent.* = idlol; // idlol += 1; // } // var pass_max = 0; // for (comp_datas) |data| { // var entityCreate = self.funcs.get(data.hash); // if (entityCreate.pass > pass_max) { // pass_max = entityCreate.pass; // } // } // // self.id_store.generate(out_ents); // for (hierarchy.depth_offsets) |depth_offset, depth| { // var pass = 0; // while (pass <= pass_max) { // for (comp_datas) |data| { // // TODO: Sort? // var entityCreate = self.funcs.get(data.id); // if (entityCreate.pass != pass) { // continue; // } // var ents: []Entity = self.allocator.alloc(Entity, data.tmp_ids); // for (ents) |*ent| { // ent.* = out_ents[ent.*]; // } // entityCreate(sys, params, ents, data_list); // self.allocator.free(ents); // } // pass += 1; // } // } // } fn createEntities(self:*EntityManager, defs:[]EntityDef)void{ var buf = self.entity_create_buffers.front(); for (defs)|def|{ for (def.components)|comp|{ var comp_data = buf.comp_datas.get(comp.tag); comp_data.component_datas } } } fn destroyEntities(self: *EntityManager, entities: []Entity) void { self.entities_to_destroy.add(entities); } }; fn lol() void { // var hierarchy = EntityCreateHierarchy { // tmp_ids = 0, // } // var comp_datas = EntityComponentDataList{ // .hash = stringHash("transform"), // .tmp_ids = {1}, // .data_list = {Variant.create_slice(math3d.Mat4.identity())}, // }; var entity_def = EntityDef{ .components = .{ .{ .hash = stringHash("transform"), .value = Variant.set_ptr(&math3d.Mat4.identity()), }, .{ .hash = stringHash("model"), .value = Variant.set_slice("models/lol.model"), }, }, .child_entities = .{ .components = .{ .{ .hash = stringHash("transform"), .value = math3d.Mat4.identity(), }, }, }, }; var init_data = entity_def.compile(allocator); entity_manager.createEntities(init_data); // entity_manager.createEntities(hierarchy, comp_datas, out_ents); }
code/core/entity.zig
const std = @import("std"); const assert = std.debug.assert; const x86 = @import("machine.zig"); usingnamespace (@import("types.zig")); const ModRmResult = x86.operand.ModRmResult; const Immediate = x86.operand.Immediate; const Address = x86.operand.Address; const MOffsetDisp = x86.operand.MOffsetDisp; const Register = x86.Register; const AvxOpcode = x86.avx.AvxOpcode; const AvxResult = x86.avx.AvxResult; const InstructionItem = x86.database.InstructionItem; // LegacyPrefixes | REX/VEX/EVEX | OPCODE(0,1,2,3) | ModRM | SIB | displacement(0,1,2,4) | immediate(0,1,2,4) pub const prefix_max_len = 4; pub const ext_max_len = 1; pub const opcode_max_len = 4; pub const modrm_max_len = 1; pub const sib_max_len = 1; pub const displacement_max_len = 8; pub const immediate_max_len = 8; pub const instruction_max_len = 15; pub const ViewPtr = struct { offset: u8 = 0, size: u8 = 0, }; /// Slices to parts of an instruction pub const View = struct { prefix: ViewPtr = ViewPtr{}, ext: ViewPtr = ViewPtr{}, opcode: ViewPtr = ViewPtr{}, modrm: ViewPtr = ViewPtr{}, sib: ViewPtr = ViewPtr{}, displacement: ViewPtr = ViewPtr{}, immediate: ViewPtr = ViewPtr{}, }; pub const Instruction = struct { pub const max_length = 15; data: [max_length]u8 = undefined, len: u8 = 0, view: View = View{}, pub fn asSlice(self: @This()) []const u8 { return self.data[0..self.len]; } pub fn asMutSlice(self: *@This()) []u8 { return self.data[0..self.len]; } fn viewSlice(self: @This(), vptr: ?ViewPtr) ?[]const u8 { if (vptr) |v| { return self.data[v.offset..(v.offset + v.size)]; } else { return null; } } fn viewMutSlice(self: *@This(), vptr: ?ViewPtr) ?[]u8 { if (vptr) |v| { return self.data[v.offset..(v.offset + v.size)]; } else { return null; } } fn debugPrint(self: @This()) void { const warn = if (true) std.debug.warn else util.warnDummy; warn("Instruction {{", .{}); if (self.view.prefix.size != 0) { warn(" Pre:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.prefix))}); } if (self.view.ext.size != 0) { warn(" Ext:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.ext))}); } if (self.view.opcode.size != 0) { warn(" Op:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.opcode))}); } if (self.view.modrm.size != 0) { warn(" Rm:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.modrm))}); } if (self.view.sib.size != 0) { warn(" Sib:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.sib))}); } if (self.view.displacement.size != 0) { warn(" Dis:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.displacement))}); } if (self.view.immediate.size != 0) { warn(" Imm:{}", .{std.fmt.fmtSliceHexLower(self.viewSlice(self.view.immediate))}); } warn(" }}\n", .{}); } fn makeViewPart(self: *@This(), size: u8) ViewPtr { assert(self.len + size <= max_length); return ViewPtr{ .offset = @intCast(u8, self.len), .size = size, }; } fn addBytes(self: *@This(), bytes: []const u8) void { std.mem.copy(u8, self.data[self.len..], bytes[0..]); self.len += @intCast(u8, bytes.len); } fn addByte(self: *@This(), byte: u8) void { self.data[self.len] = byte; self.len += 1; } fn addPrefixSlice(self: *@This(), prefix_slice: []const Prefix) void { for (prefix_slice) |pre| { if (pre == .None) { break; } self.addByte(@enumToInt(pre)); } } fn checkLengthError( instr_item: *const InstructionItem, enc_ctrl: *const EncodingControl, prefixes: Prefixes, modrm_: ?ModRmResult, ) AsmError!void { var len = instr_item.calcLengthLegacy(modrm_); if (modrm_ != null and modrm_.?.isRexRequired()) { len += 1; } len += enc_ctrl.prefixCount(); if (!enc_ctrl.useExactPrefixes()) { len += prefixes.len; } if (len > Instruction.max_length) { return AsmError.InstructionTooLong; } } pub fn addUserPrefixes( self: *@This(), ctrl: *const EncodingControl, prefixes: Prefixes, ) AsmError!void { self.addPrefixSlice(ctrl.prefixes[0..]); if (ctrl.useExactPrefixes() and !ctrl.hasNecessaryPrefixes(prefixes)) { return AsmError.InvalidPrefixes; } if (!ctrl.useExactPrefixes()) { self.addPrefixSlice(prefixes.prefixes[0..]); } } pub fn addStandardPrefixes(self: *@This(), prefix: Prefixes, opcode: Opcode) void { if (prefix.len == 0 and !opcode.hasPrefixByte()) { return; } if (opcode.hasPrefixByte()) { self.view.prefix = self.makeViewPart(prefix.len + 1); self.addBytes(prefix.asSlice()); self.addByte(@enumToInt(opcode.prefix)); } else { self.view.prefix = self.makeViewPart(prefix.len); self.addBytes(prefix.asSlice()); } } pub fn addPrefixes( self: *@This(), instr_item: *const InstructionItem, enc_ctrl: ?*const EncodingControl, prefixes: Prefixes, modrm_: ?ModRmResult, opcode: Opcode, ) AsmError!void { if (enc_ctrl) |ctrl| { var normal_prefixes = prefixes; if (opcode.hasPrefixByte()) { normal_prefixes.addPrefix(@intToEnum(Prefix, @enumToInt(opcode.prefix))); } try checkLengthError(instr_item, ctrl, normal_prefixes, modrm_); try self.addUserPrefixes(ctrl, normal_prefixes); } else { self.addStandardPrefixes(prefixes, opcode); } } // TODO: need to handle more cases, and those interacting with different addressing modes pub fn addRex(self: *@This(), mode: Mode86, reg: ?Register, rm: ?Register, overides: Overides) AsmError!void { const reg_num = if (reg == null) 0 else reg.?.number(); const rm_num = if (rm == null) 0 else rm.?.number(); var needs_rex = false; var needs_no_rex = false; var w: u1 = 0; if (reg != null and reg.?.needsRex()) { needs_rex = true; } if (rm != null and rm.?.needsRex()) { needs_rex = true; } if (reg != null and reg.?.needsNoRex()) { needs_no_rex = true; } if (rm != null and rm.?.needsNoRex()) { needs_no_rex = true; } if (!overides.is64Default()) { if (reg != null and reg.?.bitSize() == .Bit64) { w = 1; } if (rm != null and rm.?.bitSize() == .Bit64) { w = 1; } } const r: u8 = if (reg_num < 8) 0 else 1; const x: u8 = 0; const b: u8 = if (rm_num < 8) 0 else 1; const rex_byte: u8 = ((0x40) | (@as(u8, w) << 3) | (r << 2) | (x << 1) | (b << 0)); if (rex_byte != 0x40 or needs_rex) { if (mode != .x64) { return AsmError.InvalidMode; } if (needs_no_rex) { return AsmError.InvalidRegisterCombination; } self.view.ext = self.makeViewPart(1); self.addByte(rex_byte); } } pub fn addAvx(self: *@This(), mode: Mode86, info: AvxResult) AsmError!void { switch (info.encoding) { .Vex2 => { self.view.ext = self.makeViewPart(2); self.addBytes(&info.makeVex2()); }, .Vex3 => { self.view.ext = self.makeViewPart(3); self.addBytes(&info.makeVex3()); }, .Evex => { self.view.ext = self.makeViewPart(4); self.addBytes(&info.makeEvex()); }, .Xop => { self.view.ext = self.makeViewPart(3); self.addBytes(&info.makeXop()); }, } } pub fn rexRaw(self: *@This(), mode: Mode86, rex_byte: u8) AsmError!void { if (rex_byte != 0x40) { if (mode != .x64) { return AsmError.InvalidMode; } self.view.ext = self.makeViewPart(1); self.addByte(rex_byte); } } pub fn addRexRm(self: *@This(), mode: Mode86, w: u1, rm: ModRmResult) AsmError!void { const rex_byte = rm.rex(w); if (rm.needs_rex and rm.needs_no_rex) { return AsmError.InvalidRegisterCombination; } if (rex_byte != 0x40 or rm.needs_rex) { if (mode != .x64) { return AsmError.InvalidMode; } if (rm.needs_no_rex) { return AsmError.InvalidRegisterCombination; } self.view.ext = self.makeViewPart(1); self.addByte(rex_byte); } } pub fn modrm(self: *@This(), rm: ModRmResult) void { self.view.modrm = self.makeViewPart(1); self.addByte(rm.modrm()); if (rm.sib) |sib| { self.view.sib = self.makeViewPart(1); self.addByte(sib); } switch (rm.disp_bit_size) { .None => {}, .Bit8 => self.addDisp8(@intCast(i8, rm.disp)), .Bit16 => self.addDisp16(@intCast(i16, rm.disp)), .Bit32 => self.addDisp32(rm.disp), else => unreachable, } } /// Add the opcode to instruction. pub fn addCompoundOpcode(self: *@This(), op: Opcode) void { if (op.compound_op != .None) { self.addByte(@enumToInt(op.compound_op)); } } /// Add the opcode to instruction. pub fn addOpcode(self: *@This(), op: Opcode) void { self.view.opcode = self.makeViewPart(op.len); self.addBytes(op.asSlice()); } /// Add the opcode to instruction. pub fn addOpcodeByte(self: *@This(), op: u8) void { self.view.opcode = self.makeViewPart(1); self.addByte(op); } /// Add the opcode to instruction incrementing the last byte by register number. pub fn addOpcodeRegNum(self: *@This(), op: Opcode, reg: Register) void { var modified_op = op; modified_op.opcode[modified_op.len - 1] += reg.number() & 0x07; self.view.opcode = self.makeViewPart(modified_op.len); self.addBytes(modified_op.asSlice()); } /// Add the immediate to the instruction pub fn addImm(self: *@This(), imm: Immediate) void { switch (imm.size) { .Imm8, .Imm8_any => self.addImm8(imm.as8()), .Imm16, .Imm16_any => self.addImm16(imm.as16()), .Imm32, .Imm32_any => self.addImm32(imm.as32()), .Imm64, .Imm64_any => self.addImm64(imm.as64()), } } fn makeViewImmediate(self: *@This(), size: u8) void { if (self.view.immediate.size != 0) { self.view.immediate.size += size; } else { self.view.immediate = self.makeViewPart(size); } assert(self.view.immediate.size <= 8); } pub fn addImm8(self: *@This(), imm8: u8) void { self.makeViewImmediate(1); self.add8(imm8); } pub fn addImm16(self: *@This(), imm16: u16) void { self.makeViewImmediate(2); self.add16(imm16); } pub fn addImm32(self: *@This(), imm32: u32) void { self.makeViewImmediate(4); self.add32(imm32); } pub fn addImm64(self: *@This(), imm64: u64) void { self.makeViewImmediate(8); self.add64(imm64); } pub fn addDisp8(self: *@This(), disp8: i8) void { self.view.displacement = self.makeViewPart(1); self.add8(@bitCast(u8, disp8)); } pub fn addDisp16(self: *@This(), disp16: i16) void { self.view.displacement = self.makeViewPart(2); self.add16(@bitCast(u16, disp16)); } pub fn addDisp32(self: *@This(), disp32: i32) void { self.view.displacement = self.makeViewPart(4); self.add32(@bitCast(u32, disp32)); } pub fn addDisp64(self: *@This(), disp64: i64) void { self.view.displacement = self.makeViewPart(8); self.add64(@bitCast(u64, disp64)); } pub fn add8(self: *@This(), imm8: u8) void { self.addByte(imm8); } pub fn add16(self: *@This(), imm16: u16) void { self.addByte(@intCast(u8, (imm16 >> 0) & 0xFF)); self.addByte(@intCast(u8, (imm16 >> 8) & 0xFF)); } pub fn add32(self: *@This(), imm32: u32) void { self.addByte(@intCast(u8, (imm32 >> 0) & 0xFF)); self.addByte(@intCast(u8, (imm32 >> 8) & 0xFF)); self.addByte(@intCast(u8, (imm32 >> 16) & 0xFF)); self.addByte(@intCast(u8, (imm32 >> 24) & 0xFF)); } pub fn add64(self: *@This(), imm64: u64) void { self.addByte(@intCast(u8, (imm64 >> 0) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 8) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 16) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 24) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 32) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 40) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 48) & 0xFF)); self.addByte(@intCast(u8, (imm64 >> 56) & 0xFF)); } pub fn addMOffsetDisp(self: *@This(), disp: MOffsetDisp) void { switch (disp) { .Disp16 => self.add16(disp.Disp16), .Disp32 => self.add32(disp.Disp32), .Disp64 => self.add64(disp.Disp64), } } pub fn addAddress(self: *@This(), addr: Address) void { const disp = addr.getDisp(); switch (addr) { .FarJmp => |far| { const disp_size = disp.bitSize(); assert(disp_size != .Bit64); self.view.immediate = self.makeViewPart(@intCast(u8, disp_size.valueBytes()) + 2); self.addMOffsetDisp(disp); self.add16(far.segment); }, .MOffset => |moff| { const disp_size = disp.bitSize(); self.view.immediate = self.makeViewPart(@intCast(u8, disp_size.valueBytes())); self.addMOffsetDisp(disp); }, } } };
src/x86/instruction.zig
const std = @import("std"); const readIntLittle = std.mem.readIntLittle; const writeIntLittle = std.mem.writeIntLittle; const Error = std.crypto.Error; pub const Fe = struct { limbs: [5]u64, const MASK51: u64 = 0x7ffffffffffff; /// 0 pub const zero = Fe{ .limbs = .{ 0, 0, 0, 0, 0 } }; /// 1 pub const one = Fe{ .limbs = .{ 1, 0, 0, 0, 0 } }; /// sqrt(-1) pub const sqrtm1 = Fe{ .limbs = .{ 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133 } }; /// The Curve25519 base point pub const curve25519BasePoint = Fe{ .limbs = .{ 9, 0, 0, 0, 0 } }; /// Edwards25519 d = 37095705934669439343138083508754565189542113879843219016388785533085940283555 pub const edwards25519d = Fe{ .limbs = .{ 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575 } }; /// Edwards25519 2d pub const edwards25519d2 = Fe{ .limbs = .{ 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903 } }; /// Edwards25519 1/sqrt(a-d) pub const edwards25519sqrtamd = Fe{ .limbs = .{ 278908739862762, 821645201101625, 8113234426968, 1777959178193151, 2118520810568447 } }; /// Edwards25519 1-d^2 pub const edwards25519eonemsqd = Fe{ .limbs = .{ 1136626929484150, 1998550399581263, 496427632559748, 118527312129759, 45110755273534 } }; /// Edwards25519 (d-1)^2 pub const edwards25519sqdmone = Fe{ .limbs = .{ 1507062230895904, 1572317787530805, 683053064812840, 317374165784489, 1572899562415810 } }; /// Edwards25519 sqrt(ad-1) with a = -1 (mod p) pub const edwards25519sqrtadm1 = Fe{ .limbs = .{ 2241493124984347, 425987919032274, 2207028919301688, 1220490630685848, 974799131293748 } }; /// Edwards25519 A, as a single limb pub const edwards25519a_32: u32 = 486662; /// Edwards25519 A pub const edwards25519a = Fe{ .limbs = .{ @as(u64, edwards25519a_32), 0, 0, 0, 0 } }; /// Edwards25519 sqrt(A-2) pub const edwards25519sqrtam2 = Fe{ .limbs = .{ 1693982333959686, 608509411481997, 2235573344831311, 947681270984193, 266558006233600 } }; /// Return true if the field element is zero pub fn isZero(fe: Fe) callconv(.Inline) bool { var reduced = fe; reduced.reduce(); const limbs = reduced.limbs; return (limbs[0] | limbs[1] | limbs[2] | limbs[3] | limbs[4]) == 0; } /// Return true if both field elements are equivalent pub fn equivalent(a: Fe, b: Fe) callconv(.Inline) bool { return a.sub(b).isZero(); } /// Unpack a field element pub fn fromBytes(s: [32]u8) Fe { var fe: Fe = undefined; fe.limbs[0] = readIntLittle(u64, s[0..8]) & MASK51; fe.limbs[1] = (readIntLittle(u64, s[6..14]) >> 3) & MASK51; fe.limbs[2] = (readIntLittle(u64, s[12..20]) >> 6) & MASK51; fe.limbs[3] = (readIntLittle(u64, s[19..27]) >> 1) & MASK51; fe.limbs[4] = (readIntLittle(u64, s[24..32]) >> 12) & MASK51; return fe; } /// Pack a field element pub fn toBytes(fe: Fe) [32]u8 { var reduced = fe; reduced.reduce(); var s: [32]u8 = undefined; writeIntLittle(u64, s[0..8], reduced.limbs[0] | (reduced.limbs[1] << 51)); writeIntLittle(u64, s[8..16], (reduced.limbs[1] >> 13) | (reduced.limbs[2] << 38)); writeIntLittle(u64, s[16..24], (reduced.limbs[2] >> 26) | (reduced.limbs[3] << 25)); writeIntLittle(u64, s[24..32], (reduced.limbs[3] >> 39) | (reduced.limbs[4] << 12)); return s; } /// Map a 64-bit big endian string into a field element pub fn fromBytes64(s: [64]u8) Fe { var fl: [32]u8 = undefined; var gl: [32]u8 = undefined; var i: usize = 0; while (i < 32) : (i += 1) { fl[i] = s[63 - i]; gl[i] = s[31 - i]; } fl[31] &= 0x7f; gl[31] &= 0x7f; var fe_f = fromBytes(fl); const fe_g = fromBytes(gl); fe_f.limbs[0] += (s[32] >> 7) * 19; i = 0; while (i < 5) : (i += 1) { fe_f.limbs[i] += 38 * fe_g.limbs[i]; } fe_f.reduce(); return fe_f; } /// Reject non-canonical encodings of an element, possibly ignoring the top bit pub fn rejectNonCanonical(s: [32]u8, comptime ignore_extra_bit: bool) Error!void { var c: u16 = (s[31] & 0x7f) ^ 0x7f; comptime var i = 30; inline while (i > 0) : (i -= 1) { c |= s[i] ^ 0xff; } c = (c -% 1) >> 8; const d = (@as(u16, 0xed - 1) -% @as(u16, s[0])) >> 8; const x = if (ignore_extra_bit) 0 else s[31] >> 7; if ((((c & d) | x) & 1) != 0) { return error.NonCanonical; } } /// Reduce a field element mod 2^255-19 fn reduce(fe: *Fe) void { comptime var i = 0; comptime var j = 0; const limbs = &fe.limbs; inline while (j < 2) : (j += 1) { i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; } limbs[0] += 19; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; limbs[0] += 0x8000000000000 - 19; limbs[1] += 0x8000000000000 - 1; limbs[2] += 0x8000000000000 - 1; limbs[3] += 0x8000000000000 - 1; limbs[4] += 0x8000000000000 - 1; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[4] &= MASK51; } /// Add a field element pub fn add(a: Fe, b: Fe) callconv(.Inline) Fe { var fe: Fe = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] = a.limbs[i] + b.limbs[i]; } return fe; } /// Substract a field elememnt pub fn sub(a: Fe, b: Fe) callconv(.Inline) Fe { var fe = b; comptime var i = 0; inline while (i < 4) : (i += 1) { fe.limbs[i + 1] += fe.limbs[i] >> 51; fe.limbs[i] &= MASK51; } fe.limbs[0] += 19 * (fe.limbs[4] >> 51); fe.limbs[4] &= MASK51; fe.limbs[0] = (a.limbs[0] + 0xfffffffffffda) - fe.limbs[0]; fe.limbs[1] = (a.limbs[1] + 0xffffffffffffe) - fe.limbs[1]; fe.limbs[2] = (a.limbs[2] + 0xffffffffffffe) - fe.limbs[2]; fe.limbs[3] = (a.limbs[3] + 0xffffffffffffe) - fe.limbs[3]; fe.limbs[4] = (a.limbs[4] + 0xffffffffffffe) - fe.limbs[4]; return fe; } /// Negate a field element pub fn neg(a: Fe) callconv(.Inline) Fe { return zero.sub(a); } /// Return true if a field element is negative pub fn isNegative(a: Fe) callconv(.Inline) bool { return (a.toBytes()[0] & 1) != 0; } /// Conditonally replace a field element with `a` if `c` is positive pub fn cMov(fe: *Fe, a: Fe, c: u64) callconv(.Inline) void { const mask: u64 = 0 -% c; var x = fe.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] ^= a.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] ^= x.limbs[i]; } } /// Conditionally swap two pairs of field elements if `c` is positive pub fn cSwap2(a0: *Fe, b0: *Fe, a1: *Fe, b1: *Fe, c: u64) void { const mask: u64 = 0 -% c; var x0 = a0.*; var x1 = a1.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] ^= b0.limbs[i]; x1.limbs[i] ^= b1.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] &= mask; x1.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { a0.limbs[i] ^= x0.limbs[i]; b0.limbs[i] ^= x0.limbs[i]; a1.limbs[i] ^= x1.limbs[i]; b1.limbs[i] ^= x1.limbs[i]; } } fn _carry128(r: *[5]u128) callconv(.Inline) Fe { var rs: [5]u64 = undefined; comptime var i = 0; inline while (i < 4) : (i += 1) { rs[i] = @truncate(u64, r[i]) & MASK51; r[i + 1] += @intCast(u64, r[i] >> 51); } rs[4] = @truncate(u64, r[4]) & MASK51; var carry = @intCast(u64, r[4] >> 51); rs[0] += 19 * carry; carry = rs[0] >> 51; rs[0] &= MASK51; rs[1] += carry; carry = rs[1] >> 51; rs[1] &= MASK51; rs[2] += carry; return .{ .limbs = rs }; } /// Multiply two field elements pub fn mul(a: Fe, b: Fe) callconv(.Inline) Fe { var ax: [5]u128 = undefined; var bx: [5]u128 = undefined; var a19: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @intCast(u128, a.limbs[i]); bx[i] = @intCast(u128, b.limbs[i]); } i = 1; inline while (i < 5) : (i += 1) { a19[i] = 19 * ax[i]; } r[0] = ax[0] * bx[0] + a19[1] * bx[4] + a19[2] * bx[3] + a19[3] * bx[2] + a19[4] * bx[1]; r[1] = ax[0] * bx[1] + ax[1] * bx[0] + a19[2] * bx[4] + a19[3] * bx[3] + a19[4] * bx[2]; r[2] = ax[0] * bx[2] + ax[1] * bx[1] + ax[2] * bx[0] + a19[3] * bx[4] + a19[4] * bx[3]; r[3] = ax[0] * bx[3] + ax[1] * bx[2] + ax[2] * bx[1] + ax[3] * bx[0] + a19[4] * bx[4]; r[4] = ax[0] * bx[4] + ax[1] * bx[3] + ax[2] * bx[2] + ax[3] * bx[1] + ax[4] * bx[0]; return _carry128(&r); } fn _sq(a: Fe, double: comptime bool) callconv(.Inline) Fe { var ax: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @intCast(u128, a.limbs[i]); } const a0_2 = 2 * ax[0]; const a1_2 = 2 * ax[1]; const a1_38 = 38 * ax[1]; const a2_38 = 38 * ax[2]; const a3_38 = 38 * ax[3]; const a3_19 = 19 * ax[3]; const a4_19 = 19 * ax[4]; r[0] = ax[0] * ax[0] + a1_38 * ax[4] + a2_38 * ax[3]; r[1] = a0_2 * ax[1] + a2_38 * ax[4] + a3_19 * ax[3]; r[2] = a0_2 * ax[2] + ax[1] * ax[1] + a3_38 * ax[4]; r[3] = a0_2 * ax[3] + a1_2 * ax[2] + a4_19 * ax[4]; r[4] = a0_2 * ax[4] + a1_2 * ax[3] + ax[2] * ax[2]; if (double) { i = 0; inline while (i < 5) : (i += 1) { r[i] *= 2; } } return _carry128(&r); } /// Square a field element pub fn sq(a: Fe) callconv(.Inline) Fe { return _sq(a, false); } /// Square and double a field element pub fn sq2(a: Fe) callconv(.Inline) Fe { return _sq(a, true); } /// Multiply a field element with a small (32-bit) integer pub fn mul32(a: Fe, comptime n: u32) callconv(.Inline) Fe { const sn = @intCast(u128, n); var fe: Fe = undefined; var x: u128 = 0; comptime var i = 0; inline while (i < 5) : (i += 1) { x = a.limbs[i] * sn + (x >> 51); fe.limbs[i] = @truncate(u64, x) & MASK51; } fe.limbs[0] += @intCast(u64, x >> 51) * 19; return fe; } /// Square a field element `n` times fn sqn(a: Fe, comptime n: comptime_int) callconv(.Inline) Fe { var i: usize = 0; var fe = a; while (i < n) : (i += 1) { fe = fe.sq(); } return fe; } /// Compute the inverse of a field element pub fn invert(a: Fe) Fe { var t0 = a.sq(); var t1 = t0.sqn(2).mul(a); t0 = t0.mul(t1); t1 = t1.mul(t0.sq()); t1 = t1.mul(t1.sqn(5)); var t2 = t1.sqn(10).mul(t1); t2 = t2.mul(t2.sqn(20)).sqn(10); t1 = t1.mul(t2); t2 = t1.sqn(50).mul(t1); return t1.mul(t2.mul(t2.sqn(100)).sqn(50)).sqn(5).mul(t0); } /// Return a^((p-5)/8) = a^(2^252-3) /// Used to compute square roots since we have p=5 (mod 8); see Cohen and Frey. pub fn pow2523(a: Fe) Fe { var t0 = a.mul(a.sq()); var t1 = t0.mul(t0.sqn(2)).sq().mul(a); t0 = t1.sqn(5).mul(t1); var t2 = t0.sqn(5).mul(t1); t1 = t2.sqn(15).mul(t2); t2 = t1.sqn(30).mul(t1); t1 = t2.sqn(60).mul(t2); return t1.sqn(120).mul(t1).sqn(10).mul(t0).sqn(2).mul(a); } /// Return the absolute value of a field element pub fn abs(a: Fe) Fe { var r = a; r.cMov(a.neg(), @boolToInt(a.isNegative())); return r; } /// Return true if the field element is a square pub fn isSquare(a: Fe) bool { // Compute the Jacobi symbol x^((p-1)/2) const _11 = a.mul(a.sq()); const _1111 = _11.mul(_11.sq().sq()); const _11111111 = _1111.mul(_1111.sq().sq().sq().sq()); var t = _11111111.sqn(2).mul(_11); const u = t; t = t.sqn(10).mul(u).sqn(10).mul(u); t = t.sqn(30).mul(t); t = t.sqn(60).mul(t); t = t.sqn(120).mul(t).sqn(10).mul(u).sqn(3).mul(_11).sq(); return @bitCast(bool, @truncate(u1, ~(t.toBytes()[1] & 1))); } fn uncheckedSqrt(x2: Fe) Fe { var e = x2.pow2523(); const p_root = e.mul(x2); // positive root const m_root = p_root.mul(Fe.sqrtm1); // negative root const m_root2 = m_root.sq(); e = x2.sub(m_root2); var x = p_root; x.cMov(m_root, @boolToInt(e.isZero())); return x; } /// Compute the square root of `x2`, returning `error.NotSquare` if `x2` was not a square pub fn sqrt(x2: Fe) Error!Fe { var x2_copy = x2; const x = x2.uncheckedSqrt(); const check = x.sq().sub(x2_copy); if (check.isZero()) { return x; } return error.NotSquare; } };
lib/std/crypto/25519/field.zig
const std = @import("std"); const ast = std.zig.ast; const util = @import("utils.zig"); const source_url = "https://github.com/ziglang/zig/blob/master/lib/std/"; const out_fname_html = "index.html"; const in_fname_head = "html_head.html"; const in_fname_entries = "entries.json"; const max_read_filesize = 20 * 1024 * 1024; // 20Mb I mean, really. const JsonEntry = struct { name: []const u8 = undefined, description: ?[]const u8 = null, hide: bool = false, compact: bool = false, }; var tree: ast.Tree = undefined; const DeclInfoLists = struct { name: []const u8 = undefined, fields: std.ArrayList(DeclInfo), types: std.ArrayList(DeclInfo), funcs: std.ArrayList(DeclInfo), values: std.ArrayList(DeclInfo), json_entry: JsonEntry = undefined, pub fn init(alloc: *std.mem.Allocator) !@This() { return @This(){ .fields = std.ArrayList(DeclInfo).init(alloc), .types = std.ArrayList(DeclInfo).init(alloc), .funcs = std.ArrayList(DeclInfo).init(alloc), .values = std.ArrayList(DeclInfo).init(alloc), }; } pub fn htmlStringify(self: DeclInfoLists, writer: anytype) std.fs.File.WriteError!void { if (self.json_entry.hide) { // Ignore hidden items. I tried minimizing or explaining hidden items, but there // is already so much stuff, they were just adding to the clutter. return; } // On one hand, this won't work for Windows paths. On the other // hand, the '/' slash works for the source URLs as-is, so... const in_subdir = std.mem.containsAtLeast(u8, self.name, 1, "/"); const subdir_class = if (in_subdir) "subdir" else ""; const hidden_class = if (self.json_entry.hide) "hidden" else ""; try writer.print( \\ <div class="module {s} {s}"> \\ <h2><a class="decl" target="_blank" href="{s}{s}">{s}</a></h2> \\ <div class="module-inner"> , .{ subdir_class, hidden_class, source_url, self.name, self.name }); if (self.json_entry.description) |desc| { try writer.print("<p>{s}</p>", .{self.json_entry.description}); } inline for (.{"fields", "funcs", "types", "values"}) |n| { try writer.print("<span class=\"kind-{s}\">", .{n}); const this_list = @field(self, n).items; for (this_list) |decl, count| { try decl.htmlStringify(writer, self.json_entry.compact); if (self.json_entry.compact and count > 5) { try writer.print(" {} more...", .{this_list.len-5}); break; } } try writer.writeAll("</span>"); } try writer.writeAll("</div></div>"); // end of module } }; const DeclKind = enum { field, func, type, value }; const DeclInfo = struct { kind: DeclKind, name: []const u8, tag: std.zig.ast.Node.Tag, sub_cont_ty: ?[]const u8 = null, decl_info_lists: ?DeclInfoLists, src_line: usize, pub fn htmlStringify(self: DeclInfo, writer: anytype, compact: bool) std.fs.File.WriteError!void { // If this decl contains inner decls, enclose the lot in a container if (self.decl_info_lists != null) try writer.writeAll("<div class=\"inner-container\">"); var fn_parens = if (self.kind == .func) "()" else ""; var kind_str = switch (self.kind) { .field => "field", .func => "func", .type => "type", .value => "value", }; try writer.print("<a class=\"decl kind-{s}\" target=\"_blank\" href=\"{s}{s}#L{}\">{s}{s}</a> ", .{ kind_str, source_url, cur_file, self.src_line+1, // always one off - is it 0 indexed? self.name, fn_parens, }); if (self.decl_info_lists != null) { inline for (.{"fields", "funcs", "types", "values"}) |n| { const this_list = @field(self.decl_info_lists.?, n).items; for (this_list) |decl, count| { try decl.htmlStringify(writer, compact); if (compact and count > 5) { try writer.print(" {} more...", .{this_list.len}); break; } } } try writer.writeAll("</div>"); // End container started way up at the top of fn } } }; var cur_file: []const u8 = undefined; fn removeTrailingSlash(n: [:0]u8) []u8 { if (std.mem.endsWith(u8, n, "/")) return n[0 .. n.len - 1]; return n; } pub fn main() !void { // var general_pa = std.heap.GeneralPurposeAllocator(.{ .stack_trace_frames = 8 }){}; // const alloc = &general_pa.allocator; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; const args = try std.process.argsAlloc(alloc); if (args.len < 2) fatal("The first argument must be a directory path."); const dirname = removeTrailingSlash(args[1]); var walker = std.fs.walkPath(alloc, dirname) catch |e| fatalArgs("Could not read directory: {s}: {}", .{ dirname, e }); // defer walker.deinit(); // Store the decl lists for each file mapped by filename var decls_by_filename = std.StringHashMap(DeclInfoLists).init(alloc); // Read json data const info_json = std.fs.cwd().readFileAlloc(alloc, in_fname_entries, max_read_filesize) catch |e| { fatalArgs("Could not read file {s}: {}", .{in_fname_entries, e}); }; // Now parse those tasty JSON potatoes. // Used ziglearn to understand how to parse into a data type: // https://ziglearn.org/chapter-2/#json // Used laddercraft to understand how to loop over the token stream: // https://github.com/wozeparrot/laddercraft/blob/master/utils/item_registry_generator.zig // Store the entries hashed by filename (corresponds with library file names) var json_entries = std.StringHashMap(JsonEntry).init(alloc); var json_stream = std.json.TokenStream.init(info_json); const context = .{.allocator = alloc}; std.debug.assert((try json_stream.next()).? == .ObjectBegin); // '{' <--- at the very beginning while (true) { // So, ideally we could peek at the next token to see if it's a string // or an ObjectEnd '}' (expected when we're out of entries). But for // this kind of one-off utility, let's just assume the inability to // parse another entry means we've come to the end. const my_name = std.json.parse([]const u8, &json_stream, context) catch break; var my_value = try std.json.parse(JsonEntry, &json_stream, context); my_value.name = my_name; try json_entries.put(my_name, my_value); // my_value.print(); } // std.debug.print("Read {} entries from {s}\n", .{json_entries.count(), in_fname_entries}); // Terminal progress indicator var progress: std.Progress = .{}; var progress_main = try progress.start("", 0); progress_main.activate(); defer progress_main.end(); var progress_analysis = progress_main.start("Reading library...", 0); progress_analysis.activate(); // So we can sort em var filenames = std.ArrayList([]const u8,).init(alloc); // defer filenames.deinit(); // Loop through files in input directory while (walker.next() catch |e| fatalArgs("Could not read next file: {}", .{e})) |entry| { if (!std.mem.endsWith(u8, entry.path, ".zig")) continue; // Chop the dirname + "/" from the front of the path const filename = entry.path[dirname.len+1..]; // Do we already have this one? if (decls_by_filename.contains(filename)) continue; const my_filename = try alloc.dupe(u8, filename); // Show current file as progress var progress_file = progress_analysis.start(filename, 1); progress_file.activate(); defer progress_file.end(); // Store decl lists in hashmap by filename and store filename itself var list = try getDeclsFromFile(alloc, entry.path); list.name = my_filename; if (json_entries.contains(my_filename) ) { list.json_entry = json_entries.get(my_filename).?; } try decls_by_filename.put(my_filename, list); try filenames.append(my_filename); } progress_analysis.end(); // Sort the filenames std.sort.sort( []const u8, filenames.items, {}, stringAsc); var progress_writing = progress_main.start("Writing HTML...", 0); progress_writing.activate(); defer progress_writing.end(); const output_file = std.fs.cwd().createFile(out_fname_html, .{ .read = true }) catch |e| fatalArgs("Could not open {s} for writing: {}", .{out_fname_html, e}); defer output_file.close(); const w = output_file.writer(); const html_head = std.fs.cwd().readFileAlloc(alloc, in_fname_head, max_read_filesize) catch |e| { fatalArgs("Could not read file {s}: {}", .{in_fname_head, e}); }; try w.writeAll(html_head); // std.debug.print("{s}\n", .{filenames.items}); for (filenames.items) |fname| { cur_file = fname; try decls_by_filename.get(fname).?.htmlStringify(w); } try w.writeAll("</div></body></html>"); } // Comparison function for filename string sorting pub fn stringAsc(context: void, lhs: []const u8, rhs: []const u8) bool { return std.mem.lessThan(u8, lhs, rhs); } fn getDeclsFromFile( alloc: *std.mem.Allocator, fname: []const u8, ) error{OutOfMemory}!DeclInfoLists { const zig_code = std.fs.cwd().readFileAlloc(alloc, fname, max_read_filesize) catch |e| { fatalArgs("Could not read lib source file {s}: {}", .{fname, e}); }; tree = std.zig.parse(alloc, zig_code) catch |e| { fatalArgs("Could not parse lib source file {s}: {}", .{ fname, e }); }; // defer tree.deinit(alloc); const decls = tree.rootDecls(); const decl_list = try getDeclInfoList(alloc, decls); return decl_list; } fn getDeclInfoList( alloc: *std.mem.Allocator, list_d: []const ast.Node.Index, ) error{OutOfMemory}!DeclInfoLists { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); var list = try DeclInfoLists.init(alloc); for (list_d) |member| { if (!util.isNodePublic(tree, member)) continue; const tag = node_tags[member]; // Tag // We're only concerned about these types. Looks like just // test and comptime being skipped currently, but an inclusion // list will be easier to keep current, maybe? if (tag != .local_var_decl and tag != .global_var_decl and tag != .simple_var_decl and tag != .aligned_var_decl and tag != .fn_proto and tag != .fn_proto_multi and tag != .fn_proto_one and tag != .fn_proto_simple and tag != .fn_decl and tag != .container_field and tag != .container_field_init and tag != .container_field_align and tag != .identifier and tag != .error_value) { continue; } const decl_addr = member; const q_ftoken = tree.firstToken(member); const q_ltoken = tree.lastToken(member); const q_start = token_starts[q_ftoken]; const q_end = token_starts[q_ltoken + 1]; var decl_info_lists: ?DeclInfoLists = null; var destination_list = &list.fields; var kind = DeclKind.field; if (tag == .fn_decl) { // We are only interested in "type functions" which // create and return a type. destination_list = &list.funcs; decl_info_lists = getFunctionDecls(alloc, decl_addr); kind = DeclKind.func; } if (tag == .global_var_decl or tag == .local_var_decl or tag == .simple_var_decl or tag == .aligned_var_decl) { destination_list = &list.values; kind = DeclKind.value; decl_info_lists = getVarDecls(alloc, decl_addr); if (decl_info_lists) |_| { destination_list = &list.types; kind = DeclKind.type; } } try destination_list.append(.{ .kind = kind, .decl_info_lists = decl_info_lists, .src_line = std.zig.findLineColumn(tree.source, q_start).line, .name = try alloc.dupe(u8, util.getDeclName(tree, member).?), .tag = tag, }); } return list; } fn getVarDecls(alloc: *std.mem.Allocator, decl_addr: ast.Node.Index) ?DeclInfoLists { const vardecl = util.varDecl(tree, decl_addr).?; const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const name_loc = vardecl.ast.mut_token + 1; const name = tree.tokenSlice(name_loc); const init = node_datas[decl_addr].rhs; const rhst = node_tags[init]; // we find if the var is a container, we dont wanna display the full thing if it is // then we recurse over it var buf: [2]ast.Node.Index = undefined; var cd = getContainer(node_datas[decl_addr].rhs, &buf); if (cd) |container_decl| { const offset = if (container_decl.ast.enum_token != null) if (rhst == .tagged_union_enum_tag or rhst == .tagged_union_enum_tag_trailing) @as(u32, 7) else @as(u32, 4) else @as(u32, 1); return getDeclInfoList(alloc, container_decl.ast.members) catch null; } return null; } fn getFunctionDecls(alloc: *std.mem.Allocator, decl_addr: ast.Node.Index) ?DeclInfoLists { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const proto = node_datas[decl_addr].lhs; const block = node_datas[decl_addr].rhs; var params: [1]ast.Node.Index = undefined; const fn_proto = util.fnProto( tree, proto, &params, ).?; const sig = util.getFunctionSignature(tree, fn_proto); var sub_cont_ty: ?[]const u8 = null; return if (util.isTypeFunction(tree, fn_proto)) blk: { const ret = util.findReturnStatement(tree, fn_proto, block) orelse break :blk null; if (node_datas[ret].lhs == 0) break :blk null; var buf: [2]ast.Node.Index = undefined; const container = getContainer(node_datas[ret].lhs, &buf) orelse break :blk null; const offset = if (container.ast.enum_token != null) if (node_tags[node_datas[ret].lhs] == .tagged_union_enum_tag or node_tags[node_datas[ret].lhs] == .tagged_union_enum_tag_trailing) @as(u32, 7) else @as(u32, 4) else @as(u32, 1); sub_cont_ty = tree.source[token_starts[tree.firstToken(node_datas[ret].lhs)]..token_starts[ main_tokens[node_datas[ret].lhs] + offset ]]; break :blk getDeclInfoList(alloc, container.ast.members) catch |e| { return null; }; } else null; } fn getContainer(decl_addr: ast.Node.Index, buf: *[2]ast.Node.Index) ?ast.full.ContainerDecl { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const rhst = node_tags[decl_addr]; // Recurse over it return if (rhst == .container_decl or rhst == .container_decl_trailing) tree.containerDecl(decl_addr) else if (rhst == .container_decl_arg or rhst == .container_decl_arg_trailing) tree.containerDeclArg(decl_addr) else if (rhst == .container_decl_two or rhst == .container_decl_two_trailing) blk: { break :blk tree.containerDeclTwo(buf, decl_addr); } else if (rhst == .tagged_union or rhst == .tagged_union_trailing) tree.taggedUnion(decl_addr) else if (rhst == .tagged_union_two or rhst == .tagged_union_two_trailing) blk: { break :blk tree.taggedUnionTwo(buf, decl_addr); } else if (rhst == .tagged_union_enum_tag or rhst == .tagged_union_enum_tag_trailing) tree.taggedUnionEnumTag(decl_addr) else null; } fn fatal(s: []const u8) noreturn { std.log.emerg("{s}\n", .{s}); std.process.exit(1); } fn fatalArgs(comptime s: []const u8, args: anytype) noreturn { std.log.emerg(s, args); std.process.exit(1); }
gen.zig
const std = @import("std"); const print = std.debug.print; const eql = std.mem.eql; const expect = std.testing.expect; fn print_array(prefix: []const u8, array: []const u8) void { print("{}{}{}", .{ prefix, @typeName(@TypeOf(array)), "{" }); for (array) |n, i| { if (i < array.len - 1) { print(" {},", .{n}); } else { print(" {} {}", .{ n, "}" }); } } } test "array initialized to zero" { const five_zeros = [_]u16{0} ** 5; print("\n five_zeros.len={}", .{five_zeros.len}); print("\n five_zeros[4]=={}", .{five_zeros[4]}); print("\n", .{}); expect(five_zeros.len == 5); for (five_zeros) |n, i| { // print("ten_zeros[{}]={}\n", .{i, n}); expect(n == 0); } } // anonymous list literals are passed as arguments for `print` which // accepts an `anytype` and performs comptime/runtime logic. test "anonymous list literal" { const list = .{ 1, 2, 3 }; print("\n @TypeOf(list) is {}", .{@typeName(@TypeOf(list))}); print("\n", .{}); expect(list[2] == 3); } test "a string literal is a pointer to an array literal" { const a1 = "hello"; const a2 = [_]u8{ 'h', 'e', 'l', 'l', 'o' }; print("\n @TypeOf(a1) is {}", .{@typeName(@TypeOf(a1))}); print("\n @TypeOf(a2) is {}", .{@typeName(@TypeOf(a2))}); print("\n @TypeOf(&a2) is {}", .{@typeName(@TypeOf(&a2))}); print("\n", .{}); expect(eql(u8, a1, &a2)); } test "null terminated array" { const a3 = [_:0]u8{ 1, 2, 3, 4, 5 }; print("\n @TypeOf(a3) is {}", .{@typeName(@TypeOf(a3))}); print_array("\n a=", &a3); print("\n", .{}); expect(@TypeOf(a3) == [5:0]u8); expect(a3.len == 5); expect(a3[5] == 0); // the null } test "a string is a null terminated array" { const a4 = [_:0]u8{ 104, 101, 108, 108, 111 }; print("\n @TypeOf(a4) is {}", .{@typeName(@TypeOf(a4))}); print_array("\n a4=", &a4); print("\n a4={}", .{a4}); print("\n", .{}); expect(@TypeOf(a4) == [5:0]u8); expect(a4.len == 5); expect(a4[5] == 0); // the null } test "multidimentional array" { // legend... // # == wall // . == floor // @ == player const room = [5][5]u8{ [_]u8{ '#', '#', '#', '#', '#' }, [_]u8{ '#', '.', '.', '.', '#' }, [_]u8{ '#', '.', '.', '.', '#' }, [_]u8{ '#', '.', '@', '.', '#' }, [_]u8{ '#', '#', '#', '#', '#' }, }; expect(room[3][2] == '@'); for (room) |row, row_i| { for (row) |cell, col_i| { if (row_i == 0 or row_i == 4) { expect(cell == '#'); } else if (col_i == 0 or col_i == 4) { expect(cell == '#'); } else if (row_i == 3 and col_i == 2) { expect(cell == '@'); } else { expect(cell == '.'); } } } }
web/src/204_array/test.zig
const uefi = @import("../uefi.zig"); const Header = @import("header.zig").Header; const NotYetImplementedFn = uefi.NotYetImplementedFn; const Guid = uefi.Guid; const Status = uefi.Status; const ucs2 = uefi.ucs2; pub const BootServices = extern struct { pub const signature = 0x56524553544f4f42; hdr: Header, raiseTpl: NotYetImplementedFn, restoreTpl: NotYetImplementedFn, allocatePages: NotYetImplementedFn, freePages: NotYetImplementedFn, getMemoryMap: extern fn (memory_map_size: *usize, memory_map: [*]uefi.MemoryDescriptor, map_key: *usize, desc_size: *usize, desc_version: *u32) Status, allocatePool: extern fn (pool_type: uefi.MemoryType, size: usize, buf: **c_void) Status, freePool: extern fn (buf: *c_void) Status, createEvent: NotYetImplementedFn, setTimer: NotYetImplementedFn, waitForEvent: NotYetImplementedFn, signalEvent: NotYetImplementedFn, closeEvent: NotYetImplementedFn, checkEvent: NotYetImplementedFn, installProtocolInterface: NotYetImplementedFn, reinstallProtocolInterface: NotYetImplementedFn, uninstallProtocolInterface: NotYetImplementedFn, handleProtocol: NotYetImplementedFn, reserved: ?*c_void, registerProtocolNotify: NotYetImplementedFn, locateHandle: NotYetImplementedFn, locateDevicePath: NotYetImplementedFn, installConfigurationTable: NotYetImplementedFn, loadImage: NotYetImplementedFn, startImage: NotYetImplementedFn, exit: NotYetImplementedFn, unloadImage: NotYetImplementedFn, exitBootServices: extern fn (image_handle: uefi.Handle, map_key: usize) Status, getNextMonotonicCount: NotYetImplementedFn, stall: extern fn (microseconds: usize) Status, setWatchdogTimer: extern fn (timeout: usize, watchdog_code: u64, data_size: usize, watchdog_data: ?[*]ucs2) Status, connectController: NotYetImplementedFn, disconnectController: NotYetImplementedFn, openProtocol: NotYetImplementedFn, closeProtocol: NotYetImplementedFn, openProtocolInformation: NotYetImplementedFn, protocolsPerHandle: NotYetImplementedFn, locateHandleBuffer: NotYetImplementedFn, locateProtocol: extern fn (protocol: *const Guid, registration: ?*c_void, interface: *?*c_void) Status, installMultipleProtocolInterfaces: NotYetImplementedFn, uninstallMultipleProtocolInterfaces: NotYetImplementedFn, calculateCrc32: NotYetImplementedFn, copyMem: NotYetImplementedFn, setMem: NotYetImplementedFn, createEventEx: NotYetImplementedFn, };
src/uefi/tables/boot_services.zig
const std = @import("std"); const warn = std.debug.warn; const ZigParser = @import("zig/zig_parser.zig").Parser; const ZigNode = @import("zig/zig_parser.zig").Node; const ZigToken = @import("zig/zig_grammar.tokens.zig").Token; const ZigIr = struct { const Instruction = struct { id: Id, pub const Id = enum { Import, Scope, Name, Assign, Jump, Branch, }; pub fn cast(base: *Node, comptime T: type) ?*T { if (base.id == comptime typeToId(T)) { return @fieldParentPtr(T, "base", base); } return null; } pub fn unsafe_cast(base: *Node, comptime T: type) *T { return @fieldParentPtr(T, "base", base); } pub fn iterate(base: *Node, index: usize) ?*Node { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).iterate(index); } } unreachable; } pub fn typeToId(comptime T: type) Id { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (T == @field(Node, @memberName(Id, i))) { return @field(Id, @memberName(Id, i)); } } unreachable; } }; const Scope = struct { allocator: *std.mem.Allocator, parent: ?*Scope = null, label: ?*ZigToken = null, entry: *Block, exit: *Block, pub fn init(allocator: *std.mem.Allocator) !Scope { const entry = try allocator.create(Block); entry.* = Block.init(allocator); return Scope{ .allocator = allocator, .entry = entry, .exit = entry }; } }; const Block = struct { instructions: std.ArrayList(*Instruction), pub fn init(allocator: *std.mem.Allocator) Block { return Block{ .instructions = std.ArrayList(*Instruction).init(allocator) }; } }; }; usingnamespace @import("errors.zig"); pub fn main() !void { var allocator = std.heap.c_allocator; var args = std.process.args(); if(!args.skip()) return; const filename = if(args.next(allocator)) |arg1| try arg1 else "simple.zig"[0..]; var file = try std.fs.File.openRead(filename); defer file.close(); const file_size = try file.getEndPos(); const buffer = std.os.mmap( null, file_size, std.os.PROT_READ, std.os.MAP_SHARED, file.handle, 0, ) catch return error.OutOfMemory; defer std.os.munmap(buffer); var parser = try ZigParser.init(std.heap.c_allocator); defer parser.deinit(); const ms_begin = std.time.milliTimestamp(); _ = try parser.run(buffer[0..file_size]); const ms_end = std.time.milliTimestamp(); var eit = parser.engine.errors.iterator(0); while(eit.next()) |err| { warn("{}:{}-{} {}\n", err.line, err.start, err.end, parseErrorToString(err.info)); } else { warn("No errors\n"); } warn("Duration: {}ms\n", ms_end-ms_begin); if(parser.root) |root| { root.base.dump(0); } }
parser.zig
const Svg = @This(); const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; pub const Element = struct { const Tag = enum { raw, group, path, line, rect, text, }; pub const Raw = struct { const base_tag: Svg.Element.Tag = .raw; base: Svg.Element, tag: []const u8, attrs: std.ArrayListUnmanaged([]const u8) = .{}, children: std.ArrayListUnmanaged(*Svg.Element) = .{}, pub fn new(allocator: Allocator, tag: []const u8) !*Raw { const self = try allocator.create(Raw); self.* = .{ .base = .{ .tag = .raw }, .tag = tag, }; return self; } pub fn deinit(self: *Raw, allocator: Allocator) void { self.attrs.deinit(allocator); for (self.children.items) |child| { child.deinit(allocator); } self.children.deinit(allocator); } pub fn render(self: Raw, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<{s} ", .{self.tag}); for (self.attrs.items) |attr| { try writer.print("{s} ", .{attr}); } try writer.writeAll(">"); for (self.children.items) |child| { try child.render(writer); } try writer.print("</{s}>", .{self.tag}); } }; pub const Group = struct { const base_tag: Svg.Element.Tag = .group; base: Svg.Element, children: std.ArrayListUnmanaged(*Svg.Element) = .{}, pub fn new(allocator: Allocator) !*Group { const self = try allocator.create(Group); self.* = .{ .base = .{ .tag = .group }, }; return self; } pub fn deinit(self: *Group, allocator: Allocator) void { for (self.children.items) |child| { child.deinit(allocator); } self.children.deinit(allocator); } pub fn render(self: Group, writer: anytype) @TypeOf(writer).Error!void { try writer.writeAll("<g "); try self.base.renderImpl(writer); try writer.writeAll(">"); for (self.children.items) |child| { try child.render(writer); } try writer.writeAll("</g>"); } }; pub const Path = struct { const base_tag: Svg.Element.Tag = .path; base: Svg.Element, x1: ?usize, y1: ?usize, x2: ?usize, y2: ?usize, d: std.ArrayListUnmanaged(u8) = .{}, pub fn new(allocator: Allocator, opts: struct { x1: ?usize = null, y1: ?usize = null, x2: ?usize = null, y2: ?usize = null, d: ?[]const u8 = null, }) !*Path { const self = try allocator.create(Path); self.* = .{ .base = .{ .tag = .path }, .x1 = opts.x1, .y1 = opts.y1, .x2 = opts.x2, .y2 = opts.y2, }; if (opts.d) |d| { try self.d.appendSlice(allocator, d); } return self; } pub fn moveTo(self: *Path, allocator: Allocator, x: usize, y: usize) !void { const d = try std.fmt.allocPrint(allocator, "M {d} {d} ", .{ x, y }); defer allocator.free(d); try self.d.appendSlice(allocator, d); } pub fn lineTo(self: *Path, allocator: Allocator, x: usize, y: usize) !void { const d = try std.fmt.allocPrint(allocator, "L {d} {d} ", .{ x, y }); defer allocator.free(d); try self.d.appendSlice(allocator, d); } pub fn deinit(self: *Path, allocator: Allocator) void { self.d.deinit(allocator); } pub fn render(self: Path, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<path d='{s}' ", .{self.d.items}); if (self.x1) |x1| { try writer.print("x1={d} ", .{x1}); } if (self.y1) |y1| { try writer.print("y1={d} ", .{y1}); } if (self.x2) |x2| { try writer.print("x2={d} ", .{x2}); } if (self.y2) |y2| { try writer.print("y2={d} ", .{y2}); } try self.base.renderImpl(writer); try writer.writeAll("/>"); } }; pub const Line = struct { const base_tag: Svg.Element.Tag = .line; base: Svg.Element, x1: usize, y1: usize, x2: usize, y2: usize, pub fn new(allocator: Allocator, opts: struct { x1: usize = 0, y1: usize = 0, x2: usize = 0, y2: usize = 0, }) !*Line { const self = try allocator.create(Line); self.* = .{ .base = .{ .tag = .line }, .x1 = opts.x1, .y1 = opts.y1, .x2 = opts.x2, .y2 = opts.y2, }; return self; } pub fn render(self: Line, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<line x1='{d}' y1='{d}' x2='{d}' y2='{d}' ", .{ self.x1, self.y1, self.x2, self.y2, }); try self.base.renderImpl(writer); try writer.writeAll("/>"); } }; pub const Rect = struct { const base_tag: Svg.Element.Tag = .rect; base: Svg.Element, x: usize, y: usize, width: usize, height: usize, pub fn new(allocator: Allocator, opts: struct { x: usize = 0, y: usize = 0, width: usize = 0, height: usize = 0, }) !*Rect { const self = try allocator.create(Rect); self.* = .{ .base = .{ .tag = .rect }, .x = opts.x, .y = opts.y, .width = opts.width, .height = opts.height, }; return self; } pub fn render(self: Rect, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<rect x='{d}' y='{d}' width='{d}' height='{d}' ", .{ self.x, self.y, self.width, self.height, }); try self.base.renderImpl(writer); try writer.writeAll("/>"); } }; pub const Text = struct { const base_tag: Svg.Element.Tag = .text; base: Svg.Element, x: usize, y: usize, contents: ?[]const u8, pub fn new(allocator: Allocator, opts: struct { x: usize = 0, y: usize = 0, contents: ?[]const u8 = null, }) !*Text { const self = try allocator.create(Text); self.* = .{ .base = .{ .tag = .text }, .x = opts.x, .y = opts.y, .contents = opts.contents, }; return self; } pub fn render(self: Text, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<text x='{d}' y='{d}' ", .{ self.x, self.y }); try self.base.renderImpl(writer); if (self.contents) |contents| { try writer.print(">{s}</text>", .{contents}); } else { try writer.writeAll("/>"); } } }; tag: Tag, id: ?[]const u8 = null, css_classes: ?[]const u8 = null, onclick: ?[]const u8 = null, pub fn deinit(base: *Element, allocator: Allocator) void { switch (base.tag) { .raw => @fieldParentPtr(Raw, "base", base).deinit(allocator), .group => @fieldParentPtr(Group, "base", base).deinit(allocator), .path => @fieldParentPtr(Path, "base", base).deinit(allocator), else => {}, } } pub fn render(base: *Element, writer: anytype) @TypeOf(writer).Error!void { return switch (base.tag) { .raw => @fieldParentPtr(Raw, "base", base).render(writer), .group => @fieldParentPtr(Group, "base", base).render(writer), .path => @fieldParentPtr(Path, "base", base).render(writer), .line => @fieldParentPtr(Line, "base", base).render(writer), .rect => @fieldParentPtr(Rect, "base", base).render(writer), .text => @fieldParentPtr(Text, "base", base).render(writer), }; } fn renderImpl(base: *const Element, writer: anytype) @TypeOf(writer).Error!void { if (base.id) |id| { try writer.print("id='{s}' ", .{id}); } if (base.css_classes) |classes| { try writer.print("class='{s}' ", .{classes}); } if (base.onclick) |onclick| { try writer.print("onclick='{s}' ", .{onclick}); } } pub fn cast(base: *Element, comptime T: type) ?*T { if (T.base_tag != base.tag) return null; return @fieldParentPtr(T, "base", base); } }; id: ?[]const u8 = null, height: usize, width: usize, children: std.ArrayListUnmanaged(*Element) = .{}, css_styles: std.ArrayListUnmanaged([]const u8) = .{}, pub fn deinit(self: *Svg, allocator: Allocator) void { for (self.children.items) |child| { child.deinit(allocator); } self.children.deinit(allocator); self.css_styles.deinit(allocator); } pub fn render(self: Svg, writer: anytype) @TypeOf(writer).Error!void { try writer.print("<svg height='{d}' width='{d}' ", .{ self.height, self.width }); if (self.css_styles.items.len > 0) { try writer.writeAll("style=\""); for (self.css_styles.items) |css| { try writer.writeAll(css); } try writer.writeAll("\""); } if (self.id) |id| { try writer.print("id='{s}' ", .{id}); } try writer.writeAll(">"); for (self.children.items) |child| { try child.render(writer); } try writer.writeAll("</svg>"); }
src/Svg.zig
const builtin = @import("builtin"); const std = @import("std"); const crypto = std.crypto; /// Possible errors when generating a code pub const CodeGenError = error{ /// OutOfBounds is triggered when digits is smaller than 6 or higher than 8. OutOfBounds, /// UnsupportedAlgorithm is triggered when an algorithm is passed of which is not supported. UnsupportedAlgorithm, }; /// Supported hashing algorithms for generating an OTP. /// Currently `Sha1` and `Sha256` are supported. pub const Algorithm = enum { Sha1, Sha256, }; /// Options can be provided to Totp to generate a code dependent on /// the give `digits`, `algorithm` and `time_step`. pub const Options = struct { digits: u8 = 6, algorithm: Algorithm = .Sha1, time_step: u8 = 30, }; /// Hotp is a counter-based One Time password generator. /// It implements `rfc4226` which can be found at /// https://tools.ietf.org/html/rfc4226 pub const Hotp = struct { const Self = @This(); digits: u8 = 6, /// Init creates a new Hotp struct with the `digits` set by default to 6. pub fn init() Self { return .{}; } /// generateCode creates a new code using the given secret. /// The counter needs to be synchronized between the client and server. /// It is up to the implementation to handle the synchronization, this library does not facilitate it. pub fn generateCode(self: Self, secret: []const u8, counter: u64) ![]u8 { return buildCode(secret, counter, self.digits, Algorithm.Sha1); } }; /// Totp is a time-based One Time Password generator. /// It implements `rfc6238` which can be found at /// https://tools.ietf.org/html/rfc6238 pub const Totp = struct { const Self = @This(); opts: Options, /// Init creates a new Totp struct and handles the generated codes according to it. pub fn init(opts: Options) Self { return .{ .opts = opts }; } /// generateCode creates a new code with a length of `digits`. /// `timestamp` can be generated using `std.milliTimestamp`. pub fn generateCode(self: Self, secret: []const u8, time: i64) ![]u8 { // Convert to floats for higher precision const counter = @intToFloat(f64, @bitCast(u64, time)) / @intToFloat(f64, self.opts.time_step); return buildCode(secret, @floatToInt(u64, std.math.floor(counter)), self.opts.digits, self.opts.algorithm); } }; /// generateCode creates the actual code given the provided parameters from the `Hotp` & `Totp` structs. fn buildCode(secret: []const u8, counter: u64, digits: u8, algorithm: Algorithm) ![]u8 { if (digits < 6 or digits > 8) { return CodeGenError.OutOfBounds; } var buf: []u8 = undefined; switch (algorithm) { .Sha1 => { const hmac = crypto.HmacSha1; var buffer: [hmac.mac_length]u8 = undefined; var ctx = hmac.init(secret); ctx.update(intToSlice(counter)); ctx.final(buffer[0..]); buf = buffer[0..buffer.len]; }, .Sha256 => { const hmac = crypto.HmacSha256; var buffer: [hmac.mac_length]u8 = undefined; var ctx = hmac.init(secret); ctx.update(intToSlice(counter)); ctx.final(buffer[0..]); buf = buffer[0..buffer.len]; }, else => { return CodeGenError.UnsupportedAlgorithm; }, } // Truncate HS (HS = Hmac(key, counter)) // https://tools.ietf.org/html/rfc4226#section-5.4 const offset = buf[buf.len - 1] & 0xf; const bin_code: u32 = @as(u32, (buf[offset] & 0x7f)) << 24 | @as(u32, (buf[offset + 1] & 0xff)) << 16 | @as(u32, (buf[offset + 2] & 0xff)) << 8 | @as(u32, (buf[offset + 3] & 0xff)); // add padding to the left incase the first number is a 0 const code = bin_code % std.math.pow(u32, 10, digits); return formatCode(code, digits); } /// Creates a byte slice from the given integer fn intToSlice(val: u64) []const u8 { var bytes: [8]u8 = undefined; std.mem.writeIntBig(u64, &bytes, val); return bytes[0..]; } /// formatCode will try to parse the integer and return a string. /// An extra `0` will be added to the left to match the given length. fn formatCode(val: u64, length: u8) []u8 { var buf: [8]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); std.fmt.formatIntValue(val, "", std.fmt.FormatOptions{ .width = length, .fill = '0' }, fbs.outStream()) catch unreachable; return fbs.getWritten(); } test "HOTP code generation" { const hotp = Hotp.init(); const code = try hotp.generateCode("secretkey", 0); std.testing.expectEqualSlices(u8, "049381", code); } test "HOTP 8 digits" { var hotp = Hotp.init(); hotp.digits = 8; const code = try hotp.generateCode("secretkey", 0); std.testing.expectEqualSlices(u8, "74049381", code); } test "HOTP different counters" { const hotp = Hotp.init(); var code = try hotp.generateCode("secretkey", 1); std.testing.expectEqualSlices(u8, "534807", code); code = try hotp.generateCode("secretkey", 2); std.testing.expectEqualSlices(u8, "155320", code); code = try hotp.generateCode("secretkey", 3); std.testing.expectEqualSlices(u8, "642297", code); code = try hotp.generateCode("secretkey", 4); std.testing.expectEqualSlices(u8, "964223", code); code = try hotp.generateCode("secretkey", 5); std.testing.expectEqualSlices(u8, "416848", code); } test "TOTP code generation" { const totp = Totp.init(Options{}); const time = 1587915766; const code = try totp.generateCode("secretkey", time); std.testing.expectEqualSlices(u8, "623043", code); }
src/otp.zig
const std = @import("std"); const iface = @import("interface"); const utility = @import("utility.zig"); // Import modules to reduce file size usingnamespace @import("value.zig"); usingnamespace @import("../common/compile-unit.zig"); usingnamespace @import("context.zig"); usingnamespace @import("vm.zig"); usingnamespace @import("objects.zig"); /// A script function contained in either this or a foreign /// environment. For foreign environments. pub const ScriptFunction = struct { /// This is a reference to the environment for that function. /// If the environment is `null`, the environment is context-sensitive /// and will always be the environment that provided that function. /// This is a "workaround" for not storing a pointer-to-self in Environment for /// embedded script functions. environment: ?*Environment, entryPoint: u32, localCount: u16, }; pub const UserFunctionCall = fn ( environment: *Environment, context: Context, args: []const Value, ) anyerror!Value; /// A synchronous function that may be called from the script environment pub const UserFunction = struct { const Self = @This(); /// Context, will be passed to `call`. context: Context, /// Executes the function, returns a value synchronously. call: UserFunctionCall, /// Optional destructor that may free the memory stored in `context`. /// Is called when the function call is deinitialized. destructor: ?fn (context: Context) void, pub fn deinit(self: *Self) void { if (self.destructor) |dtor| { dtor(self.context); } self.* = undefined; } }; test "UserFunction (destructor)" { var uf1: UserFunction = .{ .context = Context.initVoid(), .call = undefined, .destructor = null, }; defer uf1.deinit(); var uf2: UserFunction = .{ .context = Context.init(u32, try std.testing.allocator.create(u32)), .call = undefined, .destructor = struct { fn destructor(ctx: Context) void { std.testing.allocator.destroy(ctx.get(u32)); } }.destructor, }; defer uf2.deinit(); } pub const AsyncUserFunctionCall = fn ( environment: *Environment, context: Context, args: []const Value, ) anyerror!AsyncFunctionCall; /// An asynchronous function that yields execution of the VM /// and can be resumed later. pub const AsyncUserFunction = struct { const Self = @This(); /// Context, will be passed to `call`. context: Context, /// Begins execution of this function. /// After the initialization, the return value will be invoked once /// to check if the function can finish synchronously. call: AsyncUserFunctionCall, /// Optional destructor that may free the memory stored in `context`. /// Is called when the function call is deinitialized. destructor: ?fn (context: Context) void, pub fn deinit(self: *Self) void { if (self.destructor) |dtor| { dtor(self.context); } self.* = undefined; } }; test "AsyncUserFunction (destructor)" { var uf1: AsyncUserFunction = .{ .context = undefined, .call = undefined, .destructor = null, }; defer uf1.deinit(); var uf2: AsyncUserFunction = .{ .context = Context.init(u32, try std.testing.allocator.create(u32)), .call = undefined, .destructor = struct { fn destructor(ctx: Context) void { std.testing.allocator.destroy(ctx.get(u32)); } }.destructor, }; defer uf2.deinit(); } /// An asynchronous execution state. pub const AsyncFunctionCall = struct { const Self = @This(); /// The object this call state is associated with. This is required to /// prevent calling functions that operate on dead objects. /// This field is set by the VM and should not be initialized by the creator /// of the call. object: ?ObjectHandle = null, /// The context may be used to to store the state of this function call. /// This may be created with `@sliceToBytes`. context: Context, /// Executor that will run this function call. /// May return a value (function call completed) or `null` (function call still in progress). execute: fn (context: Context) anyerror!?Value, /// Optional destructor that may free the memory stored in `context`. /// Is called when the function call is deinitialized. destructor: ?fn (context: Context) void, pub fn deinit(self: *Self) void { if (self.destructor) |dtor| { dtor(self.context); } self.* = undefined; } }; test "AsyncFunctionCall.deinit" { const Helper = struct { fn destroy(context: Context) void { std.testing.allocator.destroy(context.get(u32)); } fn exec(context: Context) anyerror!?Value { return error.NotSupported; } }; var callWithDtor = AsyncFunctionCall{ .object = null, .context = Context.init(u32, try std.testing.allocator.create(u32)), .execute = Helper.exec, .destructor = Helper.destroy, }; defer callWithDtor.deinit(); var callNoDtor = AsyncFunctionCall{ .object = null, .context = undefined, .execute = Helper.exec, .destructor = null, }; defer callNoDtor.deinit(); } /// A function that can be called by a script. pub const Function = union(enum) { const Self = @This(); /// This is another function of a script. It may be a foreign /// or local script to the environment. script: ScriptFunction, /// A synchronous function like `Sin` that executes in very short time. syncUser: UserFunction, /// An asynchronous function that will yield the VM execution. asyncUser: AsyncUserFunction, pub fn initSimpleUser(fun: fn (env: *Environment, context: Context, args: []const Value) anyerror!Value) Function { return Self{ .syncUser = UserFunction{ .context = Context.initVoid(), .destructor = null, .call = fun, }, }; } fn convertToZigValue(comptime Target: type, value: Value) !Target { const info = @typeInfo(Target); if (info == .Int) return try value.toInteger(Target); if (info == .Float) return @floatCast(Target, try value.toNumber()); if (info == .Optional) { if (value == .void) return null; return try convertToZigValue(std.meta.Child(Target), value); } return switch (Target) { // Native types void => try value.toVoid(), bool => try value.toBoolean(), []const u8 => value.toString(), // LoLa types ObjectHandle => try value.toObject(), String => if (value == .string) value.string else return error.TypeMismatch, Array => value.toArray(), Value => value, else => @compileError(@typeName(Target) ++ " is not a wrappable type!"), }; } fn convertToLoLaValue(allocator: *std.mem.Allocator, value: anytype) !Value { const T = @TypeOf(value); const info = @typeInfo(T); if (info == .Int) return Value.initInteger(T, value); if (info == .Float) return Value.initNumber(value); if (info == .Optional) { if (value) |unwrapped| return try convertToLoLaValue(allocator, unwrapped); return .void; } if (info == .ErrorUnion) { return try convertToLoLaValue(allocator, try value); } if (info == .ErrorSet) { return value; } return switch (T) { // Native types void => .void, bool => Value.initBoolean(value), []const u8 => try Value.initString(allocator, value), // LoLa types ObjectHandle => Value.initObject(value), String => Value.fromString(value), Array => Value.fromArray(value), Value => value, else => @compileError(@typeName(T) ++ " is not a wrappable type!"), }; } /// Wraps a native zig function into a LoLa function. /// The function may take any number of arguments of supported types and return one of those as well. /// Supported types are: /// - `lola.runtime.Value` /// - `lola.runtime.String` /// - `lola.runtime.Array` /// - `lola.runtime.ObjectHandle` /// - any integer type /// - any floating point type /// - `bool` /// - `void` /// - `[]const u8` /// Note that when you receive arguments, you don't own them. Do not free or store String or Array values. /// When you return a String or Array, you hand over ownership of that value to the LoLa vm. pub fn wrap(comptime function: anytype) Function { const F = @TypeOf(function); const info = @typeInfo(F); if (info != .Fn) @compileError("Function.wrap expects a function!"); const function_info = info.Fn; if (function_info.is_generic) @compileError("Cannot wrap generic functions!"); if (function_info.is_var_args) @compileError("Cannot wrap functions with variadic arguments!"); const ArgsTuple = std.meta.ArgsTuple(F); const Impl = struct { fn invoke(env: *Environment, context: Context, args: []const Value) anyerror!Value { if (args.len != function_info.args.len) return error.InvalidArgs; var zig_args: ArgsTuple = undefined; comptime var index = 0; inline while (index < function_info.args.len) : (index += 1) { const T = function_info.args[index].arg_type.?; zig_args[index] = try convertToZigValue(T, args[index]); } const ReturnType = function_info.return_type.?; const ActualReturnType = switch (@typeInfo(ReturnType)) { .ErrorUnion => |eu| eu.payload, else => ReturnType, }; var result: ActualReturnType = if (ReturnType != ActualReturnType) try @call(.{}, function, zig_args) else @call(.{}, function, zig_args); return try convertToLoLaValue(env.allocator, result); } }; return initSimpleUser(Impl.invoke); } pub fn wrapWithContext(comptime function: anytype, context: @typeInfo(@TypeOf(function)).Fn.args[0].arg_type.?) Function { const F = @TypeOf(function); const FunctionContext = std.meta.Child(@TypeOf(context)); const info = @typeInfo(F); if (info != .Fn) @compileError("Function.wrap expects a function!"); const function_info = info.Fn; if (function_info.is_generic) @compileError("Cannot wrap generic functions!"); if (function_info.is_var_args) @compileError("Cannot wrap functions with variadic arguments!"); const ArgsTuple = std.meta.ArgsTuple(F); const Impl = struct { fn invoke(env: *Environment, wrapped_context: Context, args: []const Value) anyerror!Value { if (args.len != (function_info.args.len - 1)) return error.InvalidArgs; var zig_args: ArgsTuple = undefined; zig_args[0] = wrapped_context.get(FunctionContext); comptime var index = 1; inline while (index < function_info.args.len) : (index += 1) { const T = function_info.args[index].arg_type.?; zig_args[index] = try convertToZigValue(T, args[index - 1]); } const ReturnType = function_info.return_type.?; const ActualReturnType = switch (@typeInfo(ReturnType)) { .ErrorUnion => |eu| eu.payload, else => ReturnType, }; var result: ActualReturnType = if (ReturnType != ActualReturnType) try @call(.{}, function, zig_args) else @call(.{}, function, zig_args); return try convertToLoLaValue(env.allocator, result); } }; return Self{ .syncUser = UserFunction{ .context = Context.init(FunctionContext, context), .destructor = null, .call = Impl.invoke, }, }; } pub fn deinit(self: *@This()) void { switch (self.*) { .script => {}, .syncUser => |*f| f.deinit(), .asyncUser => |*f| f.deinit(), } } }; /// An execution environment provides all needed /// data to execute a compiled piece of code. /// It stores its global variables, available functions /// and available features. pub const Environment = struct { const Self = @This(); allocator: *std.mem.Allocator, /// The compile unit that provides the executed script. compileUnit: *const CompileUnit, /// Global variables required by the script. scriptGlobals: []Value, /// Object interface to objectPool: ObjectPoolInterface, /// Stores all available global functions. /// Functions will be contained in this unit and will be deinitialized, /// the name must be kept alive until end of the environment. functions: std.StringHashMap(Function), /// This is called when the destroyObject is called. destructor: ?fn (self: *Environment) void, pub fn init(allocator: *std.mem.Allocator, compileUnit: *const CompileUnit, object_pool: ObjectPoolInterface) !Self { var self = Self{ .allocator = allocator, .compileUnit = compileUnit, .objectPool = object_pool, .scriptGlobals = undefined, .functions = undefined, .destructor = null, }; self.scriptGlobals = try allocator.alloc(Value, compileUnit.globalCount); errdefer allocator.free(self.scriptGlobals); for (self.scriptGlobals) |*glob| { glob.* = .void; } self.functions = std.StringHashMap(Function).init(allocator); errdefer self.functions.deinit(); for (compileUnit.functions) |srcfun| { var fun = Function{ .script = ScriptFunction{ .environment = null, // this is a "self-contained" script function .entryPoint = srcfun.entryPoint, .localCount = srcfun.localCount, }, }; _ = try self.functions.put(srcfun.name, fun); } return self; } pub fn deinit(self: *Self) void { var iter = self.functions.iterator(); while (iter.next()) |fun| { fun.value.deinit(); } for (self.scriptGlobals) |*glob| { glob.deinit(); } self.functions.deinit(); self.allocator.free(self.scriptGlobals); self.* = undefined; } /// Adds a function to the environment and makes it available for the script. pub fn installFunction(self: *Self, name: []const u8, function: Function) !void { var result = try self.functions.getOrPut(name); if (result.found_existing) return error.AlreadyExists; result.entry.value = function; } // Implementation to make a Environment a valid LoLa object: pub fn getMethod(self: *Self, name: []const u8) ?Function { if (self.functions.get(name)) |fun| { var mut_fun = fun; if (mut_fun == .script and mut_fun.script.environment == null) mut_fun.script.environment = self; return mut_fun; } else { return null; } } /// This is called when the object is removed from the associated object pool. pub fn destroyObject(self: *Self) void { if (self.destructor) |dtor| { dtor(self); } } /// Computes a unique signature for this environment based on /// the size and functions stored in the environment. This is used /// for serialization to ensure that Environments are restored into same /// state is it was serialized from previously. fn computeSignature(self: Self) u64 { var hasher = std.hash.SipHash64(2, 4).init("Environment Serialization Version 1"); // Hash all function names to create reproducability { var iter = self.functions.iterator(); while (iter.next()) |item| { hasher.update(item.key); } } // safe the length of the script globals as a bad signature for // the comileUnit { var buf: [8]u8 = undefined; std.mem.writeIntLittle(u64, &buf, self.scriptGlobals.len); hasher.update(&buf); } return hasher.finalInt(); } /// Serializes the environment globals in a way that these /// are restorable later. pub fn serialize(self: Self, stream: anytype) !void { const sig = self.computeSignature(); try stream.writeIntLittle(u64, sig); for (self.scriptGlobals) |glob| { try glob.serialize(stream); } } /// Deserializes the environment globals. This might fail with /// `error.SignatureMismatch` when a environment with a different signature /// is restored. pub fn deserialize(self: *Self, stream: anytype) !void { const sig_env = self.computeSignature(); const sig_ser = try stream.readIntLittle(u64); if (sig_env != sig_ser) return error.SignatureMismatch; for (self.scriptGlobals) |*glob| { const val = try Value.deserialize(stream, self.allocator); glob.replaceWith(val); } } }; test "Environment" { const cu = CompileUnit{ .arena = undefined, .comment = "", .globalCount = 4, .temporaryCount = 0, .code = "", .functions = &[_]CompileUnit.Function{ CompileUnit.Function{ .name = "fun1", .entryPoint = 10, .localCount = 5, }, CompileUnit.Function{ .name = "fun_2", .entryPoint = 21, .localCount = 1, }, CompileUnit.Function{ .name = "fun 3", .entryPoint = 32, .localCount = 3, }, }, .debugSymbols = &[0]CompileUnit.DebugSymbol{}, }; var pool = ObjectPool(.{}).init(std.testing.allocator); defer pool.deinit(); var env = try Environment.init(std.testing.allocator, &cu, pool.interface()); defer env.deinit(); std.debug.assert(env.scriptGlobals.len == 4); std.debug.assert(env.functions.count() == 3); const f1 = env.getMethod("fun1") orelse unreachable; const f2 = env.getMethod("fun_2") orelse unreachable; const f3 = env.getMethod("fun 3") orelse unreachable; std.testing.expectEqual(@as(usize, 10), f1.script.entryPoint); std.testing.expectEqual(@as(usize, 5), f1.script.localCount); std.testing.expectEqual(&env, f1.script.environment.?); std.testing.expectEqual(@as(usize, 21), f2.script.entryPoint); std.testing.expectEqual(@as(usize, 1), f2.script.localCount); std.testing.expectEqual(&env, f2.script.environment.?); std.testing.expectEqual(@as(usize, 32), f3.script.entryPoint); std.testing.expectEqual(@as(usize, 3), f3.script.localCount); std.testing.expectEqual(&env, f3.script.environment.?); } test "Function.wrap" { const Funcs = struct { fn returnVoid() void { unreachable; } fn returnValue() Value { unreachable; } fn returnString() String { unreachable; } fn returnArray() Array { unreachable; } fn returnObjectHandle() ObjectHandle { unreachable; } fn returnInt8() u8 { unreachable; } fn returnInt63() i63 { unreachable; } fn returnF64() f64 { unreachable; } fn returnF16() f16 { unreachable; } fn returnBool() bool { unreachable; } fn returnStringLit() []const u8 { unreachable; } fn takeVoid(value: void) void { unreachable; } fn takeValue(value: Value) void { unreachable; } fn takeString(value: String) void { unreachable; } fn takeArray(value: Array) void { unreachable; } fn takeObjectHandle(value: ObjectHandle) void { unreachable; } fn takeInt8(value: u8) void { unreachable; } fn takeInt63(value: i63) void { unreachable; } fn takeF64(value: f64) void { unreachable; } fn takeF16(value: f16) void { unreachable; } fn takeBool(value: bool) void { unreachable; } fn takeStringLit(value: []const u8) void { unreachable; } fn takeAll( a0: Value, a1: String, a2: Array, a3: ObjectHandle, a4_1: u7, a4_2: i33, a5_1: f32, a5_2: f16, a6: bool, a7: void, a8: []const u8, ) void { unreachable; } }; inline for (std.meta.declarations(Funcs)) |fun| { _ = Function.wrap(@field(Funcs, fun.name)); } }
src/library/runtime/environment.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Item = struct { cost: u16, atk: i8 = 0, def: i8 = 0 }; pub fn run(problem: *aoc.Problem) !aoc.Solution { const player_hp: u8 = 100; const weapons = [_]Item { .{ .cost = 8, .atk = 4 }, .{ .cost = 10, .atk = 5 }, .{ .cost = 25, .atk = 6 }, .{ .cost = 40, .atk = 7 }, .{ .cost = 74, .atk = 8 }, }; const armor = [_]Item { .{ .cost = 0 }, .{ .cost = 13, .def = 1 }, .{ .cost = 31, .def = 2 }, .{ .cost = 53, .def = 3 }, .{ .cost = 75, .def = 4 }, .{ .cost = 102, .def = 5 }, }; const rings = [_]Item { .{ .cost = 0 }, .{ .cost = 0 }, .{ .cost = 25, .atk = 1 }, .{ .cost = 50, .atk = 2 }, .{ .cost = 100, .atk = 3 }, .{ .cost = 20, .def = 1 }, .{ .cost = 40, .def = 2 }, .{ .cost = 80, .def = 3 }, }; var tokens = std.mem.tokenize(u8, problem.input, ": \n"); _ = tokens.next().?; _ = tokens.next().?; const boss_hp = try std.fmt.parseInt(u8, tokens.next().?, 10); _ = tokens.next().?; const boss_atk = try std.fmt.parseInt(i8, tokens.next().?, 10); _ = tokens.next().?; const boss_def = try std.fmt.parseInt(i8, tokens.next().?, 10); var cheapest_win: u16 = std.math.maxInt(u16); var expensive_lose: u16 = 0; for (weapons) |w| { for (armor) |a| { for (rings) |r1, r1i| { for (rings[r1i+1..]) |r2| { const total_cost = w.cost + a.cost + r1.cost + r2.cost; const player_atk = w.atk + r1.atk + r2.atk; const player_def = a.def + r1.def + r2.def; const player_hp_delta = @intCast(u8, std.math.max(boss_atk-player_def, 1)); const player_survives = player_hp / player_hp_delta - if (player_hp % player_hp_delta == 0) @as(u16, 1) else 0; const boss_hp_delta = @intCast(u8, std.math.max(player_atk-boss_def, 1)); const boss_survives = boss_hp / boss_hp_delta - if (boss_hp % boss_hp_delta == 0) @as(u16, 1) else 0; if (player_survives >= boss_survives) { cheapest_win = std.math.min(cheapest_win, total_cost); } else { expensive_lose = std.math.max(expensive_lose, total_cost); } } } } } return problem.solution(cheapest_win, expensive_lose); }
src/main/zig/2015/day21.zig
const kernel = @import("../../kernel.zig"); const log = kernel.log.scoped(.ACPI); const TODO = kernel.TODO; const Virtual = kernel.Virtual; const Physical = kernel.Physical; /// ACPI initialization. We should have a page mapper ready before executing this function pub fn init(rsdp_physical_address: kernel.Physical.Address) void { var rsdp_physical_page = rsdp_physical_address; log.debug("RSDP: 0x{x}", .{rsdp_physical_address.value}); rsdp_physical_page.page_align_backward(); const rsdp1 = rsdp_physical_address.access_higher_half(*align(1) RSDP1); if (rsdp1.revision == 0) { log.debug("First version", .{}); log.debug("RSDT: 0x{x}", .{rsdp1.RSDT_address}); const rsdt_physical_address = Physical.Address.new(rsdp1.RSDT_address); var rsdt_physical_page = rsdt_physical_address; rsdt_physical_page.page_align_backward(); kernel.address_space.map(rsdt_physical_page, rsdt_physical_page.identity_virtual_address()); const rsdt = rsdt_physical_address.access_identity(*align(1) Header); log.debug("RSDT length: {}", .{rsdt.length}); const rsdt_table_count = (rsdt.length - @sizeOf(Header)) / @sizeOf(u32); log.debug("RSDT table count: {}", .{rsdt_table_count}); const tables = @intToPtr([*]align(1) u32, @ptrToInt(rsdt) + @sizeOf(Header))[0..rsdt_table_count]; for (tables) |table_address| { log.debug("Table address: 0x{x}", .{table_address}); const header = @intToPtr(*align(1) Header, table_address); if (kernel.string_eq(&header.signature, "APIC")) { const madt = @ptrCast(*align(1) MADT, header); log.debug("MADT: {}", .{madt}); log.debug("LAPIC address: 0x{x}", .{madt.LAPIC_address}); const madt_top = @ptrToInt(madt) + madt.header.length; var offset = @ptrToInt(madt) + @sizeOf(MADT); var processor_count: u64 = 0; var entry_length: u64 = undefined; while (offset != madt_top) : (offset += entry_length) { const entry_type = @intToPtr(*MADT.Type, offset).*; entry_length = @intToPtr(*u8, offset + 1).*; processor_count += @boolToInt(entry_type == .LAPIC); } //kernel.cpus = kernel.core_heap.allocate_many(kernel.arch.CPU, processor_count); processor_count = 0; offset = @ptrToInt(madt) + @sizeOf(MADT); while (offset != madt_top) : (offset += entry_length) { const entry_type = @intToPtr(*MADT.Type, offset).*; entry_length = @intToPtr(*u8, offset + 1).*; switch (entry_type) { .LAPIC => { const lapic = @intToPtr(*align(1) MADT.LAPIC, offset); log.debug("LAPIC: {}", .{lapic}); kernel.assert(@src(), @sizeOf(MADT.LAPIC) == entry_length); }, .IO_APIC => { const ioapic = @intToPtr(*align(1) MADT.IO_APIC, offset); log.debug("IO_APIC: {}", .{ioapic}); kernel.assert(@src(), @sizeOf(MADT.IO_APIC) == entry_length); }, .ISO => { const iso = @intToPtr(*align(1) MADT.InterruptSourceOverride, offset); log.debug("ISO: {}", .{iso}); kernel.assert(@src(), @sizeOf(MADT.InterruptSourceOverride) == entry_length); }, .LAPIC_NMI => { const lapic_nmi = @intToPtr(*align(1) MADT.LAPIC_NMI, offset); log.debug("LAPIC_NMI: {}", .{lapic_nmi}); kernel.assert(@src(), @sizeOf(MADT.LAPIC_NMI) == entry_length); }, else => kernel.panic("ni: {}", .{entry_type}), } } } else { log.debug("Ignored table: {s}", .{header.signature}); } } } else { kernel.assert(@src(), rsdp1.revision == 2); //const rsdp2 = @ptrCast(*RSDP2, rsdp1); log.debug("Second version", .{}); TODO(@src()); } } const rsdt_signature = [4]u8{ 'R', 'S', 'D', 'T' }; pub fn check_valid_sdt(rsdt: *align(1) Header) void { log.debug("Header size: {}", .{@sizeOf(Header)}); kernel.assert(@src(), @sizeOf(Header) == 36); if (rsdt.revision != 1) { @panic("bad revision"); } if (!kernel.string_eq(&rsdt.signature, &rsdt_signature)) { @panic("bad signature"); } if (rsdt.length >= 16384) { @panic("bad length"); } if (checksum(@ptrCast([*]u8, rsdt)[0..rsdt.length]) != 0) { @panic("bad checksum"); } } fn checksum(slice: []const u8) u8 { if (slice.len == 0) return 0; var total: u64 = 0; for (slice) |byte| { total += byte; } return @truncate(u8, total); } const RSDP1 = extern struct { signature: [8]u8, checksum: u8, OEM_ID: [6]u8, revision: u8, RSDT_address: u32, comptime { kernel.assert_unsafe(@sizeOf(RSDP1) == 20); } }; const RSDP2 = packed struct { rsdp1: RSDP1, length: u32, XSDT_address: u64, extended_checksum: u8, reserved: [3]u8, }; const Header = extern struct { signature: [4]u8, length: u32, revision: u8, checksum: u8, OEM_ID: [6]u8, OEM_table_ID: [8]u8, OEM_revision: u32, creator_ID: u32, creator_revision: u32, comptime { kernel.assert_unsafe(@sizeOf(Header) == 36); } }; const MADT = extern struct { header: Header, LAPIC_address: u32, flags: u32, const Type = enum(u8) { LAPIC = 0, IO_APIC = 1, ISO = 2, NMI_source = 3, LAPIC_NMI = 4, LAPIC_address_override = 5, IO_SAPIC = 6, LSAPIC = 7, platform_interrupt_sources = 8, Lx2APIC = 9, Lx2APIC_NMI = 0xa, GIC_CPU_interface = 0xb, GIC_distributor = 0xc, GIC_MSI_frame = 0xd, GIC_redistributor = 0xe, GIC_interrupt_translation_service = 0xf, }; const LAPIC = struct { type: Type, length: u8, ACPI_processor_UID: u8, APIC_ID: u8, flags: u32, }; const IO_APIC = struct { type: Type, length: u8, IO_APIC_ID: u8, reserved: u8, IO_APIC_address: u32, global_system_interrupt_base: u32, }; const InterruptSourceOverride = packed struct { type: Type, length: u8, bus: u8, source: u8, global_system_interrupt: u32, flags: u16, }; const LAPIC_NMI = packed struct { type: Type, length: u8, ACPI_processor_UID: u8, flags: u16, LAPIC_lint: u8, }; };
src/kernel/arch/x86_64/acpi.zig
const expectEqual = @import("std").testing.expectEqual; const std = @import("std"); const expect = std.testing.expect; const minInt = std.math.minInt; test "@bitReverse" { comptime try testBitReverse(); try testBitReverse(); } fn testBitReverse() !void { // using comptime_ints, unsigned try expectEqual(@bitReverse(u0, 0), 0); try expectEqual(@bitReverse(u5, 0x12), 0x9); try expectEqual(@bitReverse(u8, 0x12), 0x48); try expectEqual(@bitReverse(u16, 0x1234), 0x2c48); try expectEqual(@bitReverse(u24, 0x123456), 0x6a2c48); try expectEqual(@bitReverse(u32, 0x12345678), 0x1e6a2c48); try expectEqual(@bitReverse(u40, 0x123456789a), 0x591e6a2c48); try expectEqual(@bitReverse(u48, 0x123456789abc), 0x3d591e6a2c48); try expectEqual(@bitReverse(u56, 0x123456789abcde), 0x7b3d591e6a2c48); try expectEqual(@bitReverse(u64, 0x123456789abcdef1), 0x8f7b3d591e6a2c48); try expectEqual(@bitReverse(u128, 0x123456789abcdef11121314151617181), 0x818e868a828c84888f7b3d591e6a2c48); // using runtime uints, unsigned var num0: u0 = 0; try expectEqual(@bitReverse(u0, num0), 0); var num5: u5 = 0x12; try expectEqual(@bitReverse(u5, num5), 0x9); var num8: u8 = 0x12; try expectEqual(@bitReverse(u8, num8), 0x48); var num16: u16 = 0x1234; try expectEqual(@bitReverse(u16, num16), 0x2c48); var num24: u24 = 0x123456; try expectEqual(@bitReverse(u24, num24), 0x6a2c48); var num32: u32 = 0x12345678; try expectEqual(@bitReverse(u32, num32), 0x1e6a2c48); var num40: u40 = 0x123456789a; try expectEqual(@bitReverse(u40, num40), 0x591e6a2c48); var num48: u48 = 0x123456789abc; try expectEqual(@bitReverse(u48, num48), 0x3d591e6a2c48); var num56: u56 = 0x123456789abcde; try expectEqual(@bitReverse(u56, num56), 0x7b3d591e6a2c48); var num64: u64 = 0x123456789abcdef1; try expectEqual(@bitReverse(u64, num64), 0x8f7b3d591e6a2c48); var num128: u128 = 0x123456789abcdef11121314151617181; try expectEqual(@bitReverse(u128, num128), 0x818e868a828c84888f7b3d591e6a2c48); // using comptime_ints, signed, positive try expectEqual(@bitReverse(u8, @as(u8, 0)), 0); try expectEqual(@bitReverse(i8, @bitCast(i8, @as(u8, 0x92))), @bitCast(i8, @as(u8, 0x49))); try expectEqual(@bitReverse(i16, @bitCast(i16, @as(u16, 0x1234))), @bitCast(i16, @as(u16, 0x2c48))); try expectEqual(@bitReverse(i24, @bitCast(i24, @as(u24, 0x123456))), @bitCast(i24, @as(u24, 0x6a2c48))); try expectEqual(@bitReverse(i32, @bitCast(i32, @as(u32, 0x12345678))), @bitCast(i32, @as(u32, 0x1e6a2c48))); try expectEqual(@bitReverse(i40, @bitCast(i40, @as(u40, 0x123456789a))), @bitCast(i40, @as(u40, 0x591e6a2c48))); try expectEqual(@bitReverse(i48, @bitCast(i48, @as(u48, 0x123456789abc))), @bitCast(i48, @as(u48, 0x3d591e6a2c48))); try expectEqual(@bitReverse(i56, @bitCast(i56, @as(u56, 0x123456789abcde))), @bitCast(i56, @as(u56, 0x7b3d591e6a2c48))); try expectEqual(@bitReverse(i64, @bitCast(i64, @as(u64, 0x123456789abcdef1))), @bitCast(i64, @as(u64, 0x8f7b3d591e6a2c48))); try expectEqual(@bitReverse(i128, @bitCast(i128, @as(u128, 0x123456789abcdef11121314151617181))), @bitCast(i128, @as(u128, 0x818e868a828c84888f7b3d591e6a2c48))); // using signed, negative. Compare to runtime ints returned from llvm. var neg8: i8 = -18; try expectEqual(@bitReverse(i8, @as(i8, -18)), @bitReverse(i8, neg8)); var neg16: i16 = -32694; try expectEqual(@bitReverse(i16, @as(i16, -32694)), @bitReverse(i16, neg16)); var neg24: i24 = -6773785; try expectEqual(@bitReverse(i24, @as(i24, -6773785)), @bitReverse(i24, neg24)); var neg32: i32 = -16773785; try expectEqual(@bitReverse(i32, @as(i32, -16773785)), @bitReverse(i32, neg32)); }
test/behavior/bitreverse.zig
const std = @import("std"); const zlm = @import("zlm"); const Vec3 = zlm.Vec3; const Allocator = std.mem.Allocator; const graphics = @import("didot-graphics"); const objects = @import("didot-objects"); const models = @import("didot-models"); const image = @import("didot-image"); //const physics = @import("didot-physics"); const bmp = image.bmp; const obj = models.obj; const Application = @import("didot-app").Application; const Texture = graphics.Texture; const Input = graphics.Input; const Window = graphics.Window; const ShaderProgram = graphics.ShaderProgram; const Material = graphics.Material; const GameObject = objects.GameObject; const Scene = objects.Scene; const Camera = objects.Camera; const PointLight = objects.PointLight; var input: *Input = undefined; fn cameraInput(allocator: *Allocator, gameObject: *GameObject, delta: f32) !void { const speed: f32 = 0.1 * delta; const forward = gameObject.getForward(); const left = gameObject.getLeft(); if (input.isKeyDown(Input.KEY_W)) { gameObject.position = gameObject.position.add(forward.scale(speed)); } if (input.isKeyDown(Input.KEY_S)) { gameObject.position = gameObject.position.add(forward.scale(-speed)); } if (input.isKeyDown(Input.KEY_A)) { gameObject.position = gameObject.position.add(left.scale(speed)); } if (input.isKeyDown(Input.KEY_D)) { gameObject.position = gameObject.position.add(left.scale(-speed)); } if (input.isMouseButtonDown(.Left)) { input.setMouseInputMode(.Grabbed); } else if (input.isMouseButtonDown(.Right)) { input.setMouseInputMode(.Normal); } else if (input.isKeyDown(Input.KEY_ESCAPE)) { input.setMouseInputMode(.Normal); } if (input.getMouseInputMode() == .Grabbed) { gameObject.rotation.x -= (input.mouseDelta.x / 300.0) * delta; gameObject.rotation.y -= (input.mouseDelta.y / 300.0) * delta; } if (input.getJoystick(0)) |joystick| { const axes = joystick.getRawAxes(); var fw = axes[1]; // forward var r = axes[0]; // right var thrust = (axes[3] - 1.0) * -0.5; const threshold = 0.2; if (r < threshold and r > 0) r = 0; if (r > -threshold and r < 0) r = 0; if (fw < threshold and fw > 0) fw = 0; if (fw > -threshold and fw < 0) fw = 0; gameObject.position = gameObject.position.add(forward.scale(thrust * speed)); gameObject.rotation.x -= (r / 50.0) * delta; gameObject.rotation.y -= (fw / 50.0) * delta; // std.debug.warn("A: {}, B: {}, X: {}, Y: {}\n", .{ // joystick.isButtonDown(.A), // joystick.isButtonDown(.B), // joystick.isButtonDown(.X), // joystick.isButtonDown(.Y), // }); } } fn testLight(allocator: *Allocator, gameObject: *GameObject, delta: f32) !void { const time = @intToFloat(f64, std.time.milliTimestamp()); const rad = @floatCast(f32, @mod((time / 1000.0), std.math.pi * 2.0)); gameObject.position = Vec3.new(std.math.sin(rad) * 20 + 10, 3, std.math.cos(rad) * 10 - 10); } fn loadSkybox(allocator: *Allocator, camera: *Camera, scene: *Scene) !GameObject { var skyboxShader = try ShaderProgram.createFromFile(allocator, "assets/shaders/skybox-vert.glsl", "assets/shaders/skybox-frag.glsl"); camera.*.skyboxShader = skyboxShader; try scene.assetManager.put("Texture/Skybox", .{ .loader = graphics.textureAssetLoader, .loaderData = try graphics.TextureAssetLoaderData.initCubemap(allocator, .{ .front = "assets/textures/skybox/front.bmp", .back = "assets/textures/skybox/back.bmp", .left = "assets/textures/skybox/left.bmp", .right = "assets/textures/skybox/right.bmp", .top = "assets/textures/skybox/top.bmp", .bottom = "assets/textures/skybox/bottom.bmp" }, "bmp"), .objectType = .Texture }); var skyboxMaterial = Material{ .texturePath = "Texture/Skybox" }; var skybox = try objects.createSkybox(allocator); skybox.meshPath = "Mesh/Cube"; skybox.material = skyboxMaterial; return skybox; } fn initFromFile(allocator: *Allocator, app: *Application) !void { input = &app.window.input; var scene = Scene.loadFromFile(allocator, "res/example-scene.json"); scene.findChild("Camera").?.updateFn = cameraInput; scene.findChild("Light").?.updateFn = testLight; app.scene = scene; //var skybox = try loadSkybox(allocator, camera); //try scene.add(skybox); // var i: f32 = 0; // while (i < 5) { // var j: f32 = 0; // while (j < 5) { // var kart2 = GameObject.createObject(allocator, "Mesh/Kart"); // kart2.position = Vec3.new(0.7 + (j*8), 0.75, -8 - (i*3)); // try scene.add(kart2); // j += 1; // } // i += 1; // } } fn init(allocator: *Allocator, app: *Application) !void { input = &app.window.input; var shader = try ShaderProgram.createFromFile(allocator, "assets/shaders/vert.glsl", "assets/shaders/frag.glsl"); const scene = app.scene; try scene.assetManager.put("Texture/Grass", .{ .loader = graphics.textureAssetLoader, .loaderData = try graphics.TextureAssetLoaderData.init2D(allocator, "assets/textures/grass.png", "png"), .objectType = .Texture, }); var grassMaterial = Material{ .texturePath = "Texture/Grass" }; var camera = try Camera.create(allocator, shader); camera.gameObject.position = Vec3.new(1.5, 1.5, -0.5); camera.gameObject.rotation = Vec3.new(-120.0, -15.0, 0).toRadians(); camera.gameObject.updateFn = cameraInput; try scene.add(camera.gameObject); //var skybox = try loadSkybox(allocator, camera, scene); //try scene.add(skybox); var cube = GameObject.createObject(allocator, "Mesh/Cube"); cube.position = Vec3.new(10, -0.75, -10); cube.scale = Vec3.new(20, 1, 20); cube.material = grassMaterial; try scene.add(cube); var cube2 = GameObject.createObject(allocator, "Mesh/Cube"); cube2.position = Vec3.new(-1.2, 0.75, -3); cube2.material.ambient = Vec3.new(0.2, 0.1, 0.1); cube2.material.diffuse = Vec3.new(0.8, 0.8, 0.8); try scene.add(cube2); try scene.assetManager.put("Mesh/Kart", .{ .loader = models.meshAssetLoader, .loaderData = try models.MeshAssetLoaderData.init(allocator, "assets/kart.obj", "obj"), .objectType = .Mesh, }); var kart = GameObject.createObject(allocator, "Mesh/Kart"); kart.position = Vec3.new(0.7, 0.75, -5); kart.name = "Kart"; try scene.add(kart); var i: f32 = 0; while (i < 7) { // rows front to back var j: f32 = 0; while (j < 5) { // cols left to right var kart2 = GameObject.createObject(allocator, "Mesh/Kart"); kart2.position = Vec3.new(0.7 + (j * 8), 0.75, -8 - (i * 3)); // lets decorate the kart based on its location kart2.material.ambient = Vec3.new(0.0, j * 0.001, 0.002); kart2.material.diffuse = Vec3.new(i * 0.1, j * 0.1, 0.6); // dull on the left, getting shinier to the right kart2.material.specular = Vec3.new(1.0 - (j * 0.2), 1.0 - (j * 0.2), 0.2); kart2.material.shininess = 110.0 - (j * 20.0); try scene.add(kart2); j += 1; } i += 1; } var light = try PointLight.create(allocator); light.gameObject.position = Vec3.new(1, 5, -5); light.gameObject.updateFn = testLight; light.gameObject.meshPath = "Mesh/Cube"; light.gameObject.material.ambient = Vec3.one; try scene.add(light.gameObject); //var world = physics.World.create(); } var gp: std.heap.GeneralPurposeAllocator(.{}) = undefined; pub fn main() !void { gp = .{}; defer { _ = gp.deinit(); } const allocator = &gp.allocator; var scene = try Scene.create(allocator, null); var app = Application{ .title = "Test Cubes", .initFn = init, }; try app.start(allocator, scene); }
examples/kart-and-cubes/example-scene.zig
const wlr = @import("../wlroots.zig"); const std = @import("std"); const wl = @import("wayland").server.wl; pub const ForeignToplevelManagerV1 = extern struct { event_loop: *wl.EventLoop, global: *wl.Global, resources: wl.list.Head(wl.Resource, null), toplevels: wl.list.Head(ForeignToplevelHandleV1, "link"), server_destroy: wl.Listener(*wl.Server), events: extern struct { destroy: wl.Signal(*ForeignToplevelManagerV1), }, data: usize, extern fn wlr_foreign_toplevel_manager_v1_create(wl_server: *wl.Server) ?*ForeignToplevelManagerV1; pub fn create(wl_server: *wl.Server) !*ForeignToplevelManagerV1 { return wlr_foreign_toplevel_manager_v1_create(wl_server) orelse error.OutOfMemory; } }; pub const ForeignToplevelHandleV1 = extern struct { pub const State = packed struct { maximized: bool align(@alignOf(u32)) = false, minimized: bool = false, activated: bool = false, fullscreen: bool = false, _: u28, comptime { std.debug.assert(@sizeOf(@This()) == @sizeOf(u32)); std.debug.assert(@alignOf(@This()) == @alignOf(u32)); } }; pub const Output = extern struct { link: wl.list.Link, output_destroy: wl.Listener(*wlr.Output), output: *wlr.Output, toplevel: *ForeignToplevelHandleV1, }; pub const event = struct { pub const Maximized = extern struct { toplevel: *ForeignToplevelHandleV1, maximized: bool, }; pub const Minimized = extern struct { toplevel: *ForeignToplevelHandleV1, minimized: bool, }; pub const Activated = extern struct { toplevel: *ForeignToplevelHandleV1, seat: *wlr.Seat, }; pub const Fullscreen = extern struct { toplevel: *ForeignToplevelHandleV1, fullscreen: bool, output: *wlr.Output, }; pub const SetRectangle = extern struct { toplevel: *ForeignToplevelHandleV1, surface: *wlr.Surface, x: i32, y: i32, width: i32, height: i32, }; }; manager: *ForeignToplevelManagerV1, resources: wl.list.Head(wl.Resource, null), link: wl.list.Link, idle_source: ?*wl.EventSource, title: ?[*:0]u8, app_id: ?[*:0]u8, parent: ?*ForeignToplevelHandleV1, outputs: wl.list.Head(ForeignToplevelHandleV1.Output, "link"), state: State, events: extern struct { request_maximize: wl.Signal(*event.Maximized), request_minimize: wl.Signal(*event.Minimized), request_activate: wl.Signal(*event.Activated), request_fullscreen: wl.Signal(*event.Fullscreen), request_close: wl.Signal(*ForeignToplevelHandleV1), set_rectangle: wl.Signal(*event.SetRectangle), destroy: wl.Signal(*ForeignToplevelHandleV1), }, data: usize, extern fn wlr_foreign_toplevel_handle_v1_create(manager: *ForeignToplevelManagerV1) ?*ForeignToplevelHandleV1; pub fn create(manager: *ForeignToplevelManagerV1) !*ForeignToplevelHandleV1 { return wlr_foreign_toplevel_handle_v1_create(manager) orelse error.OutOfMemory; } extern fn wlr_foreign_toplevel_handle_v1_destroy(toplevel: *ForeignToplevelHandleV1) void; pub const destroy = wlr_foreign_toplevel_handle_v1_destroy; extern fn wlr_foreign_toplevel_handle_v1_set_title(toplevel: *ForeignToplevelHandleV1, title: [*:0]const u8) void; pub const setTitle = wlr_foreign_toplevel_handle_v1_set_title; extern fn wlr_foreign_toplevel_handle_v1_set_app_id(toplevel: *ForeignToplevelHandleV1, app_id: [*:0]const u8) void; pub const setAppId = wlr_foreign_toplevel_handle_v1_set_app_id; extern fn wlr_foreign_toplevel_handle_v1_output_enter(toplevel: *ForeignToplevelHandleV1, output: *wlr.Output) void; pub const outputEnter = wlr_foreign_toplevel_handle_v1_output_enter; extern fn wlr_foreign_toplevel_handle_v1_output_leave(toplevel: *ForeignToplevelHandleV1, output: *wlr.Output) void; pub const outputLeave = wlr_foreign_toplevel_handle_v1_output_leave; extern fn wlr_foreign_toplevel_handle_v1_set_maximized(toplevel: *ForeignToplevelHandleV1, maximized: bool) void; pub const setMaximized = wlr_foreign_toplevel_handle_v1_set_maximized; extern fn wlr_foreign_toplevel_handle_v1_set_minimized(toplevel: *ForeignToplevelHandleV1, minimized: bool) void; pub const setMinimized = wlr_foreign_toplevel_handle_v1_set_minimized; extern fn wlr_foreign_toplevel_handle_v1_set_activated(toplevel: *ForeignToplevelHandleV1, activated: bool) void; pub const setActivated = wlr_foreign_toplevel_handle_v1_set_activated; extern fn wlr_foreign_toplevel_handle_v1_set_fullscreen(toplevel: *ForeignToplevelHandleV1, fullscreen: bool) void; pub const setFullscreen = wlr_foreign_toplevel_handle_v1_set_fullscreen; extern fn wlr_foreign_toplevel_handle_v1_set_parent(toplevel: *ForeignToplevelHandleV1, parent: ?*ForeignToplevelHandleV1) void; pub const setParent = wlr_foreign_toplevel_handle_v1_set_parent; };
src/types/foreign_toplevel_management_v1.zig
const std = @import("std"); const cast = std.meta.cast; const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels /// The function addcarryxU26 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^26 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^26⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x3ffffff] /// arg3: [0x0 ~> 0x3ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x3ffffff] /// out2: [0x0 ~> 0x1] fn addcarryxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u32, arg1) + arg2) + arg3); const x2 = (x1 & 0x3ffffff); const x3 = cast(u1, (x1 >> 26)); out1.* = x2; out2.* = x3; } /// The function subborrowxU26 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^26 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^26⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x3ffffff] /// arg3: [0x0 ~> 0x3ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x3ffffff] /// out2: [0x0 ~> 0x1] fn subborrowxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i32, (cast(i64, cast(i32, (cast(i64, arg2) - cast(i64, arg1)))) - cast(i64, arg3))); const x2 = cast(i1, (x1 >> 26)); const x3 = cast(u32, (cast(i64, x1) & cast(i64, 0x3ffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function addcarryxU25 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^25 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^25⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x1ffffff] /// arg3: [0x0 ~> 0x1ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x1ffffff] /// out2: [0x0 ~> 0x1] fn addcarryxU25(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u32, arg1) + arg2) + arg3); const x2 = (x1 & 0x1ffffff); const x3 = cast(u1, (x1 >> 25)); out1.* = x2; out2.* = x3; } /// The function subborrowxU25 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^25 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^25⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x1ffffff] /// arg3: [0x0 ~> 0x1ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x1ffffff] /// out2: [0x0 ~> 0x1] fn subborrowxU25(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i32, (cast(i64, cast(i32, (cast(i64, arg2) - cast(i64, arg1)))) - cast(i64, arg3))); const x2 = cast(i1, (x1 >> 25)); const x3 = cast(u32, (cast(i64, x1) & cast(i64, 0x1ffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function cmovznzU32 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] fn cmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = (~(~arg1)); const x2 = cast(u32, (cast(i64, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i64, 0xffffffff))); const x3 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function carryMul multiplies two field elements and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] /// arg2: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] pub fn carryMul(out1: *[10]u32, arg1: [10]u32, arg2: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[9]) * 0x26))); const x2 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[8]) * 0x13))); const x3 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[7]) * 0x26))); const x4 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[6]) * 0x13))); const x5 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[5]) * 0x26))); const x6 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[4]) * 0x13))); const x7 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[3]) * 0x26))); const x8 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[2]) * 0x13))); const x9 = (cast(u64, (arg1[9])) * cast(u64, ((arg2[1]) * 0x26))); const x10 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[9]) * 0x13))); const x11 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[8]) * 0x13))); const x12 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[7]) * 0x13))); const x13 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[6]) * 0x13))); const x14 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[5]) * 0x13))); const x15 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[4]) * 0x13))); const x16 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[3]) * 0x13))); const x17 = (cast(u64, (arg1[8])) * cast(u64, ((arg2[2]) * 0x13))); const x18 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[9]) * 0x26))); const x19 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[8]) * 0x13))); const x20 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[7]) * 0x26))); const x21 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[6]) * 0x13))); const x22 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[5]) * 0x26))); const x23 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[4]) * 0x13))); const x24 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[3]) * 0x26))); const x25 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[9]) * 0x13))); const x26 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[8]) * 0x13))); const x27 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[7]) * 0x13))); const x28 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[6]) * 0x13))); const x29 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[5]) * 0x13))); const x30 = (cast(u64, (arg1[6])) * cast(u64, ((arg2[4]) * 0x13))); const x31 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[9]) * 0x26))); const x32 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[8]) * 0x13))); const x33 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[7]) * 0x26))); const x34 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[6]) * 0x13))); const x35 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[5]) * 0x26))); const x36 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[9]) * 0x13))); const x37 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[8]) * 0x13))); const x38 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[7]) * 0x13))); const x39 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[6]) * 0x13))); const x40 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[9]) * 0x26))); const x41 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[8]) * 0x13))); const x42 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[7]) * 0x26))); const x43 = (cast(u64, (arg1[2])) * cast(u64, ((arg2[9]) * 0x13))); const x44 = (cast(u64, (arg1[2])) * cast(u64, ((arg2[8]) * 0x13))); const x45 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[9]) * 0x26))); const x46 = (cast(u64, (arg1[9])) * cast(u64, (arg2[0]))); const x47 = (cast(u64, (arg1[8])) * cast(u64, (arg2[1]))); const x48 = (cast(u64, (arg1[8])) * cast(u64, (arg2[0]))); const x49 = (cast(u64, (arg1[7])) * cast(u64, (arg2[2]))); const x50 = (cast(u64, (arg1[7])) * cast(u64, ((arg2[1]) * 0x2))); const x51 = (cast(u64, (arg1[7])) * cast(u64, (arg2[0]))); const x52 = (cast(u64, (arg1[6])) * cast(u64, (arg2[3]))); const x53 = (cast(u64, (arg1[6])) * cast(u64, (arg2[2]))); const x54 = (cast(u64, (arg1[6])) * cast(u64, (arg2[1]))); const x55 = (cast(u64, (arg1[6])) * cast(u64, (arg2[0]))); const x56 = (cast(u64, (arg1[5])) * cast(u64, (arg2[4]))); const x57 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[3]) * 0x2))); const x58 = (cast(u64, (arg1[5])) * cast(u64, (arg2[2]))); const x59 = (cast(u64, (arg1[5])) * cast(u64, ((arg2[1]) * 0x2))); const x60 = (cast(u64, (arg1[5])) * cast(u64, (arg2[0]))); const x61 = (cast(u64, (arg1[4])) * cast(u64, (arg2[5]))); const x62 = (cast(u64, (arg1[4])) * cast(u64, (arg2[4]))); const x63 = (cast(u64, (arg1[4])) * cast(u64, (arg2[3]))); const x64 = (cast(u64, (arg1[4])) * cast(u64, (arg2[2]))); const x65 = (cast(u64, (arg1[4])) * cast(u64, (arg2[1]))); const x66 = (cast(u64, (arg1[4])) * cast(u64, (arg2[0]))); const x67 = (cast(u64, (arg1[3])) * cast(u64, (arg2[6]))); const x68 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[5]) * 0x2))); const x69 = (cast(u64, (arg1[3])) * cast(u64, (arg2[4]))); const x70 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[3]) * 0x2))); const x71 = (cast(u64, (arg1[3])) * cast(u64, (arg2[2]))); const x72 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[1]) * 0x2))); const x73 = (cast(u64, (arg1[3])) * cast(u64, (arg2[0]))); const x74 = (cast(u64, (arg1[2])) * cast(u64, (arg2[7]))); const x75 = (cast(u64, (arg1[2])) * cast(u64, (arg2[6]))); const x76 = (cast(u64, (arg1[2])) * cast(u64, (arg2[5]))); const x77 = (cast(u64, (arg1[2])) * cast(u64, (arg2[4]))); const x78 = (cast(u64, (arg1[2])) * cast(u64, (arg2[3]))); const x79 = (cast(u64, (arg1[2])) * cast(u64, (arg2[2]))); const x80 = (cast(u64, (arg1[2])) * cast(u64, (arg2[1]))); const x81 = (cast(u64, (arg1[2])) * cast(u64, (arg2[0]))); const x82 = (cast(u64, (arg1[1])) * cast(u64, (arg2[8]))); const x83 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[7]) * 0x2))); const x84 = (cast(u64, (arg1[1])) * cast(u64, (arg2[6]))); const x85 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[5]) * 0x2))); const x86 = (cast(u64, (arg1[1])) * cast(u64, (arg2[4]))); const x87 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[3]) * 0x2))); const x88 = (cast(u64, (arg1[1])) * cast(u64, (arg2[2]))); const x89 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[1]) * 0x2))); const x90 = (cast(u64, (arg1[1])) * cast(u64, (arg2[0]))); const x91 = (cast(u64, (arg1[0])) * cast(u64, (arg2[9]))); const x92 = (cast(u64, (arg1[0])) * cast(u64, (arg2[8]))); const x93 = (cast(u64, (arg1[0])) * cast(u64, (arg2[7]))); const x94 = (cast(u64, (arg1[0])) * cast(u64, (arg2[6]))); const x95 = (cast(u64, (arg1[0])) * cast(u64, (arg2[5]))); const x96 = (cast(u64, (arg1[0])) * cast(u64, (arg2[4]))); const x97 = (cast(u64, (arg1[0])) * cast(u64, (arg2[3]))); const x98 = (cast(u64, (arg1[0])) * cast(u64, (arg2[2]))); const x99 = (cast(u64, (arg1[0])) * cast(u64, (arg2[1]))); const x100 = (cast(u64, (arg1[0])) * cast(u64, (arg2[0]))); const x101 = (x100 + (x45 + (x44 + (x42 + (x39 + (x35 + (x30 + (x24 + (x17 + x9))))))))); const x102 = (x101 >> 26); const x103 = cast(u32, (x101 & cast(u64, 0x3ffffff))); const x104 = (x91 + (x82 + (x74 + (x67 + (x61 + (x56 + (x52 + (x49 + (x47 + x46))))))))); const x105 = (x92 + (x83 + (x75 + (x68 + (x62 + (x57 + (x53 + (x50 + (x48 + x1))))))))); const x106 = (x93 + (x84 + (x76 + (x69 + (x63 + (x58 + (x54 + (x51 + (x10 + x2))))))))); const x107 = (x94 + (x85 + (x77 + (x70 + (x64 + (x59 + (x55 + (x18 + (x11 + x3))))))))); const x108 = (x95 + (x86 + (x78 + (x71 + (x65 + (x60 + (x25 + (x19 + (x12 + x4))))))))); const x109 = (x96 + (x87 + (x79 + (x72 + (x66 + (x31 + (x26 + (x20 + (x13 + x5))))))))); const x110 = (x97 + (x88 + (x80 + (x73 + (x36 + (x32 + (x27 + (x21 + (x14 + x6))))))))); const x111 = (x98 + (x89 + (x81 + (x40 + (x37 + (x33 + (x28 + (x22 + (x15 + x7))))))))); const x112 = (x99 + (x90 + (x43 + (x41 + (x38 + (x34 + (x29 + (x23 + (x16 + x8))))))))); const x113 = (x102 + x112); const x114 = (x113 >> 25); const x115 = cast(u32, (x113 & cast(u64, 0x1ffffff))); const x116 = (x114 + x111); const x117 = (x116 >> 26); const x118 = cast(u32, (x116 & cast(u64, 0x3ffffff))); const x119 = (x117 + x110); const x120 = (x119 >> 25); const x121 = cast(u32, (x119 & cast(u64, 0x1ffffff))); const x122 = (x120 + x109); const x123 = (x122 >> 26); const x124 = cast(u32, (x122 & cast(u64, 0x3ffffff))); const x125 = (x123 + x108); const x126 = (x125 >> 25); const x127 = cast(u32, (x125 & cast(u64, 0x1ffffff))); const x128 = (x126 + x107); const x129 = (x128 >> 26); const x130 = cast(u32, (x128 & cast(u64, 0x3ffffff))); const x131 = (x129 + x106); const x132 = (x131 >> 25); const x133 = cast(u32, (x131 & cast(u64, 0x1ffffff))); const x134 = (x132 + x105); const x135 = (x134 >> 26); const x136 = cast(u32, (x134 & cast(u64, 0x3ffffff))); const x137 = (x135 + x104); const x138 = (x137 >> 25); const x139 = cast(u32, (x137 & cast(u64, 0x1ffffff))); const x140 = (x138 * cast(u64, 0x13)); const x141 = (cast(u64, x103) + x140); const x142 = cast(u32, (x141 >> 26)); const x143 = cast(u32, (x141 & cast(u64, 0x3ffffff))); const x144 = (x142 + x115); const x145 = cast(u1, (x144 >> 25)); const x146 = (x144 & 0x1ffffff); const x147 = (cast(u32, x145) + x118); out1[0] = x143; out1[1] = x146; out1[2] = x147; out1[3] = x121; out1[4] = x124; out1[5] = x127; out1[6] = x130; out1[7] = x133; out1[8] = x136; out1[9] = x139; } /// The function carrySquare squares a field element and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg1) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] pub fn carrySquare(out1: *[10]u32, arg1: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[9]) * 0x13); const x2 = (x1 * 0x2); const x3 = ((arg1[9]) * 0x2); const x4 = ((arg1[8]) * 0x13); const x5 = (cast(u64, x4) * cast(u64, 0x2)); const x6 = ((arg1[8]) * 0x2); const x7 = ((arg1[7]) * 0x13); const x8 = (x7 * 0x2); const x9 = ((arg1[7]) * 0x2); const x10 = ((arg1[6]) * 0x13); const x11 = (cast(u64, x10) * cast(u64, 0x2)); const x12 = ((arg1[6]) * 0x2); const x13 = ((arg1[5]) * 0x13); const x14 = ((arg1[5]) * 0x2); const x15 = ((arg1[4]) * 0x2); const x16 = ((arg1[3]) * 0x2); const x17 = ((arg1[2]) * 0x2); const x18 = ((arg1[1]) * 0x2); const x19 = (cast(u64, (arg1[9])) * cast(u64, (x1 * 0x2))); const x20 = (cast(u64, (arg1[8])) * cast(u64, x2)); const x21 = (cast(u64, (arg1[8])) * cast(u64, x4)); const x22 = (cast(u64, (arg1[7])) * (cast(u64, x2) * cast(u64, 0x2))); const x23 = (cast(u64, (arg1[7])) * x5); const x24 = (cast(u64, (arg1[7])) * cast(u64, (x7 * 0x2))); const x25 = (cast(u64, (arg1[6])) * cast(u64, x2)); const x26 = (cast(u64, (arg1[6])) * x5); const x27 = (cast(u64, (arg1[6])) * cast(u64, x8)); const x28 = (cast(u64, (arg1[6])) * cast(u64, x10)); const x29 = (cast(u64, (arg1[5])) * (cast(u64, x2) * cast(u64, 0x2))); const x30 = (cast(u64, (arg1[5])) * x5); const x31 = (cast(u64, (arg1[5])) * (cast(u64, x8) * cast(u64, 0x2))); const x32 = (cast(u64, (arg1[5])) * x11); const x33 = (cast(u64, (arg1[5])) * cast(u64, (x13 * 0x2))); const x34 = (cast(u64, (arg1[4])) * cast(u64, x2)); const x35 = (cast(u64, (arg1[4])) * x5); const x36 = (cast(u64, (arg1[4])) * cast(u64, x8)); const x37 = (cast(u64, (arg1[4])) * x11); const x38 = (cast(u64, (arg1[4])) * cast(u64, x14)); const x39 = (cast(u64, (arg1[4])) * cast(u64, (arg1[4]))); const x40 = (cast(u64, (arg1[3])) * (cast(u64, x2) * cast(u64, 0x2))); const x41 = (cast(u64, (arg1[3])) * x5); const x42 = (cast(u64, (arg1[3])) * (cast(u64, x8) * cast(u64, 0x2))); const x43 = (cast(u64, (arg1[3])) * cast(u64, x12)); const x44 = (cast(u64, (arg1[3])) * cast(u64, (x14 * 0x2))); const x45 = (cast(u64, (arg1[3])) * cast(u64, x15)); const x46 = (cast(u64, (arg1[3])) * cast(u64, ((arg1[3]) * 0x2))); const x47 = (cast(u64, (arg1[2])) * cast(u64, x2)); const x48 = (cast(u64, (arg1[2])) * x5); const x49 = (cast(u64, (arg1[2])) * cast(u64, x9)); const x50 = (cast(u64, (arg1[2])) * cast(u64, x12)); const x51 = (cast(u64, (arg1[2])) * cast(u64, x14)); const x52 = (cast(u64, (arg1[2])) * cast(u64, x15)); const x53 = (cast(u64, (arg1[2])) * cast(u64, x16)); const x54 = (cast(u64, (arg1[2])) * cast(u64, (arg1[2]))); const x55 = (cast(u64, (arg1[1])) * (cast(u64, x2) * cast(u64, 0x2))); const x56 = (cast(u64, (arg1[1])) * cast(u64, x6)); const x57 = (cast(u64, (arg1[1])) * cast(u64, (x9 * 0x2))); const x58 = (cast(u64, (arg1[1])) * cast(u64, x12)); const x59 = (cast(u64, (arg1[1])) * cast(u64, (x14 * 0x2))); const x60 = (cast(u64, (arg1[1])) * cast(u64, x15)); const x61 = (cast(u64, (arg1[1])) * cast(u64, (x16 * 0x2))); const x62 = (cast(u64, (arg1[1])) * cast(u64, x17)); const x63 = (cast(u64, (arg1[1])) * cast(u64, ((arg1[1]) * 0x2))); const x64 = (cast(u64, (arg1[0])) * cast(u64, x3)); const x65 = (cast(u64, (arg1[0])) * cast(u64, x6)); const x66 = (cast(u64, (arg1[0])) * cast(u64, x9)); const x67 = (cast(u64, (arg1[0])) * cast(u64, x12)); const x68 = (cast(u64, (arg1[0])) * cast(u64, x14)); const x69 = (cast(u64, (arg1[0])) * cast(u64, x15)); const x70 = (cast(u64, (arg1[0])) * cast(u64, x16)); const x71 = (cast(u64, (arg1[0])) * cast(u64, x17)); const x72 = (cast(u64, (arg1[0])) * cast(u64, x18)); const x73 = (cast(u64, (arg1[0])) * cast(u64, (arg1[0]))); const x74 = (x73 + (x55 + (x48 + (x42 + (x37 + x33))))); const x75 = (x74 >> 26); const x76 = cast(u32, (x74 & cast(u64, 0x3ffffff))); const x77 = (x64 + (x56 + (x49 + (x43 + x38)))); const x78 = (x65 + (x57 + (x50 + (x44 + (x39 + x19))))); const x79 = (x66 + (x58 + (x51 + (x45 + x20)))); const x80 = (x67 + (x59 + (x52 + (x46 + (x22 + x21))))); const x81 = (x68 + (x60 + (x53 + (x25 + x23)))); const x82 = (x69 + (x61 + (x54 + (x29 + (x26 + x24))))); const x83 = (x70 + (x62 + (x34 + (x30 + x27)))); const x84 = (x71 + (x63 + (x40 + (x35 + (x31 + x28))))); const x85 = (x72 + (x47 + (x41 + (x36 + x32)))); const x86 = (x75 + x85); const x87 = (x86 >> 25); const x88 = cast(u32, (x86 & cast(u64, 0x1ffffff))); const x89 = (x87 + x84); const x90 = (x89 >> 26); const x91 = cast(u32, (x89 & cast(u64, 0x3ffffff))); const x92 = (x90 + x83); const x93 = (x92 >> 25); const x94 = cast(u32, (x92 & cast(u64, 0x1ffffff))); const x95 = (x93 + x82); const x96 = (x95 >> 26); const x97 = cast(u32, (x95 & cast(u64, 0x3ffffff))); const x98 = (x96 + x81); const x99 = (x98 >> 25); const x100 = cast(u32, (x98 & cast(u64, 0x1ffffff))); const x101 = (x99 + x80); const x102 = (x101 >> 26); const x103 = cast(u32, (x101 & cast(u64, 0x3ffffff))); const x104 = (x102 + x79); const x105 = (x104 >> 25); const x106 = cast(u32, (x104 & cast(u64, 0x1ffffff))); const x107 = (x105 + x78); const x108 = (x107 >> 26); const x109 = cast(u32, (x107 & cast(u64, 0x3ffffff))); const x110 = (x108 + x77); const x111 = (x110 >> 25); const x112 = cast(u32, (x110 & cast(u64, 0x1ffffff))); const x113 = (x111 * cast(u64, 0x13)); const x114 = (cast(u64, x76) + x113); const x115 = cast(u32, (x114 >> 26)); const x116 = cast(u32, (x114 & cast(u64, 0x3ffffff))); const x117 = (x115 + x88); const x118 = cast(u1, (x117 >> 25)); const x119 = (x117 & 0x1ffffff); const x120 = (cast(u32, x118) + x91); out1[0] = x116; out1[1] = x119; out1[2] = x120; out1[3] = x94; out1[4] = x97; out1[5] = x100; out1[6] = x103; out1[7] = x106; out1[8] = x109; out1[9] = x112; } /// The function carry reduces a field element. /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] pub fn carry(out1: *[10]u32, arg1: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = ((x1 >> 26) + (arg1[1])); const x3 = ((x2 >> 25) + (arg1[2])); const x4 = ((x3 >> 26) + (arg1[3])); const x5 = ((x4 >> 25) + (arg1[4])); const x6 = ((x5 >> 26) + (arg1[5])); const x7 = ((x6 >> 25) + (arg1[6])); const x8 = ((x7 >> 26) + (arg1[7])); const x9 = ((x8 >> 25) + (arg1[8])); const x10 = ((x9 >> 26) + (arg1[9])); const x11 = ((x1 & 0x3ffffff) + ((x10 >> 25) * 0x13)); const x12 = (cast(u32, cast(u1, (x11 >> 26))) + (x2 & 0x1ffffff)); const x13 = (x11 & 0x3ffffff); const x14 = (x12 & 0x1ffffff); const x15 = (cast(u32, cast(u1, (x12 >> 25))) + (x3 & 0x3ffffff)); const x16 = (x4 & 0x1ffffff); const x17 = (x5 & 0x3ffffff); const x18 = (x6 & 0x1ffffff); const x19 = (x7 & 0x3ffffff); const x20 = (x8 & 0x1ffffff); const x21 = (x9 & 0x3ffffff); const x22 = (x10 & 0x1ffffff); out1[0] = x13; out1[1] = x14; out1[2] = x15; out1[3] = x16; out1[4] = x17; out1[5] = x18; out1[6] = x19; out1[7] = x20; out1[8] = x21; out1[9] = x22; } /// The function add adds two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// arg2: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] pub fn add(out1: *[10]u32, arg1: [10]u32, arg2: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) + (arg2[0])); const x2 = ((arg1[1]) + (arg2[1])); const x3 = ((arg1[2]) + (arg2[2])); const x4 = ((arg1[3]) + (arg2[3])); const x5 = ((arg1[4]) + (arg2[4])); const x6 = ((arg1[5]) + (arg2[5])); const x7 = ((arg1[6]) + (arg2[6])); const x8 = ((arg1[7]) + (arg2[7])); const x9 = ((arg1[8]) + (arg2[8])); const x10 = ((arg1[9]) + (arg2[9])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; } /// The function sub subtracts two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// arg2: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] pub fn sub(out1: *[10]u32, arg1: [10]u32, arg2: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = ((0x7ffffda + (arg1[0])) - (arg2[0])); const x2 = ((0x3fffffe + (arg1[1])) - (arg2[1])); const x3 = ((0x7fffffe + (arg1[2])) - (arg2[2])); const x4 = ((0x3fffffe + (arg1[3])) - (arg2[3])); const x5 = ((0x7fffffe + (arg1[4])) - (arg2[4])); const x6 = ((0x3fffffe + (arg1[5])) - (arg2[5])); const x7 = ((0x7fffffe + (arg1[6])) - (arg2[6])); const x8 = ((0x3fffffe + (arg1[7])) - (arg2[7])); const x9 = ((0x7fffffe + (arg1[8])) - (arg2[8])); const x10 = ((0x3fffffe + (arg1[9])) - (arg2[9])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; } /// The function opp negates a field element. /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] pub fn opp(out1: *[10]u32, arg1: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = (0x7ffffda - (arg1[0])); const x2 = (0x3fffffe - (arg1[1])); const x3 = (0x7fffffe - (arg1[2])); const x4 = (0x3fffffe - (arg1[3])); const x5 = (0x7fffffe - (arg1[4])); const x6 = (0x3fffffe - (arg1[5])); const x7 = (0x7fffffe - (arg1[6])); const x8 = (0x3fffffe - (arg1[7])); const x9 = (0x7fffffe - (arg1[8])); const x10 = (0x3fffffe - (arg1[9])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; } /// The function selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn selectznz(out1: *[10]u32, arg1: u1, arg2: [10]u32, arg3: [10]u32) void { @setRuntimeSafety(mode == .Debug); var x1: u32 = undefined; cmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; cmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; cmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; cmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; cmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); var x6: u32 = undefined; cmovznzU32(&x6, arg1, (arg2[5]), (arg3[5])); var x7: u32 = undefined; cmovznzU32(&x7, arg1, (arg2[6]), (arg3[6])); var x8: u32 = undefined; cmovznzU32(&x8, arg1, (arg2[7]), (arg3[7])); var x9: u32 = undefined; cmovznzU32(&x9, arg1, (arg2[8]), (arg3[8])); var x10: u32 = undefined; cmovznzU32(&x10, arg1, (arg2[9]), (arg3[9])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; } /// The function toBytes serializes a field element to bytes in little-endian order. /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] pub fn toBytes(out1: *[32]u8, arg1: [10]u32) void { @setRuntimeSafety(mode == .Debug); var x1: u32 = undefined; var x2: u1 = undefined; subborrowxU26(&x1, &x2, 0x0, (arg1[0]), 0x3ffffed); var x3: u32 = undefined; var x4: u1 = undefined; subborrowxU25(&x3, &x4, x2, (arg1[1]), 0x1ffffff); var x5: u32 = undefined; var x6: u1 = undefined; subborrowxU26(&x5, &x6, x4, (arg1[2]), 0x3ffffff); var x7: u32 = undefined; var x8: u1 = undefined; subborrowxU25(&x7, &x8, x6, (arg1[3]), 0x1ffffff); var x9: u32 = undefined; var x10: u1 = undefined; subborrowxU26(&x9, &x10, x8, (arg1[4]), 0x3ffffff); var x11: u32 = undefined; var x12: u1 = undefined; subborrowxU25(&x11, &x12, x10, (arg1[5]), 0x1ffffff); var x13: u32 = undefined; var x14: u1 = undefined; subborrowxU26(&x13, &x14, x12, (arg1[6]), 0x3ffffff); var x15: u32 = undefined; var x16: u1 = undefined; subborrowxU25(&x15, &x16, x14, (arg1[7]), 0x1ffffff); var x17: u32 = undefined; var x18: u1 = undefined; subborrowxU26(&x17, &x18, x16, (arg1[8]), 0x3ffffff); var x19: u32 = undefined; var x20: u1 = undefined; subborrowxU25(&x19, &x20, x18, (arg1[9]), 0x1ffffff); var x21: u32 = undefined; cmovznzU32(&x21, x20, cast(u32, 0x0), 0xffffffff); var x22: u32 = undefined; var x23: u1 = undefined; addcarryxU26(&x22, &x23, 0x0, x1, (x21 & 0x3ffffed)); var x24: u32 = undefined; var x25: u1 = undefined; addcarryxU25(&x24, &x25, x23, x3, (x21 & 0x1ffffff)); var x26: u32 = undefined; var x27: u1 = undefined; addcarryxU26(&x26, &x27, x25, x5, (x21 & 0x3ffffff)); var x28: u32 = undefined; var x29: u1 = undefined; addcarryxU25(&x28, &x29, x27, x7, (x21 & 0x1ffffff)); var x30: u32 = undefined; var x31: u1 = undefined; addcarryxU26(&x30, &x31, x29, x9, (x21 & 0x3ffffff)); var x32: u32 = undefined; var x33: u1 = undefined; addcarryxU25(&x32, &x33, x31, x11, (x21 & 0x1ffffff)); var x34: u32 = undefined; var x35: u1 = undefined; addcarryxU26(&x34, &x35, x33, x13, (x21 & 0x3ffffff)); var x36: u32 = undefined; var x37: u1 = undefined; addcarryxU25(&x36, &x37, x35, x15, (x21 & 0x1ffffff)); var x38: u32 = undefined; var x39: u1 = undefined; addcarryxU26(&x38, &x39, x37, x17, (x21 & 0x3ffffff)); var x40: u32 = undefined; var x41: u1 = undefined; addcarryxU25(&x40, &x41, x39, x19, (x21 & 0x1ffffff)); const x42 = (x40 << 6); const x43 = (x38 << 4); const x44 = (x36 << 3); const x45 = (x34 * cast(u32, 0x2)); const x46 = (x30 << 6); const x47 = (x28 << 5); const x48 = (x26 << 3); const x49 = (x24 << 2); const x50 = cast(u8, (x22 & cast(u32, 0xff))); const x51 = (x22 >> 8); const x52 = cast(u8, (x51 & cast(u32, 0xff))); const x53 = (x51 >> 8); const x54 = cast(u8, (x53 & cast(u32, 0xff))); const x55 = cast(u8, (x53 >> 8)); const x56 = (x49 + cast(u32, x55)); const x57 = cast(u8, (x56 & cast(u32, 0xff))); const x58 = (x56 >> 8); const x59 = cast(u8, (x58 & cast(u32, 0xff))); const x60 = (x58 >> 8); const x61 = cast(u8, (x60 & cast(u32, 0xff))); const x62 = cast(u8, (x60 >> 8)); const x63 = (x48 + cast(u32, x62)); const x64 = cast(u8, (x63 & cast(u32, 0xff))); const x65 = (x63 >> 8); const x66 = cast(u8, (x65 & cast(u32, 0xff))); const x67 = (x65 >> 8); const x68 = cast(u8, (x67 & cast(u32, 0xff))); const x69 = cast(u8, (x67 >> 8)); const x70 = (x47 + cast(u32, x69)); const x71 = cast(u8, (x70 & cast(u32, 0xff))); const x72 = (x70 >> 8); const x73 = cast(u8, (x72 & cast(u32, 0xff))); const x74 = (x72 >> 8); const x75 = cast(u8, (x74 & cast(u32, 0xff))); const x76 = cast(u8, (x74 >> 8)); const x77 = (x46 + cast(u32, x76)); const x78 = cast(u8, (x77 & cast(u32, 0xff))); const x79 = (x77 >> 8); const x80 = cast(u8, (x79 & cast(u32, 0xff))); const x81 = (x79 >> 8); const x82 = cast(u8, (x81 & cast(u32, 0xff))); const x83 = cast(u8, (x81 >> 8)); const x84 = cast(u8, (x32 & cast(u32, 0xff))); const x85 = (x32 >> 8); const x86 = cast(u8, (x85 & cast(u32, 0xff))); const x87 = (x85 >> 8); const x88 = cast(u8, (x87 & cast(u32, 0xff))); const x89 = cast(u1, (x87 >> 8)); const x90 = (x45 + cast(u32, x89)); const x91 = cast(u8, (x90 & cast(u32, 0xff))); const x92 = (x90 >> 8); const x93 = cast(u8, (x92 & cast(u32, 0xff))); const x94 = (x92 >> 8); const x95 = cast(u8, (x94 & cast(u32, 0xff))); const x96 = cast(u8, (x94 >> 8)); const x97 = (x44 + cast(u32, x96)); const x98 = cast(u8, (x97 & cast(u32, 0xff))); const x99 = (x97 >> 8); const x100 = cast(u8, (x99 & cast(u32, 0xff))); const x101 = (x99 >> 8); const x102 = cast(u8, (x101 & cast(u32, 0xff))); const x103 = cast(u8, (x101 >> 8)); const x104 = (x43 + cast(u32, x103)); const x105 = cast(u8, (x104 & cast(u32, 0xff))); const x106 = (x104 >> 8); const x107 = cast(u8, (x106 & cast(u32, 0xff))); const x108 = (x106 >> 8); const x109 = cast(u8, (x108 & cast(u32, 0xff))); const x110 = cast(u8, (x108 >> 8)); const x111 = (x42 + cast(u32, x110)); const x112 = cast(u8, (x111 & cast(u32, 0xff))); const x113 = (x111 >> 8); const x114 = cast(u8, (x113 & cast(u32, 0xff))); const x115 = (x113 >> 8); const x116 = cast(u8, (x115 & cast(u32, 0xff))); const x117 = cast(u8, (x115 >> 8)); out1[0] = x50; out1[1] = x52; out1[2] = x54; out1[3] = x57; out1[4] = x59; out1[5] = x61; out1[6] = x64; out1[7] = x66; out1[8] = x68; out1[9] = x71; out1[10] = x73; out1[11] = x75; out1[12] = x78; out1[13] = x80; out1[14] = x82; out1[15] = x83; out1[16] = x84; out1[17] = x86; out1[18] = x88; out1[19] = x91; out1[20] = x93; out1[21] = x95; out1[22] = x98; out1[23] = x100; out1[24] = x102; out1[25] = x105; out1[26] = x107; out1[27] = x109; out1[28] = x112; out1[29] = x114; out1[30] = x116; out1[31] = x117; } /// The function fromBytes deserializes a field element from bytes in little-endian order. /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] pub fn fromBytes(out1: *[10]u32, arg1: [32]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u32, (arg1[31])) << 18); const x2 = (cast(u32, (arg1[30])) << 10); const x3 = (cast(u32, (arg1[29])) << 2); const x4 = (cast(u32, (arg1[28])) << 20); const x5 = (cast(u32, (arg1[27])) << 12); const x6 = (cast(u32, (arg1[26])) << 4); const x7 = (cast(u32, (arg1[25])) << 21); const x8 = (cast(u32, (arg1[24])) << 13); const x9 = (cast(u32, (arg1[23])) << 5); const x10 = (cast(u32, (arg1[22])) << 23); const x11 = (cast(u32, (arg1[21])) << 15); const x12 = (cast(u32, (arg1[20])) << 7); const x13 = (cast(u32, (arg1[19])) << 24); const x14 = (cast(u32, (arg1[18])) << 16); const x15 = (cast(u32, (arg1[17])) << 8); const x16 = (arg1[16]); const x17 = (cast(u32, (arg1[15])) << 18); const x18 = (cast(u32, (arg1[14])) << 10); const x19 = (cast(u32, (arg1[13])) << 2); const x20 = (cast(u32, (arg1[12])) << 19); const x21 = (cast(u32, (arg1[11])) << 11); const x22 = (cast(u32, (arg1[10])) << 3); const x23 = (cast(u32, (arg1[9])) << 21); const x24 = (cast(u32, (arg1[8])) << 13); const x25 = (cast(u32, (arg1[7])) << 5); const x26 = (cast(u32, (arg1[6])) << 22); const x27 = (cast(u32, (arg1[5])) << 14); const x28 = (cast(u32, (arg1[4])) << 6); const x29 = (cast(u32, (arg1[3])) << 24); const x30 = (cast(u32, (arg1[2])) << 16); const x31 = (cast(u32, (arg1[1])) << 8); const x32 = (arg1[0]); const x33 = (x31 + cast(u32, x32)); const x34 = (x30 + x33); const x35 = (x29 + x34); const x36 = (x35 & 0x3ffffff); const x37 = cast(u8, (x35 >> 26)); const x38 = (x28 + cast(u32, x37)); const x39 = (x27 + x38); const x40 = (x26 + x39); const x41 = (x40 & 0x1ffffff); const x42 = cast(u8, (x40 >> 25)); const x43 = (x25 + cast(u32, x42)); const x44 = (x24 + x43); const x45 = (x23 + x44); const x46 = (x45 & 0x3ffffff); const x47 = cast(u8, (x45 >> 26)); const x48 = (x22 + cast(u32, x47)); const x49 = (x21 + x48); const x50 = (x20 + x49); const x51 = (x50 & 0x1ffffff); const x52 = cast(u8, (x50 >> 25)); const x53 = (x19 + cast(u32, x52)); const x54 = (x18 + x53); const x55 = (x17 + x54); const x56 = (x15 + cast(u32, x16)); const x57 = (x14 + x56); const x58 = (x13 + x57); const x59 = (x58 & 0x1ffffff); const x60 = cast(u8, (x58 >> 25)); const x61 = (x12 + cast(u32, x60)); const x62 = (x11 + x61); const x63 = (x10 + x62); const x64 = (x63 & 0x3ffffff); const x65 = cast(u8, (x63 >> 26)); const x66 = (x9 + cast(u32, x65)); const x67 = (x8 + x66); const x68 = (x7 + x67); const x69 = (x68 & 0x1ffffff); const x70 = cast(u8, (x68 >> 25)); const x71 = (x6 + cast(u32, x70)); const x72 = (x5 + x71); const x73 = (x4 + x72); const x74 = (x73 & 0x3ffffff); const x75 = cast(u8, (x73 >> 26)); const x76 = (x3 + cast(u32, x75)); const x77 = (x2 + x76); const x78 = (x1 + x77); out1[0] = x36; out1[1] = x41; out1[2] = x46; out1[3] = x51; out1[4] = x55; out1[5] = x59; out1[6] = x64; out1[7] = x69; out1[8] = x74; out1[9] = x78; } /// The function carryScmul121666 multiplies a field element by 121666 and reduces the result. /// Postconditions: /// eval out1 mod m = (121666 * eval arg1) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000], [0x0 ~> 0xc000000], [0x0 ~> 0x6000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000], [0x0 ~> 0x4000000], [0x0 ~> 0x2000000]] pub fn carryScmul121666(out1: *[10]u32, arg1: [10]u32) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, 0x1db42) * cast(u64, (arg1[9]))); const x2 = (cast(u64, 0x1db42) * cast(u64, (arg1[8]))); const x3 = (cast(u64, 0x1db42) * cast(u64, (arg1[7]))); const x4 = (cast(u64, 0x1db42) * cast(u64, (arg1[6]))); const x5 = (cast(u64, 0x1db42) * cast(u64, (arg1[5]))); const x6 = (cast(u64, 0x1db42) * cast(u64, (arg1[4]))); const x7 = (cast(u64, 0x1db42) * cast(u64, (arg1[3]))); const x8 = (cast(u64, 0x1db42) * cast(u64, (arg1[2]))); const x9 = (cast(u64, 0x1db42) * cast(u64, (arg1[1]))); const x10 = (cast(u64, 0x1db42) * cast(u64, (arg1[0]))); const x11 = cast(u32, (x10 >> 26)); const x12 = cast(u32, (x10 & cast(u64, 0x3ffffff))); const x13 = (cast(u64, x11) + x9); const x14 = cast(u32, (x13 >> 25)); const x15 = cast(u32, (x13 & cast(u64, 0x1ffffff))); const x16 = (cast(u64, x14) + x8); const x17 = cast(u32, (x16 >> 26)); const x18 = cast(u32, (x16 & cast(u64, 0x3ffffff))); const x19 = (cast(u64, x17) + x7); const x20 = cast(u32, (x19 >> 25)); const x21 = cast(u32, (x19 & cast(u64, 0x1ffffff))); const x22 = (cast(u64, x20) + x6); const x23 = cast(u32, (x22 >> 26)); const x24 = cast(u32, (x22 & cast(u64, 0x3ffffff))); const x25 = (cast(u64, x23) + x5); const x26 = cast(u32, (x25 >> 25)); const x27 = cast(u32, (x25 & cast(u64, 0x1ffffff))); const x28 = (cast(u64, x26) + x4); const x29 = cast(u32, (x28 >> 26)); const x30 = cast(u32, (x28 & cast(u64, 0x3ffffff))); const x31 = (cast(u64, x29) + x3); const x32 = cast(u32, (x31 >> 25)); const x33 = cast(u32, (x31 & cast(u64, 0x1ffffff))); const x34 = (cast(u64, x32) + x2); const x35 = cast(u32, (x34 >> 26)); const x36 = cast(u32, (x34 & cast(u64, 0x3ffffff))); const x37 = (cast(u64, x35) + x1); const x38 = cast(u32, (x37 >> 25)); const x39 = cast(u32, (x37 & cast(u64, 0x1ffffff))); const x40 = (x38 * 0x13); const x41 = (x12 + x40); const x42 = cast(u1, (x41 >> 26)); const x43 = (x41 & 0x3ffffff); const x44 = (cast(u32, x42) + x15); const x45 = cast(u1, (x44 >> 25)); const x46 = (x44 & 0x1ffffff); const x47 = (cast(u32, x45) + x18); out1[0] = x43; out1[1] = x46; out1[2] = x47; out1[3] = x21; out1[4] = x24; out1[5] = x27; out1[6] = x30; out1[7] = x33; out1[8] = x36; out1[9] = x39; }
fiat-zig/src/curve25519_32.zig
const std = @import("std"); const cli = @import("cli.zig"); var globalOT: ?std.os.termios = null; pub fn panic(msg: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn { const stdinF = std.io.getStdIn(); cli.stopCaptureMouse() catch {}; if (globalOT) |ot| cli.exitRawMode(stdinF, ot) catch {}; std.debug.warn("Panic: {}\n", .{msg}); if (stack_trace) |trace| std.debug.dumpStackTrace(trace.*); std.debug.warn("Consider posting a bug report: https://github.com/pfgithub/jsonexplorer/issues/new\n", .{}); std.os.exit(1); } pub fn main() !void { const stdinF = std.io.getStdIn(); const stdin = stdinF.reader(); const stdoutF = std.io.getStdOut(); const stdout = stdoutF.writer(); const ot = try cli.enterRawMode(stdinF); defer cli.exitRawMode(stdinF, ot) catch @panic("failed to exit"); globalOT = ot; var mouseMode = false; var eventMode = false; for (std.os.argv) |arg, i| { // can't do [1..] because #2622 if (i < 1) continue; std.debug.warn("ARG: {s}\n", .{arg}); if (std.mem.eql(u8, std.mem.span(arg), "--mouse")) { mouseMode = true; continue; } if (std.mem.eql(u8, std.mem.span(arg), "--event")) { eventMode = true; continue; } @panic("bad args"); } if (mouseMode) try cli.startCaptureMouse(); defer if (mouseMode) cli.stopCaptureMouse() catch @panic("failed to stop mouse capture"); try stdout.print("Escape sequence debug started. Window size is: {}\n", .{try cli.winSize(stdoutF)}); if (eventMode) { try cli.mainLoop(false, struct { pub fn f(data: anytype, ev: cli.Event) bool { const stdoutF2 = std.io.getStdOut(); const stdout2 = stdoutF2.writer(); stdout2.print("{}\n", .{ev}) catch return false; if (ev.is("ctrl+c")) { return false; } if (ev.is("ctrl+p")) @panic("panic test"); return true; } }.f, stdinF); return; } const escape_start = "\x1b[34m\\\x1b[94m"; const escape_end = "\x1b(B\x1b[m"; while (true) { const rb = try stdin.readByte(); switch (rb) { 3 => break, 32...126 => |c| try stdout.print("{c}", .{c}), '\t' => try stdout.print(escape_start ++ "t" ++ escape_end, .{}), '\r' => try stdout.print(escape_start ++ "r" ++ escape_end, .{}), '\n' => try stdout.print(escape_start ++ "n" ++ escape_end, .{}), else => |c| try stdout.print(escape_start ++ "x{x:0>2}" ++ escape_end, .{c}), } } }
src/escape_sequence_debug.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const window = @import("Window.zig"); const c = @import("c.zig").c; const expect = std.testing.expect; const image = @import("Image.zig"); const MinFilter = image.MinFilter; const image_type_base_internal_formats = image.image_type_base_internal_formats; const image_type_sized_internal_formats = image.image_type_sized_internal_formats; const ImageType = image.ImageType; const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter; // For each of the 6 sides (multiply return value by 6 to get total cubemap size) pub fn imageDataSize(size: u32, imgType: ImageType) u32 { var expectedDataSize: u32 = 0; if (imgType == ImageType.RGBA or imgType == ImageType.Depth32 or imgType == ImageType.Depth32F) { expectedDataSize = size * size * 4; } else if (imgType == ImageType.Depth24) { expectedDataSize = size * size * 3; } else if (imgType == ImageType.RG or imgType == ImageType.Depth16) { assert(size * 2 % 4 == 0); // Ensure rows are a multiple of 4 bytes expectedDataSize = size * size * 2; } else if (imgType == ImageType.R) { assert(size % 4 == 0); // Ensure rows are a multiple of 4 bytes expectedDataSize = size * size; } return expectedDataSize; } // Cubemaps are always square pub const CubeMap = struct { ref_count: ReferenceCounter = ReferenceCounter{}, // width and height in pixels size: u32, imageType: ImageType, id: u32, min_filter: MinFilter, pub fn init(smooth_when_magnified: bool, min_filter: MinFilter) !CubeMap { return CubeMap{ .size = 0, .imageType = ImageType.RGBA, .id = try image.createTexture(c.GL_TEXTURE_CUBE_MAP, smooth_when_magnified, min_filter), .min_filter = min_filter, }; } pub fn bindToUnit(self: CubeMap, unit: u32) !void { if (self.size == 0 or self.id == 0) { assert(false); return error.InvalidState; } if (unit >= window.maximumNumTextureImageUnits()) { return error.InvalidParameter; } c.glActiveTexture(c.GL_TEXTURE0 + unit); c.glBindTexture(c.GL_TEXTURE_CUBE_MAP, self.id); } pub fn bind(self: CubeMap) !void { try self.bindToUnit(0); } fn validateArraySize(data: ?[]const u8, expected: u32) !void { if (data != null) { if (data.?.len != expected) { assert(false); return error.InvalidParameter; } } } // If data is null then texture data will be uninitialised pub fn upload(self: *CubeMap, size: u32, imgType: ImageType, data_pos_x: ?[]const u8, data_neg_x: ?[]const u8, data_pos_y: ?[]const u8, data_neg_y: ?[]const u8, data_pos_z: ?[]const u8, data_neg_z: ?[]const u8) !void { if (size == 0 or size > window.maximumTextureSize()) { assert(false); return error.InvalidParameter; } const expectedDataSize = imageDataSize(size, imgType); try validateArraySize(data_pos_x, expectedDataSize); try validateArraySize(data_neg_x, expectedDataSize); try validateArraySize(data_pos_y, expectedDataSize); try validateArraySize(data_neg_y, expectedDataSize); try validateArraySize(data_pos_z, expectedDataSize); try validateArraySize(data_neg_z, expectedDataSize); self.size = size; self.imageType = imgType; var internalFormat: u32 = image_type_sized_internal_formats[@enumToInt(imgType)]; try self.bind(); var pos_x: [*c]const u8 = 0; var neg_x: [*c]const u8 = 0; var pos_y: [*c]const u8 = 0; var neg_y: [*c]const u8 = 0; var pos_z: [*c]const u8 = 0; var neg_z: [*c]const u8 = 0; if (data_pos_x != null) { pos_x = data_pos_x.?.ptr; } if (data_neg_x != null) { pos_x = data_neg_x.?.ptr; } if (data_pos_y != null) { pos_x = data_pos_y.?.ptr; } if (data_neg_y != null) { pos_x = data_neg_y.?.ptr; } if (data_pos_z != null) { pos_x = data_pos_x.?.ptr; } if (data_neg_z != null) { pos_x = data_neg_y.?.ptr; } c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, pos_x); c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, neg_x); c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, pos_y); c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, neg_y); c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, pos_z); c.glTexImage2D(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, @intCast(c_int, internalFormat), @intCast(c_int, size), @intCast(c_int, size), 0, image_type_base_internal_formats[@enumToInt(imgType)], c.GL_UNSIGNED_BYTE, neg_z); if (self.min_filter != MinFilter.Nearest and self.min_filter != MinFilter.Linear) { c.glGenerateMipmap(c.GL_TEXTURE_CUBE_MAP); } } pub fn download(self: *CubeMap, output_pos_x: []u8, output_neg_x: []u8, output_pos_y: []u8, output_neg_y: []u8, output_pos_z: []u8, output_neg_z: []u8) !void { const expectedDataSize = imageDataSize(self.size, self.imageType); try validateArraySize(output_pos_x, expectedDataSize); try validateArraySize(output_neg_x, expectedDataSize); try validateArraySize(output_pos_y, expectedDataSize); try validateArraySize(output_neg_y, expectedDataSize); try validateArraySize(output_pos_z, expectedDataSize); try validateArraySize(output_neg_z, expectedDataSize); try self.bind(); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_pos_x.ptr); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_neg_x.ptr); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_pos_y.ptr); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_neg_y.ptr); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_pos_z.ptr); c.glGetTexImage(c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, image_type_base_internal_formats[@enumToInt(self.imageType)], c.GL_UNSIGNED_BYTE, output_neg_z.ptr); } pub fn free(self: *CubeMap) void { if (self.id == 0) { assert(false); return; } self.ref_count.deinit(); c.glDeleteTextures(1, @ptrCast([*c]c_uint, &self.id)); } pub fn unbind(unit: u32) !void { if (unit > window.maximumNumTextureImageUnits()) { return error.InvalidParameter; } c.glActiveTexture(GL_TEXTURE0 + unit); c.glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } }; test "cubemap texture" { try window.createWindow(false, 200, 200, "test", true, 0); var texture: CubeMap = try CubeMap.init(false, MinFilter.Nearest); expect(texture.id > 0); const dataIn: []const u8 = &[4]u8{ 127, 127, 127, 127 }; try texture.upload(1, ImageType.RGBA, dataIn, null, null, null, null, null); expect(texture.size == 1); expect(texture.imageType == ImageType.RGBA); var data: [4]u8 = undefined; var data2: [4]u8 = undefined; var data3: [4]u8 = undefined; var data4: [4]u8 = undefined; var data5: [4]u8 = undefined; var data6: [4]u8 = undefined; try texture.download(&data, &data2, &data3, &data4, &data5, &data6); expect(mem.eql(u8, data[0..], dataIn)); try texture.bind(); try texture.bindToUnit(15); texture.free(); window.closeWindow(); }
src/WindowGraphicsInput/CubeMap.zig
usingnamespace @import("enum.zig"); usingnamespace @import("struct.zig"); usingnamespace @import("../../types.zig"); pub const IAsynchronous = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetDataSize: extern fn (*Interface) UINT, }; lpVtbl: *VTable, }; pub const IBlendState = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetDesc: extern fn (*Interface, *BlenDesc) void, }; lpVtbl: *VTable, }; pub const IBlendState1 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetDesc: extern fn (*Interface, *BlenDesc) void, GetDesc1: extern fn (*Interface, *BlenDesc1) void, }; lpVtbl: *VTable, }; pub const ICommandList = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetContextFlags: extern fn (*Interface) UINT, }; lpVtbl: *VTable, }; pub const ICounter = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetDataSize: extern fn (*Interface) UINT, GetDesc: extern fn (*Interface, *CounterDesc) void, }; lpVtbl: *VTable, }; pub const IDepthStencilState = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetDesc: extern fn (*Interface, *DepthStencilDesc) void, }; lpVtbl: *VTable, }; pub const IDevice = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, }; lpVtbl: *VTable, }; pub const IDevice1 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, CreateBlendState1: extern fn (*Interface, *const BlendDesc1, **IBlendState1) HRESULT, CreateDeferredContext1: extern fn (*Interface, UINT, **IDeviceContext1) HRESULT, CreateDeviceContextState: extern fn (*Interface, UINT, [*]const FeatureLevel, UINT, UINT, *const GUID, *FeatureLevel, **IDeviceContextState) HRESULT, CreateRasterizerState1: extern fn (*Interface, *const RasterizerDesc1, **IRasterizerState1) HRESULT, GetImmediateContext1: extern fn (*Interface, **IDeviceContext1) void, OpenSharedResource1: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, OpenSharedResourceByName: extern fn (*Interface, LPCWSTR, DWORD, *const GUID, **IResource) HRESULT, }; lpVtbl: *VTable, }; pub const IDevice2 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, CreateBlendState1: extern fn (*Interface, *const BlendDesc1, **IBlendState1) HRESULT, CreateDeferredContext1: extern fn (*Interface, UINT, **IDeviceContext1) HRESULT, CreateDeviceContextState: extern fn (*Interface, UINT, [*]const FeatureLevel, UINT, UINT, *const GUID, *FeatureLevel, **IDeviceContextState) HRESULT, CreateRasterizerState1: extern fn (*Interface, *const RasterizerDesc1, **IRasterizerState1) HRESULT, GetImmediateContext1: extern fn (*Interface, **IDeviceContext1) void, OpenSharedResource1: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, OpenSharedResourceByName: extern fn (*Interface, LPCWSTR, DWORD, *const GUID, **IResource) HRESULT, CheckMultisampleQualityLevels1: extern fn (*Interface, DXGIFormat, UINT, UINT, *UINT) HRESULT, CreateDeferredContext2: extern fn (*Interface, UINT, **IDeviceContext2) HRESULT, GetImmediateContext2: extern fn (*Interface, **IDeviceContext2) HRESULT, GetResourceTiling: extern fn (*Interface, *IResource, *UINT, *PackedMipDesc, *TileShape, *UINT, UINT, *SubresourceTiling) void, }; lpVtbl: *VTable, }; pub const IDevice3 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, CreateBlendState1: extern fn (*Interface, *const BlendDesc1, **IBlendState1) HRESULT, CreateDeferredContext1: extern fn (*Interface, UINT, **IDeviceContext1) HRESULT, CreateDeviceContextState: extern fn (*Interface, UINT, [*]const FeatureLevel, UINT, UINT, *const GUID, *FeatureLevel, **IDeviceContextState) HRESULT, CreateRasterizerState1: extern fn (*Interface, *const RasterizerDesc1, **IRasterizerState1) HRESULT, GetImmediateContext1: extern fn (*Interface, **IDeviceContext1) void, OpenSharedResource1: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, OpenSharedResourceByName: extern fn (*Interface, LPCWSTR, DWORD, *const GUID, **IResource) HRESULT, CheckMultisampleQualityLevels1: extern fn (*Interface, DXGIFormat, UINT, UINT, *UINT) HRESULT, CreateDeferredContext2: extern fn (*Interface, UINT, **IDeviceContext2) HRESULT, GetImmediateContext2: extern fn (*Interface, **IDeviceContext2) HRESULT, GetResourceTiling: extern fn (*Interface, *IResource, *UINT, *PackedMipDesc, *TileShape, *UINT, UINT, *SubresourceTiling) void, CreateDeferredContext3: extern fn (*Interface, UINT, **IDeviceContext3) HRESULT, CreateQuery1: extern fn (*Interface, *const QueryDesc1, ?**IQuery) HRESULT, CreateRasterizerState2: extern fn (*Interface, *RasterizerDesc2, ?**IRasterizerState2) HRESULT, CreateRenderTargetView1: extern fn (*Interface, ?*const RenderTargetViewDesc1, ?**IRenderTargetView1) HRESULT, CreateShaderResourceView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IShaderResourceView1) HRESULT, CreateTexture2D1: extern fn (*Interface, *const Texture2DDesc1, ?*const SubresourceData, ?**ITexture2D1) HRESULT, CreateTexture3D1: extern fn (*Interface, *const Texture3DDesc1, ?*const SubresourceData, ?**ITexture3D1) HRESULT, CreateUnorderedAccessView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IUnorderedAccessView1) HRESULT, GetImmediateContext3: extern fn (*Interface, **IDeviceContext3) HRESULT, ReadFromSubresource: extern fn (*Interface, [*]BYTE, UINT, UINT, *IResource, UINT, *const Box) void, WriteToSubresource: extern fn (*Interface, *IResource, UINT, *const Box, [*]const BYTE, UINT, UINT) void, }; lpVtbl: *VTable, }; pub const IDevice4 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, CreateBlendState1: extern fn (*Interface, *const BlendDesc1, **IBlendState1) HRESULT, CreateDeferredContext1: extern fn (*Interface, UINT, **IDeviceContext1) HRESULT, CreateDeviceContextState: extern fn (*Interface, UINT, [*]const FeatureLevel, UINT, UINT, *const GUID, *FeatureLevel, **IDeviceContextState) HRESULT, CreateRasterizerState1: extern fn (*Interface, *const RasterizerDesc1, **IRasterizerState1) HRESULT, GetImmediateContext1: extern fn (*Interface, **IDeviceContext1) void, OpenSharedResource1: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, OpenSharedResourceByName: extern fn (*Interface, LPCWSTR, DWORD, *const GUID, **IResource) HRESULT, CheckMultisampleQualityLevels1: extern fn (*Interface, DXGIFormat, UINT, UINT, *UINT) HRESULT, CreateDeferredContext2: extern fn (*Interface, UINT, **IDeviceContext2) HRESULT, GetImmediateContext2: extern fn (*Interface, **IDeviceContext2) HRESULT, GetResourceTiling: extern fn (*Interface, *IResource, *UINT, *PackedMipDesc, *TileShape, *UINT, UINT, *SubresourceTiling) void, CreateDeferredContext3: extern fn (*Interface, UINT, **IDeviceContext3) HRESULT, CreateQuery1: extern fn (*Interface, *const QueryDesc1, ?**IQuery) HRESULT, CreateRasterizerState2: extern fn (*Interface, *RasterizerDesc2, ?**IRasterizerState2) HRESULT, CreateRenderTargetView1: extern fn (*Interface, ?*const RenderTargetViewDesc1, ?**IRenderTargetView1) HRESULT, CreateShaderResourceView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IShaderResourceView1) HRESULT, CreateTexture2D1: extern fn (*Interface, *const Texture2DDesc1, ?*const SubresourceData, ?**ITexture2D1) HRESULT, CreateTexture3D1: extern fn (*Interface, *const Texture3DDesc1, ?*const SubresourceData, ?**ITexture3D1) HRESULT, CreateUnorderedAccessView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IUnorderedAccessView1) HRESULT, GetImmediateContext3: extern fn (*Interface, **IDeviceContext3) HRESULT, ReadFromSubresource: extern fn (*Interface, [*]BYTE, UINT, UINT, *IResource, UINT, *const Box) void, WriteToSubresource: extern fn (*Interface, *IResource, UINT, *const Box, [*]const BYTE, UINT, UINT) void, RegisterDeviceRemovedEvent: extern fn (*Interface, HANDLE, *DWORD) HRESULT, UnregisterDeviceRemoved: extern fn (*Interface, DWORD) void, }; lpVtbl: *VTable, }; pub const IDevice5 = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, CreateBuffer: extern fn (*Interface, *const BufferDesc, ?*const SubresourceData, ?**IBuffer) HRESULT, CreateTexture1D: extern fn (*Interface, *const Texture1DDesc, ?*const SubresourceData, ?**ITexture1D) HRESULT, CreateTexture2D: extern fn (*Interface, *const Texture2DDesc, ?*const SubresourceData, ?**ITexture2D) HRESULT, CreateTexture3D: extern fn (*Interface, *const Texture3DDesc, ?*const SubresourceData, ?**ITexture3D) HRESULT, CreateShaderResourceView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IShaderResourceView) HRESULT, CreateUnorderedAccessView: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc, ?**IUnorderedAccessView) HRESULT, CreateRenderTargetView: extern fn (*Interface, *IResource, ?*const RenderTargetViewDesc, ?**IRenderTargetView) HRESULT, CreateDepthStencilView: extern fn (*Interface, *IResource, ?*const DepthStencilDesc, ?**IDepthStencilView) HRESULT, CreateInputLayout: extern fn (*Interface, *const InputElementDesc, UINT, [*]const BYTE, SIZE_T, ?**IInputLayout) HRESULT, CreateVertexShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IVertexShader) HRESULT, CreateGeometryShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreateGeometryShaderWithStreamOutput: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*const SODeclarationEntry, UINT, *const UINT, UINT, UINT, ?*IClassLinkage, ?**IGeometryShader) HRESULT, CreatePixelShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IPixelShader) HRESULT, CreateHullShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, **IHullShader) HRESULT, CreateDomainShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IDomainShader) HRESULT, CreateComputeShader: extern fn (*Interface, [*]const BYTE, SIZE_T, ?*IClassLinkage, ?**IComputeShader) HRESULT, CreateClassLinkage: extern fn (*Interface, **IClassLinkage) HRESULT, CreateBlendState: extern fn (*Interface, *const BlendDesc, **IBlendState) HRESULT, CreateDepthStencilState: extern fn (*Interface, *const DepthStencilDesc, **IDepthStencilState) HRESULT, CreateRasterizerState: extern fn (*Interface, *const RasterizerDesc, **IRasterizerState) HRESULT, CreateSamplerState: extern fn (*Interface, *const SamplerDesc, **ISamplerState) HRESULT, CreateQuery: extern fn (*Interface, *const QueryDesc, **IQuery) HRESULT, CreatePredicate: extern fn (*Interface, *const QueryDesc, **IPredicate) HRESULT, CreateCounter: extern fn (*Interface, *const CounterDesc, **ICounter) HRESULT, CreateDeferredContext: extern fn (*Interface, UINT, **InterfaceContext) HRESULT, OpenSharedResource: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, CheckFormatSupport: extern fn (*Interface, DXGIFormat, *UINT) HRESULT, CheckMultisampleQualityLevels: extern fn (*Interface, DXGIFormat, UINT, *UINT) HRESULT, CheckCounterInfo: extern fn (*Interface, *CounterInfo) void, CheckCounter: extern fn (*Interface, *const CounterDesc, *CounterType, *UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT, ?LPSTR, ?*UINT) HRESULT, CheckFeatureSupport: extern fn (*Interface, Feature, [*]BYTE, UINT) HRESULT, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, [*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, GetFeatureLevel: extern fn (*Interface) FeatureLevel, GetCreationFlags: extern fn (*Interface) UINT, GetDeviceRemovedReason: extern fn (*Interface) HRESULT, GetImmediateContext: extern fn (*Interface, **InterfaceContext) void, SetExceptionMode: extern fn (*Interface, UINT) HRESULT, GetExceptionMode: extern fn (*Interface) UINT, CreateBlendState1: extern fn (*Interface, *const BlendDesc1, **IBlendState1) HRESULT, CreateDeferredContext1: extern fn (*Interface, UINT, **IDeviceContext1) HRESULT, CreateDeviceContextState: extern fn (*Interface, UINT, [*]const FeatureLevel, UINT, UINT, *const GUID, *FeatureLevel, **IDeviceContextState) HRESULT, CreateRasterizerState1: extern fn (*Interface, *const RasterizerDesc1, **IRasterizerState1) HRESULT, GetImmediateContext1: extern fn (*Interface, **IDeviceContext1) void, OpenSharedResource1: extern fn (*Interface, HANDLE, *const GUID, **IResource) HRESULT, OpenSharedResourceByName: extern fn (*Interface, LPCWSTR, DWORD, *const GUID, **IResource) HRESULT, CheckMultisampleQualityLevels1: extern fn (*Interface, DXGIFormat, UINT, UINT, *UINT) HRESULT, CreateDeferredContext2: extern fn (*Interface, UINT, **IDeviceContext2) HRESULT, GetImmediateContext2: extern fn (*Interface, **IDeviceContext2) HRESULT, GetResourceTiling: extern fn (*Interface, *IResource, *UINT, *PackedMipDesc, *TileShape, *UINT, UINT, *SubresourceTiling) void, CreateDeferredContext3: extern fn (*Interface, UINT, **IDeviceContext3) HRESULT, CreateQuery1: extern fn (*Interface, *const QueryDesc1, ?**IQuery) HRESULT, CreateRasterizerState2: extern fn (*Interface, *RasterizerDesc2, ?**IRasterizerState2) HRESULT, CreateRenderTargetView1: extern fn (*Interface, ?*const RenderTargetViewDesc1, ?**IRenderTargetView1) HRESULT, CreateShaderResourceView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IShaderResourceView1) HRESULT, CreateTexture2D1: extern fn (*Interface, *const Texture2DDesc1, ?*const SubresourceData, ?**ITexture2D1) HRESULT, CreateTexture3D1: extern fn (*Interface, *const Texture3DDesc1, ?*const SubresourceData, ?**ITexture3D1) HRESULT, CreateUnorderedAccessView1: extern fn (*Interface, *IResource, ?*const ShaderResourceViewDesc1, ?**IUnorderedAccessView1) HRESULT, GetImmediateContext3: extern fn (*Interface, **IDeviceContext3) HRESULT, ReadFromSubresource: extern fn (*Interface, [*]BYTE, UINT, UINT, *IResource, UINT, *const Box) void, WriteToSubresource: extern fn (*Interface, *IResource, UINT, *const Box, [*]const BYTE, UINT, UINT) void, RegisterDeviceRemovedEvent: extern fn (*Interface, HANDLE, *DWORD) HRESULT, UnregisterDeviceRemoved: extern fn (*Interface, DWORD) void, CreateFence: extern fn (*Interface, UINT64, FenceFlag, *const GUID, **IFence) HRESULT, OpenSharedFence: extern fn (*Interface, HANDLE, *const GUID, **IFence) HRESULT, }; lpVtbl: *VTable, }; pub const IDeviceChild = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, GetDevice: extern fn (*Interface, **IDevice) void, GetPrivateData: extern fn (*Interface, *const GUID, *UINT, [*]BYTE) HRESULT, SetPrivateData: extern fn (*Interface, *const GUID, UINT, ?[*]const BYTE) HRESULT, SetPrivateDataInterface: extern fn (*Interface, *const GUID, *const IUnknown) HRESULT, }; lpVtbl: *VTable, }; pub const IUnknown = extern struct { const Interface = @This(); pub const VTable = extern struct { QueryInterface: extern fn (*Interface, *const GUID, *?*c_void) HRESULT, AddRef: extern fn (*Interface) ULONG, Release: extern fn (*Interface) ULONG, }; lpVtbl: *VTable, };
directx11/core/interface.zig
const std = @import("std"); const builtin = @import("builtin"); const debug = std.debug; const TypeInfo = builtin.TypeInfo; /// A function for populating vtables with their implementation. /// /// VTable is the vtables type. It has to be a struct, which has only function fields. /// It is also required that VTable contains a definition of Impl, which should be an /// OpaqueType. A pointer to this type denotes the 'self' parameter of each method. /// /// Functions is a namespace with all the functions that should populate the vtable. /// Functions can contain functions not in VTable. These will just be ignored. /// When populate populates the VTable with the functions from Functions, it does /// type checking to ensure that the population is safe. If VTable has a field of /// type 'fn(*Impl, u8) []u8', then populate will assert that Functions contain /// a function of the same name, with the type 'fn(*T, u8) []u8'. /// /// T is the self parameter of all the functions in Functions. /// /// The result will be a pointer to a global VTable that can be shared between all /// instantiations of T. pub fn populate(comptime VTable: type, comptime Functions: type, comptime T: type) *const VTable { const GlobalStorage = struct { const vtable = blk: { const Impl = VTable.Impl; var res: VTable = undefined; inline for (@typeInfo(VTable).Struct.fields) |field| { const Fn = @TypeOf(@field(res, field.name)); const Expect = @typeInfo(Fn).Fn; const Actual = @typeInfo(@TypeOf(@field(Functions, field.name))).Fn; debug.assert(!Expect.is_generic); debug.assert(!Expect.is_var_args); debug.assert(Expect.args.len > 0); debug.assert(Expect.calling_convention == Actual.calling_convention); debug.assert(Expect.is_generic == Actual.is_generic); debug.assert(Expect.is_var_args == Actual.is_var_args); debug.assert(Expect.return_type.? == Actual.return_type.?); debug.assert(Expect.args.len == Actual.args.len); for (Expect.args) |expect_arg, i| { const actual_arg = Actual.args[i]; debug.assert(!expect_arg.is_generic); debug.assert(expect_arg.is_generic == actual_arg.is_generic); debug.assert(expect_arg.is_noalias == actual_arg.is_noalias); // For the first arg. We enforce that it is a pointer, and // that the actual function takes *T. if (i == 0) { const expect_ptr = @typeInfo(expect_arg.arg_type.?).Pointer; const actual_ptr = @typeInfo(actual_arg.arg_type.?).Pointer; debug.assert(expect_ptr.size == TypeInfo.Pointer.Size.One); debug.assert(expect_ptr.size == actual_ptr.size); debug.assert(expect_ptr.is_const == actual_ptr.is_const); debug.assert(expect_ptr.is_volatile == actual_ptr.is_volatile); debug.assert(actual_ptr.child == T); debug.assert(expect_ptr.child == Impl); } else { debug.assert(expect_arg.arg_type.? == actual_arg.arg_type.?); } } @field(res, field.name) = @ptrCast(Fn, @field(T, field.name)); } break :blk res; }; }; return &GlobalStorage.vtable; }
src/vtable.zig
const std = @import("std"); const log = @import("log.zig"); const c = @cImport({ @cInclude("stdio.h"); }); const esp = @cImport({ @cInclude("sdkconfig.h"); @cInclude("esp_system.h"); @cInclude("led_strip.h"); }); const freertos = @cImport({ @cInclude("freertos/FreeRTOS.h"); @cInclude("freertos/task.h"); }); const BLINK_LED_RMT_CHANNEL = esp.CONFIG_BLINK_LED_RMT_CHANNEL; const BLINK_GPIO = esp.CONFIG_BLINK_GPIO; const LedStrip = struct { ptr: *esp.led_strip_t, const Self = @This(); pub fn init(channel: u8, gpio: u8, led_num: u16) Self { var self = Self { .ptr = esp.led_strip_init(channel, gpio, led_num) }; self.clear(50) catch unreachable; return self; } pub fn clear(self: Self, timeout: u32) !void { return switch (self.ptr.clear.?(self.ptr, timeout)) { esp.ESP_ERR_TIMEOUT => { _ = c.printf("Clear LEDs failed because of timeout\n"); return error.Timeout; }, esp.ESP_FAIL => { _ = c.printf("Clear LEDs failed because some other error occurred\n"); return error.Other; }, else => .{}, }; } pub fn setPixel(self: Self, index: u32, red: u32, green: u32, blue: u32) !void { return switch (self.ptr.set_pixel.?(self.ptr, index, red, green, blue)) { esp.ESP_ERR_INVALID_ARG => { _ = c.printf("Set RGB for a specific pixel failed because of invalid parameters\n"); return error.InvalidArgument; }, esp.ESP_FAIL => { _ = c.printf("Set RGB for a specific pixel failed because other error occurred\n"); return error.Other; }, else => .{}, }; } pub fn refresh(self: Self, timeout: u32) !void { return switch (self.ptr.refresh.?(self.ptr, timeout)) { esp.ESP_ERR_TIMEOUT => { _ = c.printf("Refresh failed because of timeout\n"); return error.Timeout; }, esp.ESP_FAIL => { _ = c.printf("Refresh failed because other error occurred\n"); return error.Other; }, else => .{}, }; } pub fn enable(self: Self) void { self.setPixel(0, 16, 16, 16) catch unreachable; self.refresh(100) catch unreachable; } pub fn disable(self: Self) void { self.clear(50) catch unreachable; } }; export fn app_main() void { var led_state = false; var strip = LedStrip.init(BLINK_LED_RMT_CHANNEL, BLINK_GPIO, 1); while (true) { log.info("blink", "Toggling the LED %s!", .{@as([:0]const u8, if (led_state) "ON" else "OFF").ptr}); if (led_state) { strip.enable(); } else { strip.disable(); } led_state = !led_state; freertos.vTaskDelay(esp.CONFIG_BLINK_PERIOD / freertos.portTICK_PERIOD_MS); } }
main/src/main.zig
const std = @import("std"); const pkgs = struct { const gemtext = std.build.Pkg{ .name = "gemtext", .path = .{ .path = "src/gemtext.zig" }, }; }; const example_list = [_][]const u8{ "gem2html", "gem2md", "streaming-parser", }; pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("zig-gemtext", "src/lib.zig"); lib.setBuildMode(mode); lib.setTarget(target); lib.addIncludeDir("include"); // Import the C types via translate-c lib.linkLibC(); lib.install(); var main_tests = b.addTest("src/tests.zig"); main_tests.setBuildMode(mode); var lib_tests = b.addTest("src/lib.zig"); //lib_tests.linkLibrary(lib); lib_tests.linkLibC(); lib_tests.addIncludeDir("include"); lib_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); test_step.dependOn(&lib_tests.step); const examples = b.step("examples", "Builds all examples"); inline for (example_list) |example_name| { { const example = b.addExecutable(example_name ++ "-zig", "examples/" ++ example_name ++ ".zig"); example.setBuildMode(mode); example.setTarget(target); example.addPackage(pkgs.gemtext); examples.dependOn(&b.addInstallArtifact(example).step); } { const example = b.addExecutable(example_name ++ "-c", null); example.addCSourceFile("examples/" ++ example_name ++ ".c", &[_][]const u8{ "-std=c11", "-Weverything", }); example.linkLibrary(lib); example.addIncludeDir("include"); example.setBuildMode(mode); example.setTarget(target); example.linkLibC(); examples.dependOn(&b.addInstallArtifact(example).step); } } }
build.zig
const macro = @import("pspmacros.zig"); comptime { asm (macro.import_module_start("UtilsForUser", "0x40010000", "26")); asm (macro.import_function("UtilsForUser", "0xBFA98062", "sceKernelDcacheInvalidateRange")); asm (macro.import_function("UtilsForUser", "0xC8186A58", "sceKernelUtilsMd5Digest")); asm (macro.import_function("UtilsForUser", "0x9E5C5086", "sceKernelUtilsMd5BlockInit")); asm (macro.import_function("UtilsForUser", "0x61E1E525", "sceKernelUtilsMd5BlockUpdate")); asm (macro.import_function("UtilsForUser", "0xB8D24E78", "sceKernelUtilsMd5BlockResult")); asm (macro.import_function("UtilsForUser", "0x840259F1", "sceKernelUtilsSha1Digest")); asm (macro.import_function("UtilsForUser", "0xF8FCD5BA", "sceKernelUtilsSha1BlockInit")); asm (macro.import_function("UtilsForUser", "0x346F6DA8", "sceKernelUtilsSha1BlockUpdate")); asm (macro.import_function("UtilsForUser", "0x585F1C09", "sceKernelUtilsSha1BlockResult")); asm (macro.import_function("UtilsForUser", "0xE860E75E", "sceKernelUtilsMt19937Init")); asm (macro.import_function("UtilsForUser", "0x06FB8A63", "sceKernelUtilsMt19937UInt")); asm (macro.import_function("UtilsForUser", "0x37FB5C42", "sceKernelGetGPI")); asm (macro.import_function("UtilsForUser", "0x6AD345D7", "sceKernelSetGPO")); asm (macro.import_function("UtilsForUser", "0x91E4F6A7", "sceKernelLibcClock")); asm (macro.import_function("UtilsForUser", "0x27CC57F0", "sceKernelLibcTime")); asm (macro.import_function("UtilsForUser", "0x71EC4271", "sceKernelLibcGettimeofday")); asm (macro.import_function("UtilsForUser", "0x79D1C3FA", "sceKernelDcacheWritebackAll")); asm (macro.import_function("UtilsForUser", "0xB435DEC5", "sceKernelDcacheWritebackInvalidateAll")); asm (macro.import_function("UtilsForUser", "0x3EE30821", "sceKernelDcacheWritebackRange")); asm (macro.import_function("UtilsForUser", "0x34B9FA9E", "sceKernelDcacheWritebackInvalidateRange")); asm (macro.import_function("UtilsForUser", "0x80001C4C", "sceKernelDcacheProbe")); asm (macro.import_function("UtilsForUser", "0x16641D70", "sceKernelDcacheReadTag")); asm (macro.import_function("UtilsForUser", "0x4FD31C9D", "sceKernelIcacheProbe")); asm (macro.import_function("UtilsForUser", "0xFB05FAD0", "sceKernelIcacheReadTag")); asm (macro.import_function("UtilsForUser", "0x920F104A", "sceKernelIcacheInvalidateAll")); asm (macro.import_function("UtilsForUser", "0xC2DF770E", "sceKernelIcacheInvalidateRange")); }
src/psp/nids/psputils.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const gui = @import("gui"); const nvg = @import("nanovg"); const Rect = @import("gui/geometry.zig").Rect; const col = @import("color.zig"); const ColorPaletteWidget = @This(); widget: gui.Widget, allocator: Allocator, colors: [4 * 256]u8 = undefined, selected: ?usize = null, selection_locked: bool = false, onSelectionChangedFn: ?fn (*Self) void = null, const Self = @This(); const default_pal_contents = @embedFile("../data/palettes/arne16.pal"); pub fn init(allocator: Allocator, rect: Rect(f32)) !*Self { var self = try allocator.create(Self); self.* = Self{ .widget = gui.Widget.init(allocator, rect), .allocator = allocator, }; try self.loadPalContents(default_pal_contents); self.widget.onMouseMoveFn = onMouseMove; self.widget.onMouseDownFn = onMouseDown; self.widget.drawFn = draw; return self; } pub fn deinit(self: *Self) void { self.widget.deinit(); self.allocator.destroy(self); } pub fn setSelection(self: *Self, selected: ?usize) void { if (self.selection_locked and selected == null) return; if (!std.meta.eql(self.selected, selected)) { self.selected = selected; if (self.onSelectionChangedFn) |onSelectionChanged| onSelectionChanged(self); } } pub fn clearSelection(self: *Self) void { self.setSelection(null); } pub fn loadPal(self: *Self, allocator: Allocator, filename: []const u8) !void { var file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); const contents = try file.readToEndAlloc(allocator, 1 << 20); defer allocator.free(contents); try self.loadPalContents(contents); } const pal_header = "JASC-PAL"; const pal_version = "0100"; const line_ending = "\r\n"; pub fn loadPalContents(self: *Self, contents: []const u8) !void { var lines = std.mem.tokenize(u8, contents, line_ending); const header = lines.next() orelse return error.UnexpectedEnd; if (!std.mem.eql(u8, header, pal_header)) return error.InvalidHeader; const version = lines.next() orelse return error.UnexpectedEnd; if (!std.mem.eql(u8, version, pal_version)) return error.InvalidVersion; const count_string = lines.next() orelse return error.UnexpectedEnd; const count = try std.fmt.parseUnsigned(u32, count_string, 10); if (count > 256) return error.TooManyColors; var i: usize = 0; while (i < count) : (i += 1) { const line = lines.next() orelse return error.UnexpectedEnd; var components = std.mem.tokenize(u8, line, " "); const red_string = components.next() orelse return error.UnexpectedEndOfLine; const green_string = components.next() orelse return error.UnexpectedEndOfLine; const blue_string = components.next() orelse return error.UnexpectedEndOfLine; const red = try std.fmt.parseUnsigned(u8, red_string, 10); const green = try std.fmt.parseUnsigned(u8, green_string, 10); const blue = try std.fmt.parseUnsigned(u8, blue_string, 10); const alpha = 0xff; // TODO self.colors[4 * i + 0] = red; self.colors[4 * i + 1] = green; self.colors[4 * i + 2] = blue; self.colors[4 * i + 3] = alpha; } while (i < 256) : (i += 1) { std.mem.copy(u8, self.colors[4 * i ..][0..4], &col.black); } } pub fn writePal(self: *Self, filename: []const u8) !void { var file = try std.fs.cwd().createFile(filename, .{}); defer file.close(); const palette = col.trimBlackColorsRight(&self.colors); var writer = file.writer(); _ = try writer.write(pal_header ++ line_ending); _ = try writer.write(pal_version ++ line_ending); _ = try writer.print("{}" ++ line_ending, .{palette.len / 4}); var i: usize = 0; while (i < palette.len) : (i += 4) { const color = palette[i .. i + 4]; _ = try writer.print("{} {} {}" ++ line_ending, .{ color[0], color[1], color[2] }); } } fn onMouseMove(widget: *gui.Widget, event: *const gui.MouseEvent) void { const self = @fieldParentPtr(Self, "widget", widget); if (event.isButtonPressed(.left) and self.selected != null) { const rect = widget.relative_rect; const ix = @floatToInt(u8, std.math.clamp(16 * event.x / rect.w, 0, 15)); const iy = @floatToInt(u8, std.math.clamp(16 * event.y / rect.h, 0, 15)); const i = 16 * iy + ix; self.setSelection(i); } } fn onMouseDown(widget: *gui.Widget, event: *const gui.MouseEvent) void { if (event.button == .left) { const self = @fieldParentPtr(Self, "widget", widget); const rect = widget.relative_rect; const ix = std.math.clamp(@floatToInt(u8, 16 * event.x / rect.w), 0, 15); const iy = std.math.clamp(@floatToInt(u8, 16 * event.y / rect.h), 0, 15); const i = 16 * iy + ix; if (self.selected) |selected| { self.setSelection(if (selected != i) i else null); } else { self.setSelection(i); } } } pub fn draw(widget: *gui.Widget, vg: nvg) void { const self = @fieldParentPtr(Self, "widget", widget); const rect = widget.relative_rect; gui.drawPanel(vg, rect.x, rect.y, rect.w, rect.h, 1, false, false); const pad: f32 = 2; const tile_w = (rect.w - pad - (pad - 1)) / 16; const tile_h = (rect.h - pad - (pad - 1)) / 16; var i: usize = 0; while (i < 256) : (i += 1) { const x = @intToFloat(f32, i % 16); const y = @intToFloat(f32, i / 16); vg.beginPath(); vg.rect(rect.x + pad + x * tile_w, rect.y + pad + y * tile_h, tile_w - 1, tile_h - 1); const color = self.colors[i * 4 ..][0..4]; vg.fillColor(nvg.rgb(color[0], color[1], color[2])); vg.fill(); } if (self.selected) |selected| { const x = @intToFloat(f32, selected % 16); const y = @intToFloat(f32, selected / 16); vg.beginPath(); vg.rect(rect.x + pad + x * tile_w - 0.5, rect.y + pad + y * tile_h - 0.5, tile_w, tile_h); vg.strokeColor(nvg.rgbf(1, 1, 1)); vg.stroke(); vg.beginPath(); vg.rect(rect.x + pad + x * tile_w - 1.5, rect.y + pad + y * tile_h - 1.5, tile_w + 2, tile_h + 2); vg.strokeColor(nvg.rgbf(0, 0, 0)); vg.stroke(); } }
src/ColorPaletteWidget.zig
pub const ICW_MAX_ACCTNAME = @as(u32, 256); pub const ICW_MAX_PASSWORD = @as(u32, 256); pub const ICW_MAX_LOGONNAME = @as(u32, 256); pub const ICW_MAX_SERVERNAME = @as(u32, 64); pub const ICW_MAX_RASNAME = @as(u32, 256); pub const ICW_MAX_EMAILNAME = @as(u32, 64); pub const ICW_MAX_EMAILADDR = @as(u32, 128); pub const ICW_CHECKSTATUS = @as(u32, 1); pub const ICW_LAUNCHFULL = @as(u32, 256); pub const ICW_LAUNCHMANUAL = @as(u32, 512); pub const ICW_USE_SHELLNEXT = @as(u32, 1024); pub const ICW_FULL_SMARTSTART = @as(u32, 2048); pub const ICW_FULLPRESENT = @as(u32, 1); pub const ICW_MANUALPRESENT = @as(u32, 2); pub const ICW_ALREADYRUN = @as(u32, 4); pub const ICW_LAUNCHEDFULL = @as(u32, 256); pub const ICW_LAUNCHEDMANUAL = @as(u32, 512); pub const ICW_USEDEFAULTS = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (2) //-------------------------------------------------------------------------------- pub const PFNCHECKCONNECTIONWIZARD = fn( param0: u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNSETSHELLNEXT = fn( param0: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (1) //-------------------------------------------------------------------------------- const PSTR = @import("../foundation.zig").PSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNCHECKCONNECTIONWIZARD")) { _ = PFNCHECKCONNECTIONWIZARD; } if (@hasDecl(@This(), "PFNSETSHELLNEXT")) { _ = PFNSETSHELLNEXT; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/network_management/internet_connection_wizard.zig
const rl = @import("raylib"); pub fn main() anyerror!void { // Initialization //-------------------------------------------------------------------------------------- const screenWidth = 800; const screenHeight = 450; rl.InitWindow(screenWidth, screenHeight, "raylib-zig [core] example - basic window"); var ballPosition = rl.Vector2 { .x = -100.0, .y = -100.0 }; var ballColor = rl.BEIGE; var touchCounter: f32 = 0; var touchPosition = rl.Vector2 { .x = 0.0, .y = 0.0 }; rl.SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop while (!rl.WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- ballPosition = rl.GetMousePosition(); ballColor = rl.BEIGE; if (rl.IsMouseButtonDown(rl.MouseButton.MOUSE_LEFT_BUTTON)) { ballColor = rl.MAROON; } if (rl.IsMouseButtonDown(rl.MouseButton.MOUSE_MIDDLE_BUTTON)) { ballColor = rl.LIME; } if (rl.IsMouseButtonDown(rl.MouseButton.MOUSE_RIGHT_BUTTON)) { ballColor = rl.DARKBLUE; } if (rl.IsMouseButtonPressed(rl.MouseButton.MOUSE_LEFT_BUTTON)) { touchCounter = 10; } if (rl.IsMouseButtonPressed(rl.MouseButton.MOUSE_MIDDLE_BUTTON)) { touchCounter = 10; } if (rl.IsMouseButtonPressed(rl.MouseButton.MOUSE_RIGHT_BUTTON)) { touchCounter = 10; } if (touchCounter > 0) { touchCounter -= 1; } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- rl.BeginDrawing(); rl.ClearBackground(rl.RAYWHITE); const nums = [_]i32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (nums) |i| { touchPosition = rl.GetTouchPosition(i); // Get the touch point if ((touchPosition.x >= 0) and (touchPosition.y >= 0)) // Make sure point is not (-1,-1) as this means there is no touch for it { // Draw circle and touch index number rl.DrawCircleV(touchPosition, 34, rl.ORANGE); rl.DrawText(rl.FormatText("%d", i), @floatToInt(c_int, touchPosition.x) - 10, @floatToInt(c_int, touchPosition.y) - 70, 40, rl.BLACK); } } // Draw the normal mouse location rl.DrawCircleV(ballPosition, 30 + (touchCounter*3), ballColor); rl.DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, rl.DARKGRAY); rl.DrawText("touch the screen at multiple locations to get multiple balls", 10, 30, 20, rl.DARKGRAY); rl.EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- rl.CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- }
examples/core/input_multitouch.zig
const std = @import("std"); const getty = @import("lib.zig"); const ArrayListSer = @import("ser/impl/ser/array_list.zig"); const BoolSer = @import("ser/impl/ser/bool.zig"); const ErrorSer = @import("ser/impl/ser/error.zig"); const EnumSer = @import("ser/impl/ser/enum.zig"); const FloatSer = @import("ser/impl/ser/float.zig"); const IntSer = @import("ser/impl/ser/int.zig"); const OptionalSer = @import("ser/impl/ser/optional.zig"); const PointerSer = @import("ser/impl/ser/pointer.zig"); const NullSer = @import("ser/impl/ser/null.zig"); const LinkedListSer = @import("ser/impl/ser/linked_list.zig"); const SequenceSer = @import("ser/impl/ser/sequence.zig"); const StringSer = @import("ser/impl/ser/string.zig"); const HashMapSer = @import("ser/impl/ser/hash_map.zig"); const StructSer = @import("ser/impl/ser/struct.zig"); const TailQueueSer = @import("ser/impl/ser/tail_queue.zig"); const TupleSer = @import("ser/impl/ser/tuple.zig"); const UnionSer = @import("ser/impl/ser/union.zig"); const VectorSer = @import("ser/impl/ser/vector.zig"); const VoidSer = @import("ser/impl/ser/void.zig"); /// Serializer interface pub usingnamespace @import("ser/interface/serializer.zig"); /// `Ser` interface pub usingnamespace @import("ser/interface/ser.zig"); /// `ser` namespace pub const ser = struct { /// Generic error set for `getty.Ser` implementations. pub const Error = std.mem.Allocator.Error || error{ Unsupported, }; pub usingnamespace @import("ser/interface/serialize/map.zig"); pub usingnamespace @import("ser/interface/serialize/sequence.zig"); pub usingnamespace @import("ser/interface/serialize/struct.zig"); pub usingnamespace @import("ser/interface/serialize/tuple.zig"); }; /// Serializes a value using a provided serializer and `ser`. /// /// `serializeWith` allows for data types that aren't supported by Getty to be /// serialized. Additionally, the function enables the use of custom /// serialization logic for data types that are supported. pub fn serializeWith(value: anytype, serializer: anytype, s: anytype) blk: { getty.concepts.@"getty.Serializer"(@TypeOf(serializer)); getty.concepts.@"getty.Ser"(@TypeOf(s)); break :blk @TypeOf(serializer).Error!@TypeOf(serializer).Ok; } { return try s.serialize(value, serializer); } /// Serializes a value using a provided serializer and a default `ser`. /// /// `Ser`s are only provided for data types supported by Getty, plus a few /// commonly used but unsupported types such as `std.ArrayList` and /// `std.AutoHashMap`. For custom serialization or serialization of data types /// not supported Getty, see `getty.serializeWith`. pub fn serialize(value: anytype, serializer: anytype) blk: { getty.concepts.@"getty.Serializer"(@TypeOf(serializer)); break :blk @TypeOf(serializer).Error!@TypeOf(serializer).Ok; } { const T = @TypeOf(value); var s = switch (@typeInfo(T)) { .Array => SequenceSer{}, .Bool => BoolSer{}, .Enum, .EnumLiteral => EnumSer{}, .ErrorSet => ErrorSer{}, .Float, .ComptimeFloat => FloatSer{}, .Int, .ComptimeInt => IntSer{}, .Null => NullSer{}, .Optional => OptionalSer{}, .Pointer => |info| switch (info.size) { .One => PointerSer{}, .Slice => switch (comptime std.meta.trait.isZigString(T)) { true => StringSer{}, false => SequenceSer{}, }, else => @compileError("type `" ++ @typeName(T) ++ "` is not supported"), }, .Struct => |info| switch (info.is_tuple) { false => blk: { if (comptime std.mem.startsWith(u8, @typeName(T), "std.array_list")) { break :blk ArrayListSer{}; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.hash_map")) { break :blk HashMapSer{}; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.linked_list.SinglyLinkedList")) { break :blk LinkedListSer{}; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.linked_list.TailQueue")) { break :blk TailQueueSer{}; } else { break :blk StructSer{}; } }, true => TupleSer{}, }, .Union => UnionSer{}, .Vector => VectorSer{}, .Void => VoidSer{}, else => @compileError("type `" ++ @typeName(T) ++ "` is not supported"), }; return try serializeWith(value, serializer, s.ser()); }
src/ser.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); fn fuel1(a: usize, b: usize) usize { return aoc.absCast(@intCast(isize, a) - @intCast(isize, b)); } test "fuel1" { try aoc.assertEq(@as(usize, 14), fuel1(16, 2)); try aoc.assertEq(@as(usize, 1), fuel1(1, 2)); try aoc.assertEq(@as(usize, 0), fuel1(2, 2)); try aoc.assertEq(@as(usize, 2), fuel1(0, 2)); try aoc.assertEq(@as(usize, 2), fuel1(4, 2)); try aoc.assertEq(@as(usize, 0), fuel1(2, 2)); try aoc.assertEq(@as(usize, 5), fuel1(7, 2)); try aoc.assertEq(@as(usize, 1), fuel1(1, 2)); try aoc.assertEq(@as(usize, 0), fuel1(2, 2)); try aoc.assertEq(@as(usize, 12), fuel1(14, 2)); } fn fuelsum1(p: usize, inp: []const usize) usize { var c: usize = 0; for (inp) |v| { c += fuel1(p, v); } return c; } fn part1(inp: []usize) usize { std.sort.sort(usize, inp, {}, aoc.usizeLessThan); return fuelsum1(inp[inp.len / 2], inp); } test "part1" { var crabs = try aoc.Ints(aoc.talloc, usize, aoc.test1file); defer aoc.talloc.free(crabs); try aoc.assertEq(@as(usize, 37), part1(crabs)); var crabs2 = try aoc.Ints(aoc.talloc, usize, aoc.inputfile); defer aoc.talloc.free(crabs2); try aoc.assertEq(@as(usize, 336701), part1(crabs2)); } fn fuel2(a: usize, b: usize) usize { var f = fuel1(a, b); return f * (f + 1) / 2; } fn fuelsum2(p: usize, inp: []const usize) usize { var c: usize = 0; for (inp) |v| { c += fuel2(p, v); } return c; } fn part2(inp: []usize) usize { var mean = inp[0]; var i: usize = 1; while (i < inp.len) : (i += 1) { mean += inp[i]; } mean /= inp.len; var min = fuelsum2(mean, inp); var c = fuelsum2(mean + 1, inp); if (min > c) { min = c; } return min; } test "part2" { var crabs = try aoc.Ints(aoc.talloc, usize, aoc.test1file); defer aoc.talloc.free(crabs); try aoc.assertEq(@as(usize, 168), part2(crabs)); var crabs2 = try aoc.Ints(aoc.talloc, usize, aoc.inputfile); defer aoc.talloc.free(crabs2); try aoc.assertEq(@as(usize, 95167302), part2(crabs2)); } fn day07(inp: []const u8, bench: bool) anyerror!void { var crabs = try aoc.Ints(aoc.halloc, usize, inp); defer aoc.halloc.free(crabs); var p1 = part1(crabs); var p2 = part2(crabs); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day07); }
2021/07/aoc.zig
pub const ProtCheckerRule = enum { /// Non-secure and non-privileged user access allowed. NsNonpriv = 0, /// Non-secure and privileged access allowed. NsPriv = 1, /// Secure and non-privileged user access allowed. SNonpriv = 2, /// Secure and privileged user access allowed. SPriv = 3, }; /// Set a single security rule. pub fn setRule(r: *volatile u32, bit: u5, rule: ProtCheckerRule) void { r.* = (r.* & ~(@as(u32, 0b11) << bit)) | (@as(u32, @enumToInt(rule)) << bit); } /// Represents a single instance of a memory protection checker. pub const Mpc = struct { base: usize, block_size_shift: u5, num_blocks: u32, const Self = @This(); /// Set the security rule of a relative address range. /// /// The range might be rounded to the block size the hardware is configured /// with. pub fn setRuleInRange(self: Self, start: u32, end: u32, rule: ProtCheckerRule) void { self.updateRange(start, end, Masks{ 0xcccccccc, @enumToInt(u32, rule) * 0x11111111 }); } fn updateLut(self: Self, gr: u32, masks: Masks) void { const lut = @intToPtr(*volatile u32, self.base + gr * 4); lut.* = (lut.* & masks[0]) ^ masks[1]; } fn updateRange(self: Self, startBytes: u32, endBytes: u32, masks: Masks) void { // (Silently) round to the block size used by the hardware const shift = self.block_size_shift(); const start = startBytes >> shift; const end = endBytes >> shift; if (start >= end) { return; } if (end > self.num_blocks) { unreachable; } // Each 32-bit register contains the information for 8 blocks const start_group = start / 32 * 4; const end_group = end / 32 * 4; if (start_group == end_group) { const masks2 = filterMasks(masks, onesFrom(start % 32) ^ onesFrom(end % 32)); self.updateLut(start_group, masks2); } else { var group = start_group; if ((start % 32) != 0) { const cap_masks = filterMasks(masks, onesFrom(start % 32)); self.updateLut(group, cap_masks); group += 1; } while (group < end_group) { self.updateLut(group, masks); group += 1; } if ((end % 32) != 0) { const cap_masks = filterMasks(masks, ~onesFrom(end % 32)); self.updateLut(group, cap_masks); } } } }; /// AND and XOR masks. const Masks = [2]u32; fn filterMasks(masks: Masks, filter: u32) Masks { return Masks{ masks[0] & ~filter, masks[1] & filter }; } /// Returns `0b11111000...000` where the number of trailing zeros is specified /// by `pos`. `pos` must be in `[0, 31]`. fn onesFrom(pos: u32) u32 { return @as(u32, 0xffffffff) << @intCast(u5, pos); }
examples/drivers/lpc_protchecker.zig
const std = @import("std"); const os = std.os; const warn = std.debug.warn; const print = std.debug.print; const memory = @import("memory.zig"); const readMemMap = @import("read_map.zig").readMemMap; const input = @import("input.zig"); const Needle = @import("needle.zig").Needle; const call_fn_with_union_type = @import("needle.zig").call_fn_with_union_type; fn help() void { warn("User must supply pid and (type + bit length). User may optionally supply a byte alignment.\n", .{}); warn("Available types are: [i, u, f, s]\n", .{}); warn("i: signed integer - Available with bit lengths [8, 16, 32, 64]\n", .{}); warn("u: unsigned integer - Available with bit lengths [8, 16, 32, 64]\n", .{}); warn("f: float - Available with bit lengths [16, 32, 64] \n", .{}); warn("s: string - Does not use a bit length\n", .{}); warn("\n", .{}); warn("Example Usage: {s} 5005 u32\n", .{os.argv[0]}); } pub fn main() anyerror!void { if (os.argv.len < 3) { help(); os.exit(2); } const pid = std.fmt.parseInt(os.pid_t, std.mem.span(os.argv[1]), 10) catch |err| { warn("Failed parsing PID \"{s}\". {}\n", .{ os.argv[1], err }); os.exit(2); }; var needle_typeinfo = input.parseStringForType(std.mem.span(os.argv[2])) catch |err| { warn("Failed parsing search type \"{s}\". {}\n", .{ os.argv[2], err }); os.exit(2); }; const byte_alignment: u8 = blk: { const default = 4; if (os.argv.len > 3) { const result = std.fmt.parseInt(u8, std.mem.span(os.argv[3]), 10) catch default; if (result < 1) break :blk 1; break :blk result; } break :blk default; }; const allocator = std.heap.page_allocator; // Perhaps we should link with libc to use malloc const st = std.time.milliTimestamp(); var memory_segments = readMemMap(allocator, pid) catch |err| { switch (err) { error.FileNotFound => { warn("Process matching pid {} not found.\n", .{pid}); os.exit(1); }, else => return err, } }; defer memory_segments.deinit(); defer for (memory_segments.items) |*i| if (i.name) |n| allocator.free(n); const process_name = find_process_name(allocator, pid) catch null; defer if (process_name) |pn| allocator.free(pn); if (memory_segments.items.len == 0) { print("No memory segments found for \"{s}\", pid {}. Exiting\n", .{ process_name, pid }); return; } var total_memory: usize = 0; for (memory_segments.items) |i, n| { total_memory += i.len; } print("{s} is using {} memory segments for a total of ", .{ process_name, memory_segments.items.len }); printHumanReadableByteCount(total_memory); print("\n", .{}); const needle: []const u8 = try input.askUserForValue(&needle_typeinfo); const initial_scan_start = std.time.milliTimestamp(); var potential_addresses = (memory.parseSegments(allocator, pid, &memory_segments, needle, byte_alignment) catch |err| { switch (err) { error.InsufficientPermission => { print("Insufficient permission to read memory from \"{s}\" (pid {})\n", .{ process_name, pid }); return; }, else => return err, } }) orelse { print("No match found. Exiting.\n", .{}); return; }; defer potential_addresses.deinit(); print("Initial scan took {} ms\n", .{std.time.milliTimestamp() - initial_scan_start}); const maybe_final_address = try findMatch(&needle_typeinfo, pid, &potential_addresses); if (maybe_final_address) |addr| { print("Match found at: {} ({x})\n", .{ addr, addr }); try handleFinalMatch(needle_typeinfo, pid, addr); } else { print("No match found. Exiting.\n", .{}); } } /// Using user input, filters potential addresses until we have a single one remaining. fn findMatch(needle: *Needle, pid: os.pid_t, potential_addresses: *memory.Addresses) !?usize { var justPrintedAddresses = false; while (potential_addresses.items.len > 1) { print("Potential addresses: {}\n", .{potential_addresses.items.len}); if (potential_addresses.items.len < 5) { for (potential_addresses.items) |pa| print("potential addr: {} ({x}) \n", .{ pa, pa }); } const needle_bytes = getNewNeedle(needle, potential_addresses.items); try memory.pruneAddresses(pid, needle_bytes, potential_addresses); } if (potential_addresses.items.len == 1) { return potential_addresses.items[0]; } else { return null; } } /// Returns the bytes for a new needle from the user. /// Will not return until a valid needle value is given. /// This may result in multiple requests to the user for a needle value. fn getNewNeedle(needle: *Needle, potential_addresses: []usize) []const u8 { const needle_bytes: []const u8 = input.askUserForValue(needle) catch |err| { switch (err) { error.NoInputGiven => { for (potential_addresses) |i, index| print("#{}: {} ({x})\n", .{ index, i, i }); print("\n", .{}); }, error.Overflow, error.InvalidCharacter => warn("{}\n\n", .{err}), } return getNewNeedle(needle, potential_addresses); }; return needle_bytes; } /// Allows user to repeatedly view the value located at the needle address. fn handleFinalMatch(needle: Needle, pid: os.pid_t, needle_address: usize) !void { var buffer = [_]u8{0} ** 400; while (true) { if (needle == .string) { print("\nPlease enter the number of characters you would like to read, up to {} > ", .{buffer.len}); } else { print("\nEnter any character to print value at needle address, or nothing to exit > ", .{}); } const user_input = input.getStdin() orelse break; var str_len: usize = 0; if (needle == .string) { var peek_length = std.fmt.parseInt(usize, user_input, 10) catch continue; if (peek_length > buffer.len) peek_length = buffer.len; str_len = memory.readRemote(buffer[0..peek_length], pid, needle_address) catch |err| { switch (err) { error.RemoteReadAmountMismatch => { print("{} exceeded the length of the valid address space. Try a smaller number\n", .{peek_length}); continue; }, else => return err, } }; } else { _ = try memory.readRemote(buffer[0..needle.size()], pid, needle_address); // We are intentionally re-using parts of buffer here for both parameters. The function is safe for this use case. str_len = try call_fn_with_union_type(needle, anyerror!usize, printToBufferAs, .{ buffer[0..needle.size()], buffer[0..] }); } print("value is: {s}\n", .{buffer[0..str_len]}); } } /// Reads the given bytes as a type appropriate for the given NeedleType. /// Prints that value to the buffer as a string. /// Returns the number of characters written to buffer. fn printToBufferAs(comptime T: type, bytes: []u8, out: []u8) !usize { const result = @ptrCast(*align(1) T, bytes[0..]).*; return (try std.fmt.bufPrint(out, "{}", .{result})).len; } // Zig std lib provides a built-in alternative, "{B:.2}". // However, I am unhappy with its output, thus we have this. // For reference, 500MB would be printed as 0.50GB. fn printHumanReadableByteCount(bytes: usize) void { const kb_limit = 1000 * 1000; const bytes_per_kb = 1000; const mb_limit = kb_limit * 1000; const bytes_per_mb = bytes_per_kb * 1000; const bytes_per_gb = bytes_per_mb * 1000; const fbytes = @intToFloat(f64, bytes); if (bytes < 1000) { print("{d:.2} B", .{bytes}); } else if (bytes < kb_limit) { print("{d:.2} KB", .{fbytes / bytes_per_kb}); } else if (bytes < mb_limit) { print("{d:.2} MB", .{fbytes / bytes_per_mb}); } else { print("{d:.2} GB", .{fbytes / bytes_per_gb}); } } /// Returns the process name for a given pid. /// Caller owns the memory. fn find_process_name(allocator: *std.mem.Allocator, pid: os.pid_t) ![]u8 { var path_buffer = [_]u8{0} ** 30; var fbs = std.io.fixedBufferStream(path_buffer[0..]); try std.fmt.format(fbs.writer(), "/proc/{}/comm", .{pid}); const path = path_buffer[0..fbs.pos]; const fd = try os.open(path, 0, os.O_RDONLY); defer os.close(fd); var file = std.fs.File{ .handle = fd }; var name = try file.readToEndAlloc(allocator, 1000); if (std.mem.endsWith(u8, name, "\n")) { name = allocator.shrink(name, name.len - 1); } return name; }
src/main.zig
const std = @import("../../std.zig"); const net = @import("net.zig"); const os = std.os; const fmt = std.fmt; const mem = std.mem; const time = std.time; const builtin = std.builtin; /// 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) { 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 = @ptrCast(*const os.sockaddr_in, address); const host = net.IPv4{ .octets = @bitCast([4]u8, info.addr) }; const port = mem.bigToNative(u16, info.port); return Socket.Address.initIPv4(host, port); }, os.AF_INET6 => { const info = @ptrCast(*const os.sockaddr_in6, 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 = @bitCast(u32, 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 { switch (self) { .ipv4 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), .ipv6 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), } } }; /// 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 (builtin.os.tag) { .windows => @import("socket_windows.zig"), else => @import("socket_posix.zig"), }.Mixin(Socket); };
lib/std/x/os/socket.zig
const std = @import("std"); const testing = std.testing; const allocator = std.heap.page_allocator; pub const Decoder = struct { pub const Mode = enum { Value, Address, }; mode: Mode, mem: std.AutoHashMap(u64, u64), mask0: u64, mask1: u64, floats: [36]u6, fpos: usize, pub fn init(mode: Mode) Decoder { var self = Decoder{ .mode = mode, .mem = std.AutoHashMap(u64, u64).init(allocator), .mask0 = 0, .mask1 = 0, .floats = undefined, .fpos = 0, }; return self; } pub fn deinit(self: *Decoder) void { self.mem.deinit(); } pub fn add_line(self: *Decoder, line: []const u8) void { var it = std.mem.tokenize(u8, line, " ="); const cmd = it.next().?; const val = it.next().?; if (std.mem.eql(u8, cmd, "mask")) { self.set_mask(val); return; } if (std.mem.eql(u8, cmd[0..3], "mem")) { var addr = std.fmt.parseInt(u64, cmd[4 .. cmd.len - 1], 10) catch unreachable; var value = std.fmt.parseInt(u64, val, 10) catch unreachable; self.set_mem(addr, value); return; } @panic("Field"); } pub fn sum_all_values(self: Decoder) usize { var sum: usize = 0; var it = self.mem.iterator(); while (it.next()) |kv| { sum += kv.value_ptr.*; } return sum; } fn set_mask(self: *Decoder, mask: []const u8) void { self.fpos = 0; self.mask0 = 0; self.mask1 = 0; for (mask) |c, j| { self.mask0 <<= 1; self.mask1 <<= 1; self.mask0 |= 1; if (c == 'X') { const bit = mask.len - j - 1; self.floats[self.fpos] = @intCast(u6, bit); self.fpos += 1; continue; } if (c == '0') { if (self.mode == Mode.Address) continue; self.mask0 &= ~(@as(u64, 1)); continue; } if (c == '1') { self.mask1 |= 1; continue; } } } fn set_mem(self: *Decoder, addr: u64, val: u64) void { switch (self.mode) { Mode.Value => { var value: u64 = val; value &= self.mask0; value |= self.mask1; self.store(addr, value); }, Mode.Address => { var address: u64 = addr; address &= self.mask0; address |= self.mask1; self.set_mem_multiple(address, val, 0); }, } } fn set_mem_multiple(self: *Decoder, addr: u64, value: u64, pos: usize) void { if (pos >= self.fpos) { self.store(addr, value); return; } const bit: u6 = self.floats[pos]; const mask0: u64 = @as(u64, 1) << bit; const mask1: u64 = ~mask0; self.set_mem_multiple(addr & mask1, value, pos + 1); self.set_mem_multiple(addr | mask0, value, pos + 1); } fn store(self: *Decoder, addr: u64, val: u64) void { // std.debug.warn("MEM {} {b} => {}\n", .{ addr, addr, val }); if (self.mem.contains(addr)) { _ = self.mem.remove(addr); } _ = self.mem.put(addr, val) catch unreachable; } }; test "sample value" { const data: []const u8 = \\mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X \\mem[8] = 11 \\mem[7] = 101 \\mem[8] = 0 ; var decoder = Decoder.init(Decoder.Mode.Value); defer decoder.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { decoder.add_line(line); } const sum = decoder.sum_all_values(); try testing.expect(sum == 165); } test "sample address" { const data: []const u8 = \\mask = 000000000000000000000000000000X1001X \\mem[42] = 100 \\mask = 00000000000000000000000000000000X0XX \\mem[26] = 1 ; var decoder = Decoder.init(Decoder.Mode.Address); defer decoder.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { decoder.add_line(line); } const sum = decoder.sum_all_values(); try testing.expect(sum == 208); }
2020/p14/decoder.zig
const std = @import("std"); const print = std.debug.print; const assert = std.debug.assert; // base is base of number system // mem[] is the number in the base number system // we do not need to use length of the buffer as function arguments // NOTE // - This pattern is, because mem_arrray is actually an array // var mem_array = [_]u32{ 1, 2, 3 }; // var mem_ref: []u32 = &mem_array; // - TODO error handling instead of returning u32 //assume base >= 0 fn isValidNumber(mem: []u32, base: u32) bool { for (mem) |m_el| { if (m_el >= base) return false; } return true; } fn isNotNull(mem: []const u32) bool { for (mem) |m_el| { if (m_el != 0) { return true; } } return false; } // TODO define error codes fn add(mem: []u32, base: u32) u32 { var carry = false; var index: u32 = @intCast(u32, mem.len - 1); while (index >= 0) : (index -= 1) { var added_val = mem[index] + 1; if (added_val == base) { carry = true; } else { mem[index] = added_val; break; } } if (index == -1 and carry == true) { return 1; // could not increase anymore } if (carry == true) { assert(index < mem.len - 1); index += 1; // zero out numbers right of the index while (index < mem.len) : (index += 1) { mem[index] = 0; } } return 0; } test "isValidNumber" { const base: u32 = 4; var mem_array = [_]u32{ 1, 2, 3 }; var mem_ref: []u32 = &mem_array; assert(isValidNumber(mem_ref, base) == true); } test "isNull" { var mem_array1 = [_]u32{ 0, 0, 0 }; var mem_ref1: []u32 = &mem_array1; var is_not_null = isNotNull(mem_ref1); assert(is_not_null == false); var mem_array2 = [_]u32{ 1, 1, 1 }; var mem_ref2: []u32 = &mem_array2; assert(isNotNull(mem_ref2) == true); } test "add" { const base: u32 = 4; var mem_array = [_]u32{ 1, 2, 3 }; var mem_ref: []u32 = &mem_array; _ = add(mem_ref, base); //assert(add(mem_ref, base) == true); // TODO deep copy of stuff }
main.zig
const std = @import("std"); const g = @import("spirv/grammar.zig"); const Allocator = std.mem.Allocator; const ExtendedStructSet = std.StringHashMap(void); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); if (args.len != 2) { usageAndExit(std.io.getStdErr(), args[0], 1); } const spec_path = args[1]; const spec = try std.fs.cwd().readFileAlloc(allocator, spec_path, std.math.maxInt(usize)); // Required for json parsing. @setEvalBranchQuota(10000); var tokens = std.json.TokenStream.init(spec); var registry = try std.json.parse(g.Registry, &tokens, .{ .allocator = allocator }); const core_reg = switch (registry) { .core => |core_reg| core_reg, .extension => return error.TODOSpirVExtensionSpec, }; var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); try render(bw.writer(), allocator, core_reg); try bw.flush(); } /// Returns a set with types that require an extra struct for the `Instruction` interface /// to the spir-v spec, or whether the original type can be used. fn extendedStructs( arena: Allocator, kinds: []const g.OperandKind, ) !ExtendedStructSet { var map = ExtendedStructSet.init(arena); try map.ensureTotalCapacity(@intCast(u32, kinds.len)); for (kinds) |kind| { const enumerants = kind.enumerants orelse continue; for (enumerants) |enumerant| { if (enumerant.parameters.len > 0) { break; } } else continue; map.putAssumeCapacity(kind.kind, {}); } return map; } // Return a score for a particular priority. Duplicate instruction/operand enum values are // removed by picking the tag with the lowest score to keep, and by making an alias for the // other. Note that the tag does not need to be just a tag at this point, in which case it // gets the lowest score automatically anyway. fn tagPriorityScore(tag: []const u8) usize { if (tag.len == 0) { return 1; } else if (std.mem.eql(u8, tag, "EXT")) { return 2; } else if (std.mem.eql(u8, tag, "KHR")) { return 3; } else { return 4; } } fn render(writer: anytype, allocator: Allocator, registry: g.CoreRegistry) !void { try writer.writeAll( \\//! This file is auto-generated by tools/gen_spirv_spec.zig. \\ \\const Version = @import("std").builtin.Version; \\ \\pub const Word = u32; \\pub const IdResultType = struct{ \\ id: Word, \\ pub fn toRef(self: IdResultType) IdRef { \\ return .{.id = self.id}; \\ } \\}; \\pub const IdResult = struct{ \\ id: Word, \\ pub fn toRef(self: IdResult) IdRef { \\ return .{.id = self.id}; \\ } \\ pub fn toResultType(self: IdResult) IdResultType { \\ return .{.id = self.id}; \\ } \\}; \\pub const IdRef = struct{ id: Word }; \\ \\pub const IdMemorySemantics = IdRef; \\pub const IdScope = IdRef; \\ \\pub const LiteralInteger = Word; \\pub const LiteralString = []const u8; \\pub const LiteralContextDependentNumber = union(enum) { \\ int32: i32, \\ uint32: u32, \\ int64: i64, \\ uint64: u64, \\ float32: f32, \\ float64: f64, \\}; \\pub const LiteralExtInstInteger = struct{ inst: Word }; \\pub const LiteralSpecConstantOpInteger = struct { opcode: Opcode }; \\pub const PairLiteralIntegerIdRef = struct { value: LiteralInteger, label: IdRef }; \\pub const PairIdRefLiteralInteger = struct { target: IdRef, member: LiteralInteger }; \\pub const PairIdRefIdRef = [2]IdRef; \\ \\ ); try writer.print( \\pub const version = Version{{ .major = {}, .minor = {}, .patch = {} }}; \\pub const magic_number: Word = {s}; \\ , .{ registry.major_version, registry.minor_version, registry.revision, registry.magic_number }, ); const extended_structs = try extendedStructs(allocator, registry.operand_kinds); try renderOpcodes(writer, allocator, registry.instructions, extended_structs); try renderOperandKinds(writer, allocator, registry.operand_kinds, extended_structs); } fn renderOpcodes( writer: anytype, allocator: Allocator, instructions: []const g.Instruction, extended_structs: ExtendedStructSet, ) !void { var inst_map = std.AutoArrayHashMap(u32, usize).init(allocator); try inst_map.ensureTotalCapacity(instructions.len); var aliases = std.ArrayList(struct { inst: usize, alias: usize }).init(allocator); try aliases.ensureTotalCapacity(instructions.len); for (instructions) |inst, i| { const result = inst_map.getOrPutAssumeCapacity(inst.opcode); if (!result.found_existing) { result.value_ptr.* = i; continue; } const existing = instructions[result.value_ptr.*]; const tag_index = std.mem.indexOfDiff(u8, inst.opname, existing.opname).?; const inst_priority = tagPriorityScore(inst.opname[tag_index..]); const existing_priority = tagPriorityScore(existing.opname[tag_index..]); if (inst_priority < existing_priority) { aliases.appendAssumeCapacity(.{ .inst = result.value_ptr.*, .alias = i }); result.value_ptr.* = i; } else { aliases.appendAssumeCapacity(.{ .inst = i, .alias = result.value_ptr.* }); } } const instructions_indices = inst_map.values(); try writer.writeAll("pub const Opcode = enum(u16) {\n"); for (instructions_indices) |i| { const inst = instructions[i]; try writer.print("{} = {},\n", .{ std.zig.fmtId(inst.opname), inst.opcode }); } try writer.writeByte('\n'); for (aliases.items) |alias| { try writer.print("pub const {} = Opcode.{};\n", .{ std.zig.fmtId(instructions[alias.inst].opname), std.zig.fmtId(instructions[alias.alias].opname), }); } try writer.writeAll( \\ \\pub fn Operands(comptime self: Opcode) type { \\return switch (self) { \\ ); for (instructions_indices) |i| { const inst = instructions[i]; try renderOperand(writer, .instruction, inst.opname, inst.operands, extended_structs); } try writer.writeAll("};\n}\n};\n"); _ = extended_structs; } fn renderOperandKinds( writer: anytype, allocator: Allocator, kinds: []const g.OperandKind, extended_structs: ExtendedStructSet, ) !void { for (kinds) |kind| { switch (kind.category) { .ValueEnum => try renderValueEnum(writer, allocator, kind, extended_structs), .BitEnum => try renderBitEnum(writer, allocator, kind, extended_structs), else => {}, } } } fn renderValueEnum( writer: anytype, allocator: Allocator, enumeration: g.OperandKind, extended_structs: ExtendedStructSet, ) !void { const enumerants = enumeration.enumerants orelse return error.InvalidRegistry; var enum_map = std.AutoArrayHashMap(u32, usize).init(allocator); try enum_map.ensureTotalCapacity(enumerants.len); var aliases = std.ArrayList(struct { enumerant: usize, alias: usize }).init(allocator); try aliases.ensureTotalCapacity(enumerants.len); for (enumerants) |enumerant, i| { const result = enum_map.getOrPutAssumeCapacity(enumerant.value.int); if (!result.found_existing) { result.value_ptr.* = i; continue; } const existing = enumerants[result.value_ptr.*]; const tag_index = std.mem.indexOfDiff(u8, enumerant.enumerant, existing.enumerant).?; const enum_priority = tagPriorityScore(enumerant.enumerant[tag_index..]); const existing_priority = tagPriorityScore(existing.enumerant[tag_index..]); if (enum_priority < existing_priority) { aliases.appendAssumeCapacity(.{ .enumerant = result.value_ptr.*, .alias = i }); result.value_ptr.* = i; } else { aliases.appendAssumeCapacity(.{ .enumerant = i, .alias = result.value_ptr.* }); } } const enum_indices = enum_map.values(); try writer.print("pub const {s} = enum(u32) {{\n", .{std.zig.fmtId(enumeration.kind)}); for (enum_indices) |i| { const enumerant = enumerants[i]; if (enumerant.value != .int) return error.InvalidRegistry; try writer.print("{} = {},\n", .{ std.zig.fmtId(enumerant.enumerant), enumerant.value.int }); } try writer.writeByte('\n'); for (aliases.items) |alias| { try writer.print("pub const {} = {}.{};\n", .{ std.zig.fmtId(enumerants[alias.enumerant].enumerant), std.zig.fmtId(enumeration.kind), std.zig.fmtId(enumerants[alias.alias].enumerant), }); } if (!extended_structs.contains(enumeration.kind)) { try writer.writeAll("};\n"); return; } try writer.print("\npub const Extended = union({}) {{\n", .{std.zig.fmtId(enumeration.kind)}); for (enum_indices) |i| { const enumerant = enumerants[i]; try renderOperand(writer, .@"union", enumerant.enumerant, enumerant.parameters, extended_structs); } try writer.writeAll("};\n};\n"); } fn renderBitEnum( writer: anytype, allocator: Allocator, enumeration: g.OperandKind, extended_structs: ExtendedStructSet, ) !void { try writer.print("pub const {s} = packed struct {{\n", .{std.zig.fmtId(enumeration.kind)}); var flags_by_bitpos = [_]?usize{null} ** 32; const enumerants = enumeration.enumerants orelse return error.InvalidRegistry; var aliases = std.ArrayList(struct { flag: usize, alias: u5 }).init(allocator); try aliases.ensureTotalCapacity(enumerants.len); for (enumerants) |enumerant, i| { if (enumerant.value != .bitflag) return error.InvalidRegistry; const value = try parseHexInt(enumerant.value.bitflag); if (@popCount(u32, value) == 0) { continue; // Skip 'none' items } std.debug.assert(@popCount(u32, value) == 1); var bitpos = std.math.log2_int(u32, value); if (flags_by_bitpos[bitpos]) |*existing| { const tag_index = std.mem.indexOfDiff(u8, enumerant.enumerant, enumerants[existing.*].enumerant).?; const enum_priority = tagPriorityScore(enumerant.enumerant[tag_index..]); const existing_priority = tagPriorityScore(enumerants[existing.*].enumerant[tag_index..]); if (enum_priority < existing_priority) { aliases.appendAssumeCapacity(.{ .flag = existing.*, .alias = bitpos }); existing.* = i; } else { aliases.appendAssumeCapacity(.{ .flag = i, .alias = bitpos }); } } else { flags_by_bitpos[bitpos] = i; } } for (flags_by_bitpos) |maybe_flag_index, bitpos| { if (maybe_flag_index) |flag_index| { try writer.print("{}", .{std.zig.fmtId(enumerants[flag_index].enumerant)}); } else { try writer.print("_reserved_bit_{}", .{bitpos}); } try writer.writeAll(": bool = false,\n"); } try writer.writeByte('\n'); for (aliases.items) |alias| { try writer.print("pub const {}: {} = .{{.{} = true}};\n", .{ std.zig.fmtId(enumerants[alias.flag].enumerant), std.zig.fmtId(enumeration.kind), std.zig.fmtId(enumerants[flags_by_bitpos[alias.alias].?].enumerant), }); } if (!extended_structs.contains(enumeration.kind)) { try writer.writeAll("};\n"); return; } try writer.print("\npub const Extended = struct {{\n", .{}); for (flags_by_bitpos) |maybe_flag_index, bitpos| { const flag_index = maybe_flag_index orelse { try writer.print("_reserved_bit_{}: bool = false,\n", .{bitpos}); continue; }; const enumerant = enumerants[flag_index]; try renderOperand(writer, .mask, enumerant.enumerant, enumerant.parameters, extended_structs); } try writer.writeAll("};\n};\n"); } fn renderOperand( writer: anytype, kind: enum { @"union", instruction, mask, }, field_name: []const u8, parameters: []const g.Operand, extended_structs: ExtendedStructSet, ) !void { if (kind == .instruction) { try writer.writeByte('.'); } try writer.print("{}", .{std.zig.fmtId(field_name)}); if (parameters.len == 0) { switch (kind) { .@"union" => try writer.writeAll(",\n"), .instruction => try writer.writeAll(" => void,\n"), .mask => try writer.writeAll(": bool = false,\n"), } return; } if (kind == .instruction) { try writer.writeAll(" => "); } else { try writer.writeAll(": "); } if (kind == .mask) { try writer.writeByte('?'); } try writer.writeAll("struct{"); for (parameters) |param, j| { if (j != 0) { try writer.writeAll(", "); } try renderFieldName(writer, parameters, j); try writer.writeAll(": "); if (param.quantifier) |q| { switch (q) { .@"?" => try writer.writeByte('?'), .@"*" => try writer.writeAll("[]const "), } } try writer.print("{}", .{std.zig.fmtId(param.kind)}); if (extended_structs.contains(param.kind)) { try writer.writeAll(".Extended"); } if (param.quantifier) |q| { switch (q) { .@"?" => try writer.writeAll(" = null"), .@"*" => try writer.writeAll(" = &.{}"), } } } try writer.writeAll("}"); if (kind == .mask) { try writer.writeAll(" = null"); } try writer.writeAll(",\n"); } fn renderFieldName(writer: anytype, operands: []const g.Operand, field_index: usize) !void { const operand = operands[field_index]; // Should be enough for all names - adjust as needed. var name_buffer = std.BoundedArray(u8, 64){ .buffer = undefined, }; derive_from_kind: { // Operand names are often in the json encoded as "'Name'" (with two sets of quotes). // Additionally, some operands have ~ in them at the end (D~ref~). const name = std.mem.trim(u8, operand.name, "'~"); if (name.len == 0) { break :derive_from_kind; } // Some names have weird characters in them (like newlines) - skip any such ones. // Use the same loop to transform to snake-case. for (name) |c| { switch (c) { 'a'...'z', '0'...'9' => try name_buffer.append(c), 'A'...'Z' => try name_buffer.append(std.ascii.toLower(c)), ' ', '~' => try name_buffer.append('_'), else => break :derive_from_kind, } } // Assume there are no duplicate 'name' fields. try writer.print("{}", .{std.zig.fmtId(name_buffer.slice())}); return; } // Translate to snake case. name_buffer.len = 0; for (operand.kind) |c, i| { switch (c) { 'a'...'z', '0'...'9' => try name_buffer.append(c), 'A'...'Z' => if (i > 0 and std.ascii.isLower(operand.kind[i - 1])) { try name_buffer.appendSlice(&[_]u8{ '_', std.ascii.toLower(c) }); } else { try name_buffer.append(std.ascii.toLower(c)); }, else => unreachable, // Assume that the name is valid C-syntax (and contains no underscores). } } try writer.print("{}", .{std.zig.fmtId(name_buffer.slice())}); // For fields derived from type name, there could be any amount. // Simply check against all other fields, and if another similar one exists, add a number. const need_extra_index = for (operands) |other_operand, i| { if (i != field_index and std.mem.eql(u8, operand.kind, other_operand.kind)) { break true; } } else false; if (need_extra_index) { try writer.print("_{}", .{field_index}); } } fn parseHexInt(text: []const u8) !u31 { const prefix = "0x"; if (!std.mem.startsWith(u8, text, prefix)) return error.InvalidHexInt; return try std.fmt.parseInt(u31, text[prefix.len..], 16); } fn usageAndExit(file: std.fs.File, arg0: []const u8, code: u8) noreturn { file.writer().print( \\Usage: {s} <spirv json spec> \\ \\Generates Zig bindings for a SPIR-V specification .json (either core or \\extinst versions). The result, printed to stdout, should be used to update \\files in src/codegen/spirv. Don't forget to format the output. \\ \\The relevant specifications can be obtained from the SPIR-V registry: \\https://github.com/KhronosGroup/SPIRV-Headers/blob/master/include/spirv/unified1/ \\ , .{arg0}) catch std.process.exit(1); std.process.exit(code); }
tools/gen_spirv_spec.zig
const layout = @import("layout.zig"); const x86 = @import("x86.zig"); const fmt = @import("std").fmt; // Screen size. const VGA_WIDTH = 80; const VGA_HEIGHT = 25; // Color codes. pub const Color = enum(u4) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGrey = 7, DarkGrey = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, LightBrown = 14, White = 15, }; // Character with attributes. const VGAEntry = packed struct { char: u8, foreground: Color, background: Color, }; // VRAM buffer. const vram = @intToPtr(&volatile VGAEntry, layout.VRAM)[0..0x4000]; var background = Color.Black; // Background color. var foreground = Color.LightGrey; // Foreground color. var cursor = usize(0); // Cursor position. //// // Initialize the terminal. // pub fn initialize() void { // Disable cursor. x86.outb(0x3D4, 0xA); x86.outb(0x3D5, 1 << 5); clear(); } //// // Clear the screen. // pub fn clear() void { cursor = 0; while (cursor < VGA_HEIGHT * VGA_WIDTH) writeChar(' '); cursor = 0; } //// // Set the default foreground color. // // Arguments: // fg: The color to set. // pub fn setForeground(fg: Color) void { foreground = fg; } //// // Set the default background color. // // Arguments: // bg: The color to set. // pub fn setBackground(bg: Color) void { background = bg; } //// // Print a formatted string to screen. // // Arguments: // format: Format string. // args: Parameters for format specifiers. // const Errors = error {}; pub fn printf(comptime format: []const u8, args: ...) void { _ = fmt.format({}, Errors, printCallback, format, args); } // Callback for printf. fn printCallback(context: void, string: []const u8) Errors!void { write(string); } //// // Print a string in the given foreground color. // // Arguments: // fg: Color of the text. // format: Format string. // args: Parameters for format specifiers. // pub fn colorPrintf(fg: Color, comptime format: []const u8, args: ...) void { var save_foreground = foreground; foreground = fg; printf(format, args); foreground = save_foreground; } //// // Print a string to the screen. // // Arguments: // string: String to be printed. // pub fn write(string: []const u8) void { for (string) |c| writeChar(c); } //// // Print a character to the screen. // // Arguments: // char: Char to be printed. // pub fn writeChar(char: u8) void { switch (char) { // Newline: '\n' => { writeChar(' '); alignLeft(0); }, // Tab: '\t' => { writeChar(' '); while (cursor % 4 != 0) writeChar(' '); }, // Any other character: else => { vram[cursor] = VGAEntry { .char = char, .background = background, .foreground = foreground, }; cursor += 1; }, } } //// // Align the cursor so that it is offset characters from the left border. // // Arguments: // offset: Number of characters from the left border. // pub fn alignLeft(offset: usize) void { while (cursor % VGA_WIDTH != offset) writeChar(' '); } //// // Align the cursor so that it is offset characters from the right border. // // Arguments: // offset: Number of characters from the right border. // pub fn alignRight(offset: usize) void { alignLeft(VGA_WIDTH - offset); } //// // Align the cursor to horizontally center a string. // // Arguments: // str_len: Length of the string to be centered. // pub fn alignCenter(str_len: usize) void { alignLeft((VGA_WIDTH - str_len) / 2); } //// // Signal an unrecoverable error and hang the computer. // // Arguments: // format: Format string. // args: Parameters for format specifiers. // pub fn panic(comptime format: []const u8, args: ...) noreturn { writeChar('\n'); setBackground(Color.Red); colorPrintf(Color.White, "KERNEL PANIC: " ++ format ++ "\n", args); x86.hang(); } //// // Print a loading step. // // Arguments: // format: Format string. // args: Parameters for format specifiers. // pub fn step(comptime format: []const u8, args: ...) void { colorPrintf(Color.LightBlue, ">> "); printf(format ++ "...", args); } //// // Signal that a loading step completed successfully. // pub fn stepOK() void { const ok = " [ OK ]"; alignRight(ok.len); colorPrintf(Color.LightGreen, ok); }
kernel/tty.zig
pub const Video = struct { const VI_BASE = @intToPtr([*]volatile u32, 0xA4400000); pub const VideoStatusFlags = struct { pub const BPP32 = 0x3; pub const INTERLACE = 0x40; pub const AA_MODE_2 = 0x200; }; pub fn setupNtsc(width: u32, height: u32, status: u32, origin: u32) void { // Pulled from https://github.com/PeterLemon/N64/blob/master/CPUTest/CPU/ADD/LIB/N64_GFX.INC VI_BASE[0x0] = status; VI_BASE[0x1] = origin; VI_BASE[0x2] = width; // Vertical interrupt VI_BASE[0x3] = 200; // Current Vertical line (Current Half-line, sampled once per line). VI_BASE[0x4] = 0; // Video Timing (Start Of Color Burst In Pixels from H-Sync = 3, Vertical Sync Width In Half Lines = 229, Color Burst Width In Pixels = 34, Horizontal Sync Width In Pixels = 57) VI_BASE[0x5] = 0x3E52239; // Vertical Sync (Number Of Half-Lines Per Field = 525) VI_BASE[0x6] = 0x20D; // Horizontal Sync (5-bit Leap Pattern Used For PAL only = 0, Total Duration Of A Line In 1/4 Pixel = 3093) VI_BASE[0x7] = 0xC15; // Horizontal Sync Leap (Identical To H Sync = 3093, Identical To H Sync = 3093) VI_BASE[0x8] = 0xC150C15; // Horizontal Video (Start Of Active Video In Screen Pixels = 108, End Of Active Video In Screen Pixels = 748) VI_BASE[0x9] = 0x6C02EC; // Vertical Video (Start Of Active Video In Screen Half-Lines = 37, End Of Active Video In Screen Half-Lines = 511) VI_BASE[0xA] = 0x2501FF; // Vertical Burst (Start Of Color Burst Enable In Half-Lines = 14, End Of Color Burst Enable In Half-Lines = 516) VI_BASE[0xB] = 0xE0204; // X-Scale (Horizontal Subpixel Offset In 2.10 Format = 0, 1/Horizontal Scale Up Factor In 2.10 Format) VI_BASE[0xC] = 100 * width / 160; // Y-Scale (Vertical Subpixel Offset In 2.10 Format = 0, 1/Vertical Scale Up Factor In 2.10 Format) VI_BASE[0xD] = 100 * height / 60; } };
src/video.zig
const std = @import("std"); // const builtin = @import("builtin"); const builtin = std.builtin; const fs = std.fs; const mem = std.mem; const path = fs.path; const ChildProcess = std.ChildProcess; pub const Package = struct { pub const Source = union(enum) { pub const Error = fs.Dir.AccessError || mem.Allocator.Error || ChildProcess.SpawnError || error{Git}; Git: [2][]const u8, Local: []const u8, pub fn getPath(self: Source, allocator: *mem.Allocator, name: []const u8) Error![]const u8 { _ = name; switch (self) { .Local => |file| { try fs.cwd().access(file, .{}); return file; }, .Git => |repo| { // the build system is backed by an arena allocator so leaking mem is fine const out = try path.join(allocator, &[_][]const u8{ "deps", repo[1] }); fs.cwd().access(out, .{}) catch { if (fs.cwd().access(out, .{})) {} else |_| { var git = try ChildProcess.init(&[_][]const u8{ "git", "clone", repo[0], path.dirname(out).? }, allocator); switch (try git.spawnAndWait()) { ChildProcess.Term{ .Exited = 0 } => try fs.cwd().access(out, .{}), else => return error.Git, } } }; return out; }, } } }; pub const Type = enum { Binary, Library }; name: []const u8, source: Source, dependencies: ?[]const Package = null, kind: Type = .Library, install_step: ?fn (*std.build.Builder) anyerror!void = null, pub fn ensureDeps(self: Package, allocator: *mem.Allocator) Source.Error!void { _ = try self.source.getPath(allocator, self.name); if (self.dependencies) |deps| { for (deps) |dep| { try dep.ensureDeps(allocator); } } } fn addPackages(self: Package, allocator: *mem.Allocator, step: *std.build.LibExeObjStep) !void { if (self.dependencies) |deps| { for (deps) |dep| { step.addPackagePath(dep.name, try dep.source.getPath(allocator, dep.name)); } } } pub fn build(self: Package, b: *std.build.Builder, target: std.zig.CrossTarget, mode: builtin.Mode) !void { try self.ensureDeps(b.allocator); const src_path = try self.source.getPath(b.allocator, self.name); switch (self.kind) { .Binary => { const exe = b.addExecutable(self.name, src_path); try self.addPackages(b.allocator, exe); exe.setBuildMode(mode); exe.setTarget(target); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step(self.name, b.fmt("run {s}", .{self.name})); run_step.dependOn(&run_cmd.step); var main_tests = b.addTest(src_path); try self.addPackages(b.allocator, main_tests); main_tests.setBuildMode(mode); const test_name = b.fmt("test-{s}", .{self.name}); const test_step = b.step(test_name, b.fmt("run tests for {s}", .{self.name})); test_step.dependOn(&main_tests.step); }, .Library => { const lib = b.addStaticLibrary(self.name, src_path); try self.addPackages(b.allocator, lib); lib.setBuildMode(mode); lib.install(); var main_tests = b.addTest(src_path); try self.addPackages(b.allocator, main_tests); main_tests.setBuildMode(mode); const test_name = b.fmt("test-{s}", .{self.name}); const test_step = b.step(test_name, b.fmt("run tests for {s}", .{self.name})); test_step.dependOn(&main_tests.step); }, } if (self.install_step) |step| { try step(b); } } };
build/sys.zig
const os = @import("root").os; const std = @import("std"); const kepler = os.kepler; /// InterruptObject is a source of interrupts of some kind /// InterruptObject will typically be embedded in the other /// object that contains info about the interrupt vector like /// gsi vector etc (depends on the interrupt source) /// To create InterruptObject, two callback fields /// unlink() and dispose() should be set. /// NOTE: InterruptObject is strictly thread local /// and assumes that raise() is called from the /// thread owning queue. /// NOTE: After unlink() was called, raise() /// can no longer be called pub const InterruptObject = struct { /// Unlink function pointer /// Called when owner of InterruptObject unsubscribes /// from further interrupt notifications. Called /// with interrupts disabled unlink: fn (*@This()) void, /// Dispose function pointer. /// Allows interrupt controller driver to free /// InterruptObject along with all other things dispose: fn (*@This()) void, /// Set to true if owner has unsubscribed from /// interrupt source dying: bool, /// Set to true if note was sent sent: bool, /// Note that is sent on InterruptRaised event note: kepler.ipc.Note, /// Target queue queue: *kepler.ipc.NoteQueue, /// Init method. Queue reference is borrowed pub fn init(self: *@This(), queue: *kepler.ipc.NoteQueue, unlink: fn (*@This()) void, dispose: fn (*@This()) void) void { self.dying = false; self.sent = false; self.queue = queue.borrow(); self.unlink = unlink; self.dispose = dispose; } /// Raise method. Called from interrupt handler pub fn raise(self: *@This()) void { std.debug.assert(!self.dying); // If note is already sent, no need to resend if (@atomicLoad(bool, &self.sent, .Unordered)) { return; } // Fill out note fields self.note.typ = .InterruptRaised; self.note.owner_ref = .{ .interrupt = self }; // Try sending note @atomicStore(bool, &self.sent, true, .Unordered); self.queue.send(&self.note) catch { // Queue could not be shut down, as object is not dying // and hence thread was not yet terminated => it's // queue has not been destroyed yet. @panic("Failed to sent note from interrupt handler"); }; } /// Drop owning reference. Calls unlink() pub fn shutdown(self: *@This()) void { const state = os.platform.get_and_disable_interrupts(); self.dying = true; self.unlink(self); os.platform.set_interrupts(state); if (!@atomicLoad(bool, &self.sent, .Unordered)) { self.queue.drop(); self.dispose(self); } } /// Drop non-owning reference (from note) pub fn drop(self: *@This()) void { if (self.dying) { self.queue.drop(); self.dispose(self); } else { @atomicStore(bool, &self.sent, true, .Unordered); } } /// Returns true if object is still subscribed /// to interrupt notifications pub fn is_active(self: *@This()) bool { return !self.dying; } };
src/kepler/interrupts.zig
const std = @import("std"); const warn = std.debug.warn; const ZigParser = @import("zig/zig_parser.zig").Parser; const ZigNode = @import("zig/zig_parser.zig").Node; const Uri = @import("uri.zig"); usingnamespace @import("json/json.zig"); usingnamespace @import("errors.zig"); const allocator = std.heap.c_allocator; var stdout_file: std.fs.File = undefined; var stdout: std.fs.File.OutStream = undefined; const initialize_response = \\,"jsonrpc":"2.0","result":{"capabilities":{"signatureHelpProvider":{"triggerCharacters":["(",","]},"textDocumentSync":1,"completionProvider":{"resolveProvider":false,"triggerCharacters":[".",":"]},"documentHighlightProvider":false,"codeActionProvider":false,"workspace":{"workspaceFolders":{"supported":true}}}}} ; const error_response = \\,"jsonrpc":"2.0","error":{"code":-32601,"message":"NotImplemented"}} ; const null_result_response = \\,"jsonrpc":"2.0","result":null} ; const empty_result_response = \\,"jsonrpc":"2.0","result":{}} ; const empty_array_response = \\,"jsonrpc":"2.0","result":[]} ; const edit_not_applied_response = \\,"jsonrpc":"2.0","result":{"applied":false,"failureReason":"feature not implemented"}} ; const no_completions_response = \\,"jsonrpc":"2.0","result":{"isIncomplete":false,"items":[]}} ; fn processSource(uri: []const u8, version: usize, source: []const u8) !void { var parser = try ZigParser.init(std.heap.c_allocator); defer parser.deinit(); // TODO: semantic analysis if parser succeeds _ = try parser.run(source); // try debug.stream.print("parsed {} v.{}\n", uri, version); var buffer = try std.Buffer.initSize(std.heap.c_allocator, 0); defer buffer.deinit(); var stream = &std.io.BufferOutStream.init(&buffer).stream; try stream.write( \\{"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{"uri": ); try stream.print("\"{}\",\"diagnostics\":[", uri); if (parser.engine.errors.len > 0) { var count: usize = 0; var eit = parser.engine.errors.iterator(0); // Diagnostic: { range, severity?: number, code?: number|string, source?: string, message: string, relatedInformation?: ... } while (eit.next()) |err| { try stream.write( \\{"range":{"start":{ ); try stream.print("\"line\":{},\"character\":{}", err.line - 1, err.start - 1); try stream.write( \\},"end":{ ); try stream.print("\"line\":{},\"character\":{}", err.line - 1, err.end); try stream.write( \\}},"severity":1,"source":"zig-lsp","message": ); try stream.print("\"{}\",\"code\":\"{}\"", parseErrorToString(err.info), @tagName(err.info)); try stream.write( \\,"relatedInformation":[]}, ); // try debug.stream.print("{}\n", err); } buffer.list.len -= 1; } try stream.write( \\]}} ); try stdout.stream.print("Content-Length: {}\r\n\r\n", buffer.len()); try stdout.stream.write(buffer.toSlice()); } fn sendGenericRpcResponse(rpc_id: usize, response: []const u8) !bool { const rpc_id_digits = blk: { if (rpc_id == 0) break :blk 1; var digits: usize = 1; var value = rpc_id / 10; while (value != 0) : (value /= 10) { digits += 1; } break :blk digits; }; try stdout.stream.print("Content-Length: {}\r\n\r\n{}\"id\":{}", response.len + rpc_id_digits + 6, "{", rpc_id); try stdout.stream.write(response); return true; } fn processJsonRpc(jsonrpc: Json) !bool { const root = jsonrpc.root; // Verify version const rpc_version = root.v("jsonrpc").s("").?; if (std.mem.compare(u8, "2.0", rpc_version) != .Equal) return error.WrongVersion; // Get method const rpc_method = root.v("method").s("").?; // Get ID const rpc_maybe_id = root.v("id").u(null); const rpc_id = rpc_maybe_id orelse 0; // Get Params const rpc_params = root.v("params"); // Process some methods if (std.mem.compare(u8, "textDocument/didOpen", rpc_method) == .Equal) { // Notification // textDocument: TextDocumentItem{ uri: string, languageId: string, version: number, text: string } const document = rpc_params.v("textDocument"); const uri = document.v("uri").s("").?; const lang = document.v("languageId").s("").?; const version = document.v("version").u(0).?; const text = document.v("text").s("").?; const path = try Uri.parse(allocator, uri); defer allocator.free(path); try processSource(uri, version, text); return true; } else if (std.mem.compare(u8, "textDocument/didChange", rpc_method) == .Equal) { // Notification // textDocument: VersionedTextDocumentIdentifier{ uri: string, version: number|null } // contentChanges[ { range?: { start: Position{ line: number, character:number }, end: Position{} }, rangeLength?: number, text: string } ] const document = rpc_params.v("textDocument"); const uri = document.v("uri").s("").?; const version = document.v("version").u(0).?; const change = rpc_params.v("contentChanges").at(0); const start = change.v("range").v("start"); // const changed_line = start.v("line").u(null); // const changed_char = start.v("character").u(0).?; const text = change.v("text").s("").?; try processSource(uri, version, text); return true; } else if (std.mem.compare(u8, "textDocument/didSave", rpc_method) == .Equal) { // Notification // textDocument: TextDocumentIdentifier{ uri: string } // text?: string const uri = rpc_params.v("textDocument").v("uri").s("").?; const text = rpc_params.v("text").s("").?; // try processSource(uri, 0, text); return true; } else if (std.mem.compare(u8, "textDocument/didClose", rpc_method) == .Equal) { // Notification // textDocument: TextDocumentIdentifier{ uri: string } const uri = rpc_params.v("textDocument").v("uri").s("").?; return true; } else if (std.mem.compare(u8, "textDocument/completion", rpc_method) == .Equal) { // textDocument: TextDocumentIdentifier{ uri: string } // position: Position{ line: number, character:number } // context?: CompletionContext { not very important } const uri = rpc_params.v("textDocument").v("uri").s("").?; const position = rpc_params.v("position"); const iline = position.v("line").i(-1).?; const icharacter = position.v("character").i(-1).?; if (uri.len > 0 and iline >= 0 and icharacter >= 0) { const line = @bitCast(u64, iline); const character = @bitCast(u64, icharacter); } return try sendGenericRpcResponse(rpc_id, no_completions_response); } else if (std.mem.compare(u8, "textDocument/signatureHelp", rpc_method) == .Equal) { // Request // textDocument: TextDocumentIdentifier{ uri: string } // position: Position{ line: number, character:number } return try sendGenericRpcResponse(rpc_id, empty_array_response); } else if (std.mem.compare(u8, "textDocument/willSave", rpc_method) == .Equal) { // Notification // textDocument: TextDocumentIdentifier{ uri: string } // reason: number (Manual=1, AfterDelay=2, FocusOut=3) return true; } else if (std.mem.compare(u8, "textDocument/willSaveWaitUntil", rpc_method) == .Equal) { // Request // textDocument: TextDocumentIdentifier{ uri: string } // reason: number (Manual=1, AfterDelay=2, FocusOut=3) return try sendGenericRpcResponse(rpc_id, empty_array_response); } else if (std.mem.compare(u8, "initialize", rpc_method) == .Equal) { // Request // processId: number|null // rootPath?: string|null (deprecated) // rootUri: DocumentUri{} | null // initializeOptions?: any // capabilities: ClientCapabilities{ ... } // trace: 'off'|'messages'|'verbose' (defaults to off) // workspaceFolders: WorkspaceFolder[]|null const rootUri = rpc_params.v("rootUri").s(rpc_params.v("rootPath").s(null)); return try sendGenericRpcResponse(rpc_id, initialize_response); } else if (std.mem.compare(u8, "initialized", rpc_method) == .Equal) { // Notification // params: empty return true; } else if (std.mem.compare(u8, "shutdown", rpc_method) == .Equal) { // Request // params: void return try sendGenericRpcResponse(rpc_id, null_result_response); } else if (std.mem.compare(u8, "exit", rpc_method) == .Equal) { // Notification // params: void return false; } else if (std.mem.compare(u8, "$/cancelRequest", rpc_method) == .Equal) { // Notification // id: number|string return true; } else if (std.mem.compare(u8, "workspace/didChangeWorkspaceFolders", rpc_method) == .Equal) { // Notification return true; } else if (std.mem.compare(u8, "workspace/didChangeConfiguration", rpc_method) == .Equal) { // Notification return true; } else if (std.mem.compare(u8, "workspace/didChangeWatchedFiles", rpc_method) == .Equal) { // Notification return true; } else if (std.mem.compare(u8, "workspace/symbol", rpc_method) == .Equal) { // Request return try sendGenericRpcResponse(rpc_id, null_result_response); } else if (std.mem.compare(u8, "workspace/executeCommand", rpc_method) == .Equal) { // Request return try sendGenericRpcResponse(rpc_id, null_result_response); } else if (std.mem.compare(u8, "workspace/applyEdit", rpc_method) == .Equal) { // Request return try sendGenericRpcResponse(rpc_id, edit_not_applied_response); } // Only requests need a response if (rpc_maybe_id) |_| { _ = try sendGenericRpcResponse(rpc_id, error_response); } return true; } fn event_loop() !void { var buffer = std.ArrayList(u8).init(allocator); defer buffer.deinit(); try buffer.resize(4096); const stdin = std.io.getStdIn(); stdout_file = std.io.getStdOut(); stdout = stdout_file.outStream(); var bytes_read: usize = 0; var offset: usize = 0; stdin_poll: while (true) { var body_len: usize = 0; var index: usize = 0; if (offset >= 21 and std.mem.compare(u8, "Content-Length: ", buffer.items[0..16]) == .Equal) { index = 16; while (index < offset - 3) : (index += 1) { const c = buffer.items[index]; if (c >= '0' and c <= '9') body_len = body_len * 10 + (c - '0'); if (c == '\r' and buffer.items[index + 1] == '\n') { index += 4; break; } } if (buffer.items[index - 4] == '\r') { if (buffer.len < index + body_len) try buffer.resize(index + body_len); body_poll: while (offset < body_len + index) { bytes_read = stdin.read(buffer.items[offset .. index + body_len]) catch return; if (bytes_read == 0) return; offset += bytes_read; } var json = (try Json.initWithString(allocator, buffer.items[index .. index + body_len])) orelse return; defer json.deinit(); if (!(try processJsonRpc(json))) return; offset = 0; body_len = 0; } } else if (offset >= 21) { return; } if (offset < 21) { bytes_read = stdin.read(buffer.items[offset..21]) catch return; } else { if (offset == buffer.len) try buffer.resize(buffer.len * 2); if (index + body_len > buffer.len) { bytes_read = stdin.read(buffer.items[offset..buffer.len]) catch return; } else { bytes_read = stdin.read(buffer.items[offset .. index + body_len]) catch return; } } if (bytes_read == 0) return; offset += bytes_read; } } pub fn main() void { event_loop() catch return; }
server.zig
const std = @import("std"); const util = @import("util"); const vm = @import("vm.zig"); const input = @embedFile("8.txt"); const Interpreter = vm.Interpreter(input, Mixin); fn Mixin(comptime T: type) type { @setEvalBranchQuota(100 * T.bytecode_init.len); const instr_count = T.bytecode_init.len / 2; comptime var target_instr: []const u32 = &[_]u32{}; comptime { var i = 0; while (i < T.bytecode_init.len) : (i += 2) { if (T.bytecode_init[i] != @enumToInt(vm.Instr.acc)) target_instr = target_instr ++ [_]u32{i}; } } return struct { executed_instr: [instr_count]bool = [_]bool{false} ** instr_count, target_idx: u32 = 0, pub const default_value = @This(){}; pub fn update(self: *T) !bool { const idx = self.index / 2; if (idx >= instr_count) return false; if (self.mixin.executed_instr[idx]) return error.InfiniteLoop; self.mixin.executed_instr[idx] = true; return true; } pub const namespace = struct { pub fn runUntilLoop(self: *T) !void { while (self.step() catch |err| switch (err) { error.InfiniteLoop => return, else => return err, }) {} return; } pub fn runNewState(self: *T) !bool { const target_idx = self.mixin.target_idx; try util.expect(target_idx < target_instr.len); self.accum = 0; self.index = 0; self.mixin = .{ .target_idx = target_idx }; swapInstr(&self.bytecode[target_instr[target_idx]]); defer swapInstr(&self.bytecode[target_instr[target_idx]]); defer self.mixin.target_idx += 1; while (self.step() catch |err| switch (err) { error.InfiniteLoop => return true, else => return err, }) {} return false; } }; fn swapInstr(target: *u32) void { target.* = switch (target.*) { @enumToInt(vm.Instr.jmp) => @enumToInt(vm.Instr.nop), @enumToInt(vm.Instr.nop) => @enumToInt(vm.Instr.jmp), else => unreachable, }; } }; } pub fn main(n: util.Utils) !void { var interpreter = Interpreter{}; try interpreter.runUntilLoop(); const part_1 = interpreter.accum; while (try interpreter.runNewState()) {} const part_2 = interpreter.accum; try n.out.print("{}\n{}\n", .{part_1, part_2}); }
2020/8.zig
const std = @import("std"); const math = std.math; const max = math.max; const min = math.min; const abs = math.fabs; const hypot = math.hypot; const ln = math.ln; const exp = math.exp; const floor = math.floor; const ceil = math.ceil; const pi: f64 = math.pi; const tau: f64 = 6.28318530717958647; const sqrt3: f64 = 1.73205080756887729; const invSqrt2: f64 = 0.70710678118654752; const V2 = @import("affine.zig").V2; const v2 = V2.init; const gmath = @import("gmath.zig").gmath(f64); const saturate = gmath.saturate; const clamp = gmath.clamp; const mix = gmath.mix; pub const Sdfn = fn (V2) f64; pub const Model = union(enum) { const Self = @This(); Origin: void, Round: Round, Sdfn: Sdfn, Displace: Model2, pub fn compile(comptime self: Self) Sdfn { return switch (self) { .Origin => Sdf.origin, .Round => |c| Sdf.roundFn(c.sub.compile(), c.r), .Sdfn => |f| f, .Displace => |c| Sdf.displaceFn(c.a.compile(), c.b.compile()), }; } }; pub const Round = struct { r: f64, sub: *const Model, }; pub const Model2 = struct { a: *const Model, b: *const Model, }; pub const Sdf = struct { pub inline fn origin(p: V2) f64 { return p.length(); } //pub fn ellipse(p: V2, ab: V2) f64 { // const q = NearestPoint.ellipse(p, ab); // const d = p.distTo(q); // if (p.lengthSq() < q.lengthSq()) { // return -d; // } else { // return d; // } //} pub fn ellipse(p: V2, ab: V2) f64 { const pAbs = p.abs(); const a = ab.x; const b = ab.y; const ai = 1 / a; const bi = 1 / b; const eab = v2((a * a - b * b) * ai, (b * b - a * a) * bi); var t = v2(invSqrt2, invSqrt2); for ([_]usize{ 0, 1, 2 }) |i| { const e = v2(t.x * t.x * t.x, t.y * t.y * t.y).mul(eab); const q = pAbs.sub(e); const u = q.normalize().scale(t.mul(ab).sub(e).length()); t = v2(saturate((e.x + u.x) * ai), saturate((e.y + u.y) * bi)).normalize(); } const nearestAbs = t.mul(ab); const dist = pAbs.distTo(nearestAbs); return if (pAbs.lengthSq() < nearestAbs.lengthSq()) -dist else dist; } pub fn roundFn(comptime sub: Sdfn, comptime r: f64) Sdfn { const compiler = struct { inline fn round(p: V2) f64 { return Dist.round(sub(p), r); } }; return compiler.round; } pub fn displaceFn(comptime f: Sdfn, comptime g: Sdfn) Sdfn { const compiler = struct { inline fn displace(p: V2) f64 { return Dist.displace(f(p), g(p)); } }; return compiler.displace; } }; pub const NearestPoint = struct { pub fn ellipse(p: V2, ab: V2) V2 { const pAbs = p.abs(); const a = ab.x; const b = ab.y; const ai = 1 / a; const bi = 1 / b; const ea = (a * a - b * b) * ai; const eb = (b * b - a * a) * bi; var t = v2(invSqrt2, invSqrt2); for ([_]usize{ 0, 1, 2 }) |i| { const e = v2(ea * t.x * t.x * t.x, eb * t.y * t.y * t.y); const q = pAbs.sub(e); const u = q.normalize().scale(t.mul(ab).sub(e).length()); t = v2(saturate((e.x + u.x) * ai), saturate((e.y + u.y) * bi)).normalize(); } const nearestAbs = t.mul(ab); const nearest = V2{ .x = math.copysign(f64, nearestAbs.x, p.x), .y = math.copysign(f64, nearestAbs.y, p.y), }; return nearest; } }; pub const Sd = struct { d: f64, const Self = @This(); pub fn init(d: f64) Self { return .{ .d = d }; } pub fn invert(self: Self) Self { return init(Dist.invert(self.d)); } pub fn edge(self: Self) Self { return init(Dist.edge(self.d)); } pub fn round(self: Self, r: f64) Self { return init(Dist.round(self.d, r)); } pub fn annular(self: Self, r: f64) Self { return init(Dist.annular(self.d, r)); } pub fn annular2(self: Self, r: f64) Self { return init(Dist.annular2(self.d, r)); } pub fn displace(self: Self, other: Self) Self { return init(Dist.displace(self.d, other.d)); } pub fn merge(self: Self, other: Self) Self { return init(Dist.merge(self.d, other.d)); } pub fn match(self: Self, other: Self) Self { return init(Dist.match(self.d, other.d)); } pub fn cut(self: Self, other: Self) Self { return init(Dist.cut(self.d, other.d)); } pub fn overlay(self: Self, other: Self) Self { return init(Dist.overlay(self.d, other.d)); } pub fn smoothstepC1(self: Self, e0: f64, e1: f64) f64 { return gmath.smoothstepC1(e0, e1, self.d); } pub fn smoothstepC2(self: Self, e0: f64, e1: f64) f64 { return gmath.smoothstepC2(e0, e1, self.d); } pub fn smoothstepC3(self: Self, e0: f64, e1: f64) f64 { return gmath.smoothstepC3(e0, e1, self.d); } pub fn step(self: Self, e: f64) f64 { return gmath.step(e, self.d); } pub fn coStep(self: Self, e: f64) f64 { return gmath.coStep(e, self.d); } }; pub const Dist = struct { pub inline fn invert(d: f64) f64 { return -d; } pub inline fn edge(d: f64) f64 { return abs(d); } pub inline fn round(d: f64, r: f64) f64 { return d - r; } pub inline fn annular(d: f64, r: f64) f64 { return round(edge(d), r); //return abs(d) - r; } pub inline fn annular2(d: f64, r: f64) f64 { return annular(annular(d, r + r), r); //return round(edge(round(edge(d), r + r)), r); //return abs(abs(d) - r - r) - r; } pub inline fn displace(a: f64, b: f64) f64 { return a + b; } pub inline fn merge(d1: f64, d2: f64) f64 { return math.min(d1, d2); } pub inline fn match(d1: f64, d2: f64) f64 { return math.max(d1, d2); } pub inline fn cut(d1: f64, d2: f64) f64 { return match(d1, invert(d2)); } pub inline fn overlay(d1: f64, d2: f64) f64 { return if (d1 < 0 and d2 < 0) -math.max(-d2, -d1) else if (d1 < 0) d1 else if (d2 < 0) d2 else math.min(d1, d2); } }; pub fn rayMarch(ro: V2, rd: V2, comptime model: Sdfn) ?Marched { const stepLimit: usize = 256; const closeEnough: f64 = 0.001; const maxT: f64 = 1000; var t: f64 = 0; var step: usize = 0; while (step < stepLimit and t < maxT) : (step += 1) { const pos = rd.scale(t).add(ro); const d = model(pos); if (d < closeEnough) { return Marched{ .d = d, .pos = pos, }; } t += d * 0.95; } return null; } pub const Marched = struct { d: f64, pos: V2, }; pub fn normal(p: V2, comptime model: Sdfn) V2 { const e = 0.00001; return v2( model(v2(p.x + e, p.y)) - model(v2(p.x - e, p.y)), model(v2(p.x, p.y + e)) - model(v2(p.x, p.y - e)), ).normalize(); }
lib/sdf2.zig
const std = @import("std"); const mem = std.mem; const fs = std.fs; const Step = std.build.Step; const Builder = std.build.Builder; /// ScdocStep generates man pages using scdoc(1). /// /// It reads all the raw pages from src_path and writes them to out_path. /// src_path is typically "doc/" relative to the build root and out_path is /// the build cache. /// /// The man pages can be installed by calling install() on the step. const ScdocStep = @This(); step: Step, builder: *Builder, /// path to read man page sources from, defaults to the "doc/" subdirectory /// from the build.zig file. This must be an absolute path. src_path: []const u8, /// path where the generated man pages will be written (NOT installed). This /// defaults to build cache root. out_path: []const u8, pub fn create(builder: *Builder) *ScdocStep { const self = builder.allocator.create(ScdocStep) catch unreachable; self.* = init(builder); return self; } pub fn init(builder: *Builder) ScdocStep { return ScdocStep{ .builder = builder, .step = Step.init(.custom, "generate man pages", builder.allocator, make), .src_path = builder.pathFromRoot("doc/"), .out_path = fs.path.join(builder.allocator, &[_][]const u8{ builder.cache_root, "man", }) catch unreachable, }; } fn make(step: *std.build.Step) !void { const self = @fieldParentPtr(ScdocStep, "step", step); // Create our cache path // TODO(mitchellh): ideally this would be pure zig { const command = try std.fmt.allocPrint( self.builder.allocator, "rm -f {[path]s}/* && mkdir -p {[path]s}", .{ .path = self.out_path }, ); _ = try self.builder.exec(&[_][]const u8{ "sh", "-c", command }); } // Find all our man pages which are in our src path ending with ".scd". var dir = try fs.openDirAbsolute(self.src_path, .{ .iterate = true, }); defer dir.close(); var iter = dir.iterate(); while (try iter.next()) |*entry| { // We only want "scd" files to generate. if (!mem.eql(u8, fs.path.extension(entry.name), ".scd")) { continue; } const src = try fs.path.join( self.builder.allocator, &[_][]const u8{ self.src_path, entry.name }, ); const dst = try fs.path.join( self.builder.allocator, &[_][]const u8{ self.out_path, entry.name[0..(entry.name.len - 4)] }, ); const command = try std.fmt.allocPrint( self.builder.allocator, "scdoc < {s} > {s}", .{ src, dst }, ); _ = try self.builder.exec(&[_][]const u8{ "sh", "-c", command }); } } pub fn install(self: *ScdocStep) !void { // Ensure that `zig build install` depends on our generation step first. self.builder.getInstallStep().dependOn(&self.step); // Then run our install step which looks at what we made out of our // generation and moves it to the install prefix. const install_step = InstallStep.create(self.builder, self); self.builder.getInstallStep().dependOn(&install_step.step); } /// Install man pages, create using install() on ScdocStep. const InstallStep = struct { step: Step, builder: *Builder, scdoc: *ScdocStep, pub fn create(builder: *Builder, scdoc: *ScdocStep) *InstallStep { const self = builder.allocator.create(InstallStep) catch unreachable; self.* = InstallStep.init(builder, scdoc); return self; } pub fn init(builder: *Builder, scdoc: *ScdocStep) InstallStep { return InstallStep{ .builder = builder, .step = Step.init(.custom, "generate man pages", builder.allocator, InstallStep.make), .scdoc = scdoc, }; } fn make(step: *Step) !void { const self = @fieldParentPtr(InstallStep, "step", step); // Get our absolute output path var path = self.scdoc.out_path; if (!fs.path.isAbsolute(path)) { path = self.builder.pathFromRoot(path); } // Find all our man pages which are in our src path ending with ".scd". var dir = try fs.openDirAbsolute(path, .{ .iterate = true }); defer dir.close(); var iter = dir.iterate(); while (try iter.next()) |*entry| { // We expect filenames to be "foo.3" and this gets us "3" const section = entry.name[(entry.name.len - 1)..]; const src = try fs.path.join( self.builder.allocator, &[_][]const u8{ path, entry.name }, ); const output = try std.fmt.allocPrint( self.builder.allocator, "share/man/man{s}/{s}", .{ section, entry.name }, ); const fileStep = self.builder.addInstallFile( .{ .path = src }, output, ); try fileStep.step.make(); } } };
src-build/ScdocStep.zig
const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; const maxInt = std.math.maxInt; test "@bitCast i32 -> u32" { testBitCast_i32_u32(); comptime testBitCast_i32_u32(); } fn testBitCast_i32_u32() void { expect(conv(-1) == maxInt(u32)); expect(conv2(maxInt(u32)) == -1); } fn conv(x: i32) u32 { return @bitCast(u32, x); } fn conv2(x: u32) i32 { return @bitCast(i32, x); } test "@bitCast extern enum to its integer type" { const SOCK = extern enum { A, B, fn testBitCastExternEnum() void { var SOCK_DGRAM = @This().B; var sock_dgram = @bitCast(c_int, SOCK_DGRAM); expect(sock_dgram == 1); } }; SOCK.testBitCastExternEnum(); comptime SOCK.testBitCastExternEnum(); } test "@bitCast packed structs at runtime and comptime" { const Full = packed struct { number: u16, }; const Divided = packed struct { half1: u8, quarter3: u4, quarter4: u4, }; const S = struct { fn doTheTest() void { var full = Full{ .number = 0x1234 }; var two_halves = @bitCast(Divided, full); switch (builtin.endian) { builtin.Endian.Big => { expect(two_halves.half1 == 0x12); expect(two_halves.quarter3 == 0x3); expect(two_halves.quarter4 == 0x4); }, builtin.Endian.Little => { expect(two_halves.half1 == 0x34); expect(two_halves.quarter3 == 0x2); expect(two_halves.quarter4 == 0x1); }, } } }; S.doTheTest(); comptime S.doTheTest(); } test "@bitCast extern structs at runtime and comptime" { const Full = extern struct { number: u16, }; const TwoHalves = extern struct { half1: u8, half2: u8, }; const S = struct { fn doTheTest() void { var full = Full{ .number = 0x1234 }; var two_halves = @bitCast(TwoHalves, full); switch (builtin.endian) { builtin.Endian.Big => { expect(two_halves.half1 == 0x12); expect(two_halves.half2 == 0x34); }, builtin.Endian.Little => { expect(two_halves.half1 == 0x34); expect(two_halves.half2 == 0x12); }, } } }; S.doTheTest(); comptime S.doTheTest(); } test "bitcast packed struct to integer and back" { const LevelUpMove = packed struct { move_id: u9, level: u7, }; const S = struct { fn doTheTest() void { var move = LevelUpMove{ .move_id = 1, .level = 2 }; var v = @bitCast(u16, move); var back_to_a_move = @bitCast(LevelUpMove, v); expect(back_to_a_move.move_id == 1); expect(back_to_a_move.level == 2); } }; S.doTheTest(); comptime S.doTheTest(); } test "implicit cast to error union by returning" { const S = struct { fn entry() void { expect((func(-1) catch unreachable) == maxInt(u64)); } pub fn func(sz: i64) anyerror!u64 { return @bitCast(u64, sz); } }; S.entry(); comptime S.entry(); } // issue #3010: compiler segfault test "bitcast literal [4]u8 param to u32" { const ip = @bitCast(u32, [_]u8{ 255, 255, 255, 255 }); expect(ip == maxInt(u32)); } test "bitcast packed struct literal to byte" { const Foo = packed struct { value: u8, }; const casted = @bitCast(u8, Foo{ .value = 0xF }); expect(casted == 0xf); } test "comptime bitcast used in expression has the correct type" { const Foo = packed struct { value: u8, }; expect(@bitCast(u8, Foo{ .value = 0xF }) == 0xf); } test "bitcast result to _" { _ = @bitCast(u8, @as(i8, 1)); }
test/stage1/behavior/bitcast.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const mem = std.mem; const builtin = @import("builtin"); const maxInt = std.math.maxInt; // normal comment /// this is a documentation comment /// doc comment line 2 fn emptyFunctionWithComments() void {} test "empty function with comments" { emptyFunctionWithComments(); } comptime { @export(disabledExternFn, .{ .name = "disabledExternFn", .linkage = .Internal }); } fn disabledExternFn() callconv(.C) void {} test "call disabled extern fn" { disabledExternFn(); } test "@IntType builtin" { expect(@IntType(true, 8) == i8); expect(@IntType(true, 16) == i16); expect(@IntType(true, 32) == i32); expect(@IntType(true, 64) == i64); expect(@IntType(false, 8) == u8); expect(@IntType(false, 16) == u16); expect(@IntType(false, 32) == u32); expect(@IntType(false, 64) == u64); expect(i8.bit_count == 8); expect(i16.bit_count == 16); expect(i32.bit_count == 32); expect(i64.bit_count == 64); expect(i8.is_signed); expect(i16.is_signed); expect(i32.is_signed); expect(i64.is_signed); expect(isize.is_signed); expect(!u8.is_signed); expect(!u16.is_signed); expect(!u32.is_signed); expect(!u64.is_signed); expect(!usize.is_signed); } test "floating point primitive bit counts" { expect(f16.bit_count == 16); expect(f32.bit_count == 32); expect(f64.bit_count == 64); } test "short circuit" { testShortCircuit(false, true); comptime testShortCircuit(false, true); } fn testShortCircuit(f: bool, t: bool) void { var hit_1 = f; var hit_2 = f; var hit_3 = f; var hit_4 = f; if (t or x: { expect(f); break :x f; }) { hit_1 = t; } if (f or x: { hit_2 = t; break :x f; }) { expect(f); } if (t and x: { hit_3 = t; break :x f; }) { expect(f); } if (f and x: { expect(f); break :x f; }) { expect(f); } else { hit_4 = t; } expect(hit_1); expect(hit_2); expect(hit_3); expect(hit_4); } test "truncate" { expect(testTruncate(0x10fd) == 0xfd); } fn testTruncate(x: u32) u8 { return @truncate(u8, x); } fn first4KeysOfHomeRow() []const u8 { return "aoeu"; } test "return string from function" { expect(mem.eql(u8, first4KeysOfHomeRow(), "aoeu")); } const g1: i32 = 1233 + 1; var g2: i32 = 0; test "global variables" { expect(g2 == 0); g2 = g1; expect(g2 == 1234); } test "memcpy and memset intrinsics" { var foo: [20]u8 = undefined; var bar: [20]u8 = undefined; @memset(foo[0..].ptr, 'A', foo.len); @memcpy(bar[0..].ptr, foo[0..].ptr, bar.len); if (bar[11] != 'A') unreachable; } test "builtin static eval" { const x: i32 = comptime x: { break :x 1 + 2 + 3; }; expect(x == comptime 6); } test "slicing" { var array: [20]i32 = undefined; array[5] = 1234; var slice = array[5..10]; if (slice.len != 5) unreachable; const ptr = &slice[0]; if (ptr.* != 1234) unreachable; var slice_rest = array[10..]; if (slice_rest.len != 10) unreachable; } test "constant equal function pointers" { const alias = emptyFn; expect(comptime x: { break :x emptyFn == alias; }); } fn emptyFn() void {} test "hex escape" { expect(mem.eql(u8, "\x68\x65\x6c\x6c\x6f", "hello")); } test "string concatenation" { expect(mem.eql(u8, "OK" ++ " IT " ++ "WORKED", "OK IT WORKED")); } test "array mult operator" { expect(mem.eql(u8, "ab" ** 5, "ababababab")); } test "string escapes" { expect(mem.eql(u8, "\"", "\x22")); expect(mem.eql(u8, "\'", "\x27")); expect(mem.eql(u8, "\n", "\x0a")); expect(mem.eql(u8, "\r", "\x0d")); expect(mem.eql(u8, "\t", "\x09")); expect(mem.eql(u8, "\\", "\x5c")); expect(mem.eql(u8, "\u{1234}\u{069}\u{1}", "\xe1\x88\xb4\x69\x01")); } test "multiline string" { const s1 = \\one \\two) \\three ; const s2 = "one\ntwo)\nthree"; expect(mem.eql(u8, s1, s2)); } test "multiline C string" { const s1 = \\one \\two) \\three ; const s2 = "one\ntwo)\nthree"; expect(std.cstr.cmp(s1, s2) == 0); } test "type equality" { expect(*const u8 != *u8); } const global_a: i32 = 1234; const global_b: *const i32 = &global_a; const global_c: *const f32 = @ptrCast(*const f32, global_b); test "compile time global reinterpret" { const d = @ptrCast(*const i32, global_c); expect(d.* == 1234); } test "explicit cast maybe pointers" { const a: ?*i32 = undefined; const b: ?*f32 = @ptrCast(?*f32, a); } test "generic malloc free" { const a = memAlloc(u8, 10) catch unreachable; memFree(u8, a); } var some_mem: [100]u8 = undefined; fn memAlloc(comptime T: type, n: usize) anyerror![]T { return @ptrCast([*]T, &some_mem[0])[0..n]; } fn memFree(comptime T: type, memory: []T) void {} test "cast undefined" { const array: [100]u8 = undefined; const slice = @as([]const u8, &array); testCastUndefined(slice); } fn testCastUndefined(x: []const u8) void {} test "cast small unsigned to larger signed" { expect(castSmallUnsignedToLargerSigned1(200) == @as(i16, 200)); expect(castSmallUnsignedToLargerSigned2(9999) == @as(i64, 9999)); } fn castSmallUnsignedToLargerSigned1(x: u8) i16 { return x; } fn castSmallUnsignedToLargerSigned2(x: u16) i64 { return x; } test "implicit cast after unreachable" { expect(outer() == 1234); } fn inner() i32 { return 1234; } fn outer() i64 { return inner(); } test "pointer dereferencing" { var x = @as(i32, 3); const y = &x; y.* += 1; expect(x == 4); expect(y.* == 4); } test "call result of if else expression" { expect(mem.eql(u8, f2(true), "a")); expect(mem.eql(u8, f2(false), "b")); } fn f2(x: bool) []const u8 { return (if (x) fA else fB)(); } fn fA() []const u8 { return "a"; } fn fB() []const u8 { return "b"; } test "const expression eval handling of variables" { var x = true; while (x) { x = false; } } test "constant enum initialization with differing sizes" { test3_1(test3_foo); test3_2(test3_bar); } const Test3Foo = union(enum) { One: void, Two: f32, Three: Test3Point, }; const Test3Point = struct { x: i32, y: i32, }; const test3_foo = Test3Foo{ .Three = Test3Point{ .x = 3, .y = 4, }, }; const test3_bar = Test3Foo{ .Two = 13 }; fn test3_1(f: Test3Foo) void { switch (f) { Test3Foo.Three => |pt| { expect(pt.x == 3); expect(pt.y == 4); }, else => unreachable, } } fn test3_2(f: Test3Foo) void { switch (f) { Test3Foo.Two => |x| { expect(x == 13); }, else => unreachable, } } test "character literals" { expect('\'' == single_quote); } const single_quote = '\''; test "take address of parameter" { testTakeAddressOfParameter(12.34); } fn testTakeAddressOfParameter(f: f32) void { const f_ptr = &f; expect(f_ptr.* == 12.34); } test "pointer comparison" { const a = @as([]const u8, "a"); const b = &a; expect(ptrEql(b, b)); } fn ptrEql(a: *const []const u8, b: *const []const u8) bool { return a == b; } test "string concatenation" { const a = "OK" ++ " IT " ++ "WORKED"; const b = "OK IT WORKED"; comptime expect(@TypeOf(a) == *const [12:0]u8); comptime expect(@TypeOf(b) == *const [12:0]u8); const len = mem.len(u8, b); const len_with_null = len + 1; { var i: u32 = 0; while (i < len_with_null) : (i += 1) { expect(a[i] == b[i]); } } expect(a[len] == 0); expect(b[len] == 0); } test "cast slice to u8 slice" { expect(@sizeOf(i32) == 4); var big_thing_array = [_]i32{ 1, 2, 3, 4 }; const big_thing_slice: []i32 = big_thing_array[0..]; const bytes = @sliceToBytes(big_thing_slice); expect(bytes.len == 4 * 4); bytes[4] = 0; bytes[5] = 0; bytes[6] = 0; bytes[7] = 0; expect(big_thing_slice[1] == 0); const big_thing_again = @bytesToSlice(i32, bytes); expect(big_thing_again[2] == 3); big_thing_again[2] = -1; expect(bytes[8] == maxInt(u8)); expect(bytes[9] == maxInt(u8)); expect(bytes[10] == maxInt(u8)); expect(bytes[11] == maxInt(u8)); } test "pointer to void return type" { testPointerToVoidReturnType() catch unreachable; } fn testPointerToVoidReturnType() anyerror!void { const a = testPointerToVoidReturnType2(); return a.*; } const test_pointer_to_void_return_type_x = void{}; fn testPointerToVoidReturnType2() *const void { return &test_pointer_to_void_return_type_x; } test "non const ptr to aliased type" { const int = i32; expect(?*int == ?*i32); } test "array 2D const double ptr" { const rect_2d_vertexes = [_][1]f32{ [_]f32{1.0}, [_]f32{2.0}, }; testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } fn testArray2DConstDoublePtr(ptr: *const f32) void { const ptr2 = @ptrCast([*]const f32, ptr); expect(ptr2[0] == 1.0); expect(ptr2[1] == 2.0); } const Tid = builtin.TypeId; const AStruct = struct { x: i32, }; const AnEnum = enum { One, Two, }; const AUnionEnum = union(enum) { One: i32, Two: void, }; const AUnion = union { One: void, Two: void, }; test "@typeId" { comptime { expect(@typeId(type) == Tid.Type); expect(@typeId(void) == Tid.Void); expect(@typeId(bool) == Tid.Bool); expect(@typeId(noreturn) == Tid.NoReturn); expect(@typeId(i8) == Tid.Int); expect(@typeId(u8) == Tid.Int); expect(@typeId(i64) == Tid.Int); expect(@typeId(u64) == Tid.Int); expect(@typeId(f32) == Tid.Float); expect(@typeId(f64) == Tid.Float); expect(@typeId(*f32) == Tid.Pointer); expect(@typeId([2]u8) == Tid.Array); expect(@typeId(AStruct) == Tid.Struct); expect(@typeId(@TypeOf(1)) == Tid.ComptimeInt); expect(@typeId(@TypeOf(1.0)) == Tid.ComptimeFloat); expect(@typeId(@TypeOf(undefined)) == Tid.Undefined); expect(@typeId(@TypeOf(null)) == Tid.Null); expect(@typeId(?i32) == Tid.Optional); expect(@typeId(anyerror!i32) == Tid.ErrorUnion); expect(@typeId(anyerror) == Tid.ErrorSet); expect(@typeId(AnEnum) == Tid.Enum); expect(@typeId(@TypeOf(AUnionEnum.One)) == Tid.Enum); expect(@typeId(AUnionEnum) == Tid.Union); expect(@typeId(AUnion) == Tid.Union); expect(@typeId(fn () void) == Tid.Fn); expect(@typeId(@TypeOf(builtin)) == Tid.Type); // TODO bound fn // TODO arg tuple // TODO opaque } } test "@typeName" { const Struct = struct {}; const Union = union { unused: u8, }; const Enum = enum { Unused, }; comptime { expect(mem.eql(u8, @typeName(i64), "i64")); expect(mem.eql(u8, @typeName(*usize), "*usize")); // https://github.com/ziglang/zig/issues/675 expect(mem.eql(u8, "behavior.misc.TypeFromFn(u8)", @typeName(TypeFromFn(u8)))); expect(mem.eql(u8, @typeName(Struct), "Struct")); expect(mem.eql(u8, @typeName(Union), "Union")); expect(mem.eql(u8, @typeName(Enum), "Enum")); } } fn TypeFromFn(comptime T: type) type { return struct {}; } test "double implicit cast in same expression" { var x = @as(i32, @as(u16, nine())); expect(x == 9); } fn nine() u8 { return 9; } test "global variable initialized to global variable array element" { expect(global_ptr == &gdt[0]); } const GDTEntry = struct { field: i32, }; var gdt = [_]GDTEntry{ GDTEntry{ .field = 1 }, GDTEntry{ .field = 2 }, }; var global_ptr = &gdt[0]; // can't really run this test but we can make sure it has no compile error // and generates code const vram = @intToPtr([*]volatile u8, 0x20000000)[0..0x8000]; export fn writeToVRam() void { vram[0] = 'X'; } const OpaqueA = @OpaqueType(); const OpaqueB = @OpaqueType(); test "@OpaqueType" { expect(*OpaqueA != *OpaqueB); expect(mem.eql(u8, @typeName(OpaqueA), "OpaqueA")); expect(mem.eql(u8, @typeName(OpaqueB), "OpaqueB")); } test "variable is allowed to be a pointer to an opaque type" { var x: i32 = 1234; _ = hereIsAnOpaqueType(@ptrCast(*OpaqueA, &x)); } fn hereIsAnOpaqueType(ptr: *OpaqueA) *OpaqueA { var a = ptr; return a; } test "comptime if inside runtime while which unconditionally breaks" { testComptimeIfInsideRuntimeWhileWhichUnconditionallyBreaks(true); comptime testComptimeIfInsideRuntimeWhileWhichUnconditionallyBreaks(true); } fn testComptimeIfInsideRuntimeWhileWhichUnconditionallyBreaks(cond: bool) void { while (cond) { if (false) {} break; } } test "implicit comptime while" { while (false) { @compileError("bad"); } } fn fnThatClosesOverLocalConst() type { const c = 1; return struct { fn g() i32 { return c; } }; } test "function closes over local const" { const x = fnThatClosesOverLocalConst().g(); expect(x == 1); } test "cold function" { thisIsAColdFn(); comptime thisIsAColdFn(); } fn thisIsAColdFn() void { @setCold(true); } const PackedStruct = packed struct { a: u8, b: u8, }; const PackedUnion = packed union { a: u8, b: u32, }; const PackedEnum = packed enum { A, B, }; test "packed struct, enum, union parameters in extern function" { testPackedStuff(&(PackedStruct{ .a = 1, .b = 2, }), &(PackedUnion{ .a = 1 }), PackedEnum.A); } export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion, c: PackedEnum) void {} test "slicing zero length array" { const s1 = ""[0..]; const s2 = ([_]u32{})[0..]; expect(s1.len == 0); expect(s2.len == 0); expect(mem.eql(u8, s1, "")); expect(mem.eql(u32, s2, &[_]u32{})); } const addr1 = @ptrCast(*const u8, emptyFn); test "comptime cast fn to ptr" { const addr2 = @ptrCast(*const u8, emptyFn); comptime expect(addr1 == addr2); } test "equality compare fn ptrs" { var a = emptyFn; expect(a == a); } test "self reference through fn ptr field" { const S = struct { const A = struct { f: fn (A) u8, }; fn foo(a: A) u8 { return 12; } }; var a: S.A = undefined; a.f = S.foo; expect(a.f(a) == 12); } test "volatile load and store" { var number: i32 = 1234; const ptr = @as(*volatile i32, &number); ptr.* += 1; expect(ptr.* == 1235); } test "slice string literal has type []const u8" { comptime { expect(@TypeOf("aoeu"[0..]) == []const u8); const array = [_]i32{ 1, 2, 3, 4 }; expect(@TypeOf(array[0..]) == []const i32); } } test "pointer child field" { expect((*u32).Child == u32); } test "struct inside function" { testStructInFn(); comptime testStructInFn(); } fn testStructInFn() void { const BlockKind = u32; const Block = struct { kind: BlockKind, }; var block = Block{ .kind = 1234 }; block.kind += 1; expect(block.kind == 1235); } test "fn call returning scalar optional in equality expression" { expect(getNull() == null); } fn getNull() ?*i32 { return null; } test "thread local variable" { const S = struct { threadlocal var t: i32 = 1234; }; S.t += 1; expect(S.t == 1235); } test "unicode escape in character literal" { var a: u24 = '\u{01f4a9}'; expect(a == 128169); } test "unicode character in character literal" { expect('💩' == 128169); } test "result location zero sized array inside struct field implicit cast to slice" { const E = struct { entries: []u32, }; var foo = E{ .entries = &[_]u32{} }; expect(foo.entries.len == 0); } var global_foo: *i32 = undefined; test "global variable assignment with optional unwrapping with var initialized to undefined" { const S = struct { var data: i32 = 1234; fn foo() ?*i32 { return &data; } }; global_foo = S.foo() orelse { @panic("bad"); }; expect(global_foo.* == 1234); } test "peer result location with typed parent, runtime condition, comptime prongs" { const S = struct { fn doTheTest(arg: i32) i32 { const st = Structy{ .bleh = if (arg == 1) 1 else 1, }; if (st.bleh == 1) return 1234; return 0; } const Structy = struct { bleh: i32, }; }; expect(S.doTheTest(0) == 1234); expect(S.doTheTest(1) == 1234); } test "nested optional field in struct" { const S2 = struct { y: u8, }; const S1 = struct { x: ?S2, }; var s = S1{ .x = S2{ .y = 127 }, }; expect(s.x.?.y == 127); } fn maybe(x: bool) anyerror!?u32 { return switch (x) { true => @as(u32, 42), else => null, }; } test "result location is optional inside error union" { const x = maybe(true) catch unreachable; expect(x.? == 42); } threadlocal var buffer: [11]u8 = undefined; test "pointer to thread local array" { const s = "Hello world"; std.mem.copy(u8, buffer[0..], s); std.testing.expectEqualSlices(u8, buffer[0..], s); }
test/stage1/behavior/misc.zig
const std = @import("std"); const tests = @import("tests.zig"); const nl = std.cstr.line_sep; pub fn addCases(cases: *tests.RunTranslatedCContext) void { cases.add("array initializer", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int a0[4] = {1}; \\ int a1[4] = {1,2,3,4}; \\ int s0 = 0, s1 = 0; \\ for (int i = 0; i < 4; i++) { \\ s0 += a0[i]; \\ s1 += a1[i]; \\ } \\ if (s0 != 1) abort(); \\ if (s1 != 10) abort(); \\} , ""); cases.add("forward declarations", \\#include <stdlib.h> \\int foo(int); \\int foo(int x) { return x + 1; } \\int main(int argc, char **argv) { \\ if (foo(2) != 3) abort(); \\ return 0; \\} , ""); cases.add("typedef and function pointer", \\#include <stdlib.h> \\typedef struct _Foo Foo; \\typedef int Ret; \\typedef int Param; \\struct _Foo { Ret (*func)(Param p); }; \\static Ret add1(Param p) { \\ return p + 1; \\} \\int main(int argc, char **argv) { \\ Foo strct = { .func = add1 }; \\ if (strct.func(16) != 17) abort(); \\ return 0; \\} , ""); cases.add("ternary operator", \\#include <stdlib.h> \\static int cnt = 0; \\int foo() { cnt++; return 42; } \\int main(int argc, char **argv) { \\ short q = 3; \\ signed char z0 = q?:1; \\ if (z0 != 3) abort(); \\ int z1 = 3?:1; \\ if (z1 != 3) abort(); \\ int z2 = foo()?:-1; \\ if (z2 != 42) abort(); \\ if (cnt != 1) abort(); \\ return 0; \\} , ""); cases.add("switch case", \\#include <stdlib.h> \\int lottery(unsigned int x) { \\ switch (x) { \\ case 3: return 0; \\ case -1: return 3; \\ case 8 ... 10: return x; \\ default: return -1; \\ } \\} \\int main(int argc, char **argv) { \\ if (lottery(2) != -1) abort(); \\ if (lottery(3) != 0) abort(); \\ if (lottery(-1) != 3) abort(); \\ if (lottery(9) != 9) abort(); \\ return 0; \\} , ""); cases.add("boolean values and expressions", \\#include <stdlib.h> \\static const _Bool false_val = 0; \\static const _Bool true_val = 1; \\void foo(int x, int y) { \\ _Bool r = x < y; \\ if (!r) abort(); \\ _Bool self = foo; \\ if (self == false_val) abort(); \\ if (((r) ? 'a' : 'b') != 'a') abort(); \\} \\int main(int argc, char **argv) { \\ foo(2, 5); \\ if (false_val == true_val) abort(); \\ return 0; \\} , ""); cases.add("hello world", \\#define _NO_CRT_STDIO_INLINE 1 \\#include <stdio.h> \\int main(int argc, char **argv) { \\ printf("hello, world!\n"); \\ return 0; \\} , "hello, world!" ++ nl); cases.add("anon struct init", \\#include <stdlib.h> \\struct {int a; int b;} x = {1, 2}; \\int main(int argc, char **argv) { \\ x.a += 2; \\ x.b += 1; \\ if (x.a != 3) abort(); \\ if (x.b != 3) abort(); \\ return 0; \\} , ""); cases.add("casting away const and volatile", \\void foo(int *a) {} \\void bar(const int *a) { \\ foo((int *)a); \\} \\void baz(volatile int *a) { \\ foo((int *)a); \\} \\int main(int argc, char **argv) { \\ int a = 0; \\ bar((const int *)&a); \\ baz((volatile int *)&a); \\ return 0; \\} , ""); cases.add("anonymous struct & unions", \\#include <stdlib.h> \\#include <stdint.h> \\static struct { struct { uint16_t x, y; }; } x = { 1 }; \\static struct { union { uint32_t x; uint8_t y; }; } y = { 0x55AA55AA }; \\int main(int argc, char **argv) { \\ if (x.x != 1) abort(); \\ if (x.y != 0) abort(); \\ if (y.x != 0x55AA55AA) abort(); \\ if (y.y != 0xAA) abort(); \\ return 0; \\} , ""); cases.add("array to pointer decay", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ char data[3] = {'a','b','c'}; \\ if (2[data] != data[2]) abort(); \\ if ("abc"[1] != data[1]) abort(); \\ char *as_ptr = data; \\ if (2[as_ptr] != as_ptr[2]) abort(); \\ if ("abc"[1] != as_ptr[1]) abort(); \\ return 0; \\} , ""); cases.add("struct initializer - packed", \\#define _NO_CRT_STDIO_INLINE 1 \\#include <stdint.h> \\#include <stdlib.h> \\struct s {uint8_t x,y; \\ uint32_t z;} __attribute__((packed)) s0 = {1, 2}; \\int main() { \\ /* sizeof nor offsetof currently supported */ \\ if (((intptr_t)&s0.z - (intptr_t)&s0.x) != 2) abort(); \\ return 0; \\} , ""); cases.add("cast signed array index to unsigned", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int a[10], i = 0; \\ a[i] = 0; \\ if (a[i] != 0) abort(); \\ return 0; \\} , ""); cases.add("cast long long array index to unsigned", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ long long a[10], i = 0; \\ a[i] = 0; \\ if (a[i] != 0) abort(); \\ return 0; \\} , ""); cases.add("case boolean expression converted to int", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int value = 1 + 2 * 3 + 4 * 5 + 6 << 7 | 8 == 9; \\ if (value != 4224) abort(); \\ return 0; \\} , ""); cases.add("case boolean expression on left converted to int", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int value = 8 == 9 | 1 + 2 * 3 + 4 * 5 + 6 << 7; \\ if (value != 4224) abort(); \\ return 0; \\} , ""); cases.add("case boolean and operator+ converts bool to int", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int value = (8 == 9) + 3; \\ int value2 = 3 + (8 == 9); \\ if (value != value2) abort(); \\ return 0; \\} , ""); cases.add("case boolean and operator<", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int value = (8 == 9) < 3; \\ if (value == 0) abort(); \\ return 0; \\} , ""); cases.add("case boolean and operator*", \\#include <stdlib.h> \\int main(int argc, char **argv) { \\ int value = (8 == 9) * 3; \\ int value2 = 3 * (9 == 9); \\ if (value != 0) abort(); \\ if (value2 == 0) abort(); \\ return 0; \\} , ""); cases.add("scoped typedef", \\int main(int argc, char **argv) { \\ typedef int Foo; \\ typedef Foo Bar; \\ typedef void (*func)(int); \\ typedef int uint32_t; \\ uint32_t a; \\ Foo i; \\ Bar j; \\ return 0; \\} , ""); cases.add("scoped for loops with shadowing", \\#include <stdlib.h> \\int main() { \\ int count = 0; \\ for (int x = 0; x < 2; x++) \\ for (int x = 0; x < 2; x++) \\ count++; \\ \\ if (count != 4) abort(); \\ return 0; \\} , ""); cases.add("array value type casts properly", \\#include <stdlib.h> \\unsigned int choose[53][10]; \\static int hash_binary(int k) \\{ \\ choose[0][k] = 3; \\ int sum = 0; \\ sum += choose[0][k]; \\ return sum; \\} \\ \\int main() { \\ int s = hash_binary(4); \\ if (s != 3) abort(); \\ return 0; \\} , ""); cases.add("array value type casts properly use +=", \\#include <stdlib.h> \\static int hash_binary(int k) \\{ \\ unsigned int choose[1][1] = {{3}}; \\ int sum = -1; \\ int prev = 0; \\ prev = sum += choose[0][0]; \\ if (sum != 2) abort(); \\ return sum + prev; \\} \\ \\int main() { \\ int x = hash_binary(4); \\ if (x != 4) abort(); \\ return 0; \\} , ""); cases.add("ensure array casts outisde +=", \\#include <stdlib.h> \\static int hash_binary(int k) \\{ \\ unsigned int choose[3] = {1, 2, 3}; \\ int sum = -2; \\ int prev = sum + choose[k]; \\ if (prev != 0) abort(); \\ return sum + prev; \\} \\ \\int main() { \\ int x = hash_binary(1); \\ if (x != -2) abort(); \\ return 0; \\} , ""); cases.add("array cast int to uint", \\#include <stdlib.h> \\static unsigned int hash_binary(int k) \\{ \\ int choose[3] = {-1, -2, 3}; \\ unsigned int sum = 2; \\ sum += choose[k]; \\ return sum; \\} \\ \\int main() { \\ unsigned int x = hash_binary(1); \\ if (x != 0) abort(); \\ return 0; \\} , ""); }
test/run_translated_c.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../in/day07.txt"); const AdjacencyList = std.hash_map.StringHashMap(Bag1); const List = std.ArrayList([]const u8); const Queue = std.fifo.LinearFifo([]const u8, .Dynamic); const Bag1 = struct { is_connected: bool = false, edges: List }; /// Strategy: /// 1. Parse input into an inverted digraph (represented by an adjacency list) /// - inverted bc it means we can start searching from the shiny gold bag and it also /// guarantees that (when searching) we only visit nodes connected to the shiny gold bag. /// 2. Find the number of nodes connected to the shiny gold bag /// - use BFS so that walking cycles can be prevented by only adding disconnected nodes to the frontier /// - (TODO think harder about whether DFS could even have this issue) pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; var graph = try buildInvertedGraph(allocator); const count = try countConnectedNodes(allocator, graph); print("part1: {}\n", .{count}); try part2(allocator); } const Bag = struct { const NestedBag = struct {color: []const u8, quantity: u3}; color: []const u8, contains: []NestedBag }; fn part2(ally: *mem.Allocator) !void { const bags = try parse(ally); var map = std.StringHashMap(Bag).init(ally); for (bags) |bag| try map.put(bag.color, bag); var next_bag: []const u8 = "shiny gold"; const counter = struct { bag_map: std.StringHashMap(Bag), pub fn countBags(self: @This(), src: []const u8) u16 { var count: u16 = 0; const inner = self.bag_map.get(src) orelse unreachable; for (inner.contains) |nested_bag| { count += nested_bag.quantity + nested_bag.quantity * self.countBags(nested_bag.color); } return count; } }; const c = counter{.bag_map = map}; const total = c.countBags("shiny gold"); print("part2: {}\n", .{total}); } /// Example: /// -------- /// 'light violet bags contain 3 pale beige bags, 2 mirrored silver bags.' fn parse(ally: *mem.Allocator) ![]Bag { var bags = std.ArrayList(Bag).init(ally); errdefer bags.deinit(); var it = mem.tokenize(input, ".\n"); while (it.next()) |rule| { const main_bag = parseBagBlk: { const end = mem.indexOf(u8, rule, " bags") orelse unreachable; break :parseBagBlk rule[0..end]; }; const nested_bags = parseNestedBlk: { var list = std.ArrayList(Bag.NestedBag).init(ally); if (mem.eql(u8, rule[main_bag.len..], " bags contain no other bags")) { break :parseNestedBlk list.toOwnedSlice(); // []NestedBag } var nested_it = mem.split(rule[main_bag.len+14..], ", "); while (nested_it.next()) |bag_info| { const quantity = try std.fmt.parseUnsigned(u3, bag_info[0..1], 10); const end_offset = 4 + @as(usize, @boolToInt(quantity > 1)); // _bag[s] try list.append(Bag.NestedBag{ .quantity = quantity, .color = bag_info[2..bag_info.len-end_offset] }); } break :parseNestedBlk list.toOwnedSlice(); // []NestedBag }; try bags.append(Bag{.color = main_bag, .contains = nested_bags}); } return bags.toOwnedSlice(); // []Bag } fn buildInvertedGraph(allocator: *mem.Allocator) !AdjacencyList { var graph = AdjacencyList.init(allocator); try graph.ensureCapacity(500); errdefer graph.deinit(); var it = mem.split(input, "\n"); while (it.next()) |rule| { const v = blk: { const end = mem.indexOf(u8, rule, "bags") orelse continue; break :blk rule[0..end-1]; }; const edges = blk: { var list = List.init(allocator); var offset: usize = v.len; while (indexOfDigit(rule[offset..])) |idx| { const begin = idx+offset+2; const end = if (mem.indexOf(u8, rule[begin..], "bag")) |res| res+begin else continue; try list.append(rule[begin..end-1]); offset = end+3; } break :blk list.toOwnedSlice(); }; // ensure that an entry will exist for each vertex. if (!graph.contains(v)) { try graph.put(v, Bag1{.edges = List.init(allocator)}); } // assemble inversion for (edges) |e| { const res = try graph.getOrPutValue(e, Bag1{.edges = List.init(allocator)}); try res.value.edges.append(v); } } return graph; } fn countConnectedNodes(allocator: *mem.Allocator, graph: AdjacencyList) !usize { var count: usize = 0; // bfs var frontier = Queue.init(allocator); defer frontier.deinit(); try frontier.writeItem("shiny gold"); while (frontier.readItem()) |v_color| { const v = graph.get(v_color) orelse unreachable; for (v.edges.items) |u_color| { const u = graph.getEntry(u_color) orelse unreachable; if (u.value.is_connected) continue; u.value.is_connected = true; try frontier.writeItem(u_color); count += 1; } } return count; } fn indexOfDigit(slice: []const u8) ?usize { for (slice) |c, i| { if (std.ascii.isDigit(c)) return i; } return null; }
src/day07.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const StreamServer = std.net.StreamServer; const Address = std.net.Address; const File = std.fs.File; const builtin = @import("builtin"); const request = @import("http/request.zig"); const response = @import("http/response.zig"); const parser = @import("http/parser.zig"); const http = @import("http.zig"); const router = @import("router.zig"); const Version = @import("http/common.zig").Version; const Method = http.Method; const Request = http.Request; const Response = http.Response; const Headers = http.Headers; const Router = router.Router; const HandlerFn = router.HandlerFn; pub const Server = struct { server: StreamServer, handler: HandlerFn, allocator: Allocator, config: Config, discards: DiscardStack, const DiscardStack = std.atomic.Stack(*Context); pub const Config = struct { keepalive_time: u64 = 5000, max_request_size: u32 = 1024 * 1024, stack_size: usize = 4 * 1024 * 1024, }; pub const Context = struct { stack: []align(16) u8, buf: []u8, index: usize = 0, count: usize = 0, writer: std.io.BufferedWriter(4096, std.net.Stream.Writer), server: *Server, stream: std.net.Stream, frame: @Frame(handleRequest), node: DiscardStack.Node, pub fn init(server: *Server, stream: std.net.Stream) !*Context { var ctx = try server.allocator.create(Context); errdefer server.allocator.destroy(ctx); var stack = try server.allocator.alignedAlloc(u8, 16, server.config.stack_size); errdefer server.allocator.free(stack); var buf = try server.allocator.alloc(u8, server.config.max_request_size); errdefer server.allocator.free(buf); ctx.* = .{ .stack = stack, .buf = buf, .writer = std.io.bufferedWriter(stream.writer()), .server = server, .stream = stream, .frame = undefined, .node = .{ .next = null, .data = ctx, }, }; return ctx; } pub fn deinit(context: *Context) void { context.stream.close(); context.server.allocator.free(context.stack); context.server.allocator.free(context.buf); } pub fn read(context: *Context) !void { context.index = 0; context.count = try context.stream.read(context.buf); } }; const Upgrade = enum { webSocket, http2, none, }; pub fn init(allocator: Allocator, config: Config, handlers: anytype) Server { return .{ .server = StreamServer.init(.{}), .handler = Router(handlers), .allocator = allocator, .config = config, .discards = DiscardStack.init(), }; } pub const ListenError = error{ AddressInUse, AddressNotAvailable, ListenError, AcceptError, BlockedByFirewall, }; pub fn listen(server: *Server, address: Address) ListenError!void { defer server.server.deinit(); server.server.listen(address) catch |err| switch (err) { error.AddressInUse, error.AddressNotAvailable, => |e| return e, else => return error.ListenError, }; while (true) { var conn = server.server.accept() catch |err| switch (err) { error.ConnectionAborted, error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, error.SystemResources, error.ProtocolFailure, error.Unexpected, error.ConnectionResetByPeer, error.NetworkSubsystemFailed, => continue, error.BlockedByFirewall => |e| return e, error.FileDescriptorNotASocket, error.SocketNotListening, error.OperationNotSupported, => return error.ListenError, }; var context = Context.init(server, conn.stream) catch { conn.stream.close(); continue; }; context.frame = async handleRequest(context); while (server.discards.pop()) |c| { c.data.deinit(); server.allocator.destroy(c.data); } } } fn handleRequest(context: *Context) callconv(.Async) void { defer context.server.discards.push(&context.node); const up = handleHttp(context) catch |e| { std.debug.print("error in http handler: {}\n", .{e}); return; }; switch (up) { .webSocket => { // handleWs(self, socket.handle) catch |e| {}; }, .http2 => {}, .none => {}, } } fn handleHttp(ctx: *Context) callconv(.Async) !Upgrade { var buf = std.ArrayList(u8).init(ctx.server.allocator); defer buf.deinit(); // for use in headers and allocations in handlers var arena = ArenaAllocator.init(ctx.server.allocator); defer arena.deinit(); const alloc = arena.allocator(); while (true) { var req = request.Request{ .method = "", .headers = Headers.init(alloc), .path = "", .query = "", .body = "", .version = .Http11, }; var res = response.Response{ .status_code = null, .headers = Headers.init(alloc), .body = buf.writer(), .allocator = alloc, }; try ctx.read(); if (ctx.count == 0) { return .none; } if (parser.parse(&req, ctx)) { var frame = @asyncCall(ctx.stack, {}, ctx.server.handler, .{ &req, &res, req.path }); await frame catch |e| { try defaultErrorHandler(e, &req, &res); }; } else |e| { try defaultErrorHandler(e, &req, &res); try writeResponse(ctx.server, ctx.writer.writer(), &req, &res); try ctx.writer.flush(); return .none; } try writeResponse(ctx.server, ctx.writer.writer(), &req, &res); try ctx.writer.flush(); // reset for next request arena.deinit(); arena = ArenaAllocator.init(ctx.server.allocator); buf.resize(0) catch unreachable; } return .none; } fn writeResponse(_: *Server, writer: anytype, req: Request, res: Response) !void { const body = res.body.context.items; const is_head = mem.eql(u8, req.method, Method.Head); try writer.print("{s} {} {s}\r\n", .{ req.version.toString(), @enumToInt(res.status_code.?), res.status_code.?.toString() }); for (res.headers.list.items) |header| { try writer.print("{s}: {s}\r\n", .{ header.name, header.value }); } const keep_alive = switch (req.version) { Version.Http09 => false, Version.Http10 => req.headers.hasTokenIgnoreCase("connection", "keep-alive"), else => !req.headers.hasTokenIgnoreCase("connection", "close"), }; if (keep_alive) { try writer.writeAll("connection: keep-alive\r\n"); } else { try writer.writeAll("connection: close\r\n"); } if (is_head) { try writer.writeAll("content-length: 0\r\n\r\n"); } else { try writer.print("content-length: {}\r\n\r\n", .{body.len}); } if (!is_head) { try writer.writeAll(body); } } fn defaultErrorHandler(err: anyerror, req: Request, res: Response) !void { switch (err) { error.FileNotFound => { res.status_code = .NotFound; try res.print( \\<!DOCTYPE html> \\<html> \\<head> \\ <title>404 - Not Found</title> \\</head> \\<body> \\ <h1>Not Found</h1> \\ <p>Requested URL {s} was not found.</p> \\</body> \\</html> , .{req.path}); }, else => { if (builtin.mode == .Debug) { res.status_code = .InternalServerError; try res.print( \\<!DOCTYPE html> \\<html> \\<head> \\ <title>500 - Internal Server Error</title> \\</head> \\<body> \\ <h1>Internal Server Error</h1> \\ <p>Debug info - Error: {s}</p> \\</body> \\</html> , .{@errorName(err)}); } else { res.status_code = .InternalServerError; try res.write( \\<!DOCTYPE html> \\<html> \\<head> \\ <title>500 - Internal Server Error</title> \\</head> \\<body> \\ <h1>Internal Server Error</h1> \\</body> \\</html> ); } }, } } };
src/routez/server.zig
const std = @import("std"); const mem = std.mem; const GraphemeExtend = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 768, hi: u21 = 917999, pub fn init(allocator: *mem.Allocator) !GraphemeExtend { var instance = GraphemeExtend{ .allocator = allocator, .array = try allocator.alloc(bool, 917232), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 111) : (index += 1) { instance.array[index] = true; } index = 387; while (index <= 391) : (index += 1) { instance.array[index] = true; } index = 392; while (index <= 393) : (index += 1) { instance.array[index] = true; } index = 657; while (index <= 701) : (index += 1) { instance.array[index] = true; } instance.array[703] = true; index = 705; while (index <= 706) : (index += 1) { instance.array[index] = true; } index = 708; while (index <= 709) : (index += 1) { instance.array[index] = true; } instance.array[711] = true; index = 784; while (index <= 794) : (index += 1) { instance.array[index] = true; } index = 843; while (index <= 863) : (index += 1) { instance.array[index] = true; } instance.array[880] = true; index = 982; while (index <= 988) : (index += 1) { instance.array[index] = true; } index = 991; while (index <= 996) : (index += 1) { instance.array[index] = true; } index = 999; while (index <= 1000) : (index += 1) { instance.array[index] = true; } index = 1002; while (index <= 1005) : (index += 1) { instance.array[index] = true; } instance.array[1041] = true; index = 1072; while (index <= 1098) : (index += 1) { instance.array[index] = true; } index = 1190; while (index <= 1200) : (index += 1) { instance.array[index] = true; } index = 1259; while (index <= 1267) : (index += 1) { instance.array[index] = true; } instance.array[1277] = true; index = 1302; while (index <= 1305) : (index += 1) { instance.array[index] = true; } index = 1307; while (index <= 1315) : (index += 1) { instance.array[index] = true; } index = 1317; while (index <= 1319) : (index += 1) { instance.array[index] = true; } index = 1321; while (index <= 1325) : (index += 1) { instance.array[index] = true; } index = 1369; while (index <= 1371) : (index += 1) { instance.array[index] = true; } index = 1491; while (index <= 1505) : (index += 1) { instance.array[index] = true; } index = 1507; while (index <= 1538) : (index += 1) { instance.array[index] = true; } instance.array[1594] = true; instance.array[1596] = true; index = 1601; while (index <= 1608) : (index += 1) { instance.array[index] = true; } instance.array[1613] = true; index = 1617; while (index <= 1623) : (index += 1) { instance.array[index] = true; } index = 1634; while (index <= 1635) : (index += 1) { instance.array[index] = true; } instance.array[1665] = true; instance.array[1724] = true; instance.array[1726] = true; index = 1729; while (index <= 1732) : (index += 1) { instance.array[index] = true; } instance.array[1741] = true; instance.array[1751] = true; index = 1762; while (index <= 1763) : (index += 1) { instance.array[index] = true; } instance.array[1790] = true; index = 1793; while (index <= 1794) : (index += 1) { instance.array[index] = true; } instance.array[1852] = true; index = 1857; while (index <= 1858) : (index += 1) { instance.array[index] = true; } index = 1863; while (index <= 1864) : (index += 1) { instance.array[index] = true; } index = 1867; while (index <= 1869) : (index += 1) { instance.array[index] = true; } instance.array[1873] = true; index = 1904; while (index <= 1905) : (index += 1) { instance.array[index] = true; } instance.array[1909] = true; index = 1921; while (index <= 1922) : (index += 1) { instance.array[index] = true; } instance.array[1980] = true; index = 1985; while (index <= 1989) : (index += 1) { instance.array[index] = true; } index = 1991; while (index <= 1992) : (index += 1) { instance.array[index] = true; } instance.array[1997] = true; index = 2018; while (index <= 2019) : (index += 1) { instance.array[index] = true; } index = 2042; while (index <= 2047) : (index += 1) { instance.array[index] = true; } instance.array[2049] = true; instance.array[2108] = true; instance.array[2110] = true; instance.array[2111] = true; index = 2113; while (index <= 2116) : (index += 1) { instance.array[index] = true; } instance.array[2125] = true; index = 2133; while (index <= 2134) : (index += 1) { instance.array[index] = true; } instance.array[2135] = true; index = 2146; while (index <= 2147) : (index += 1) { instance.array[index] = true; } instance.array[2178] = true; instance.array[2238] = true; instance.array[2240] = true; instance.array[2253] = true; instance.array[2263] = true; instance.array[2304] = true; instance.array[2308] = true; index = 2366; while (index <= 2368) : (index += 1) { instance.array[index] = true; } index = 2374; while (index <= 2376) : (index += 1) { instance.array[index] = true; } index = 2378; while (index <= 2381) : (index += 1) { instance.array[index] = true; } index = 2389; while (index <= 2390) : (index += 1) { instance.array[index] = true; } index = 2402; while (index <= 2403) : (index += 1) { instance.array[index] = true; } instance.array[2433] = true; instance.array[2492] = true; instance.array[2495] = true; instance.array[2498] = true; instance.array[2502] = true; index = 2508; while (index <= 2509) : (index += 1) { instance.array[index] = true; } index = 2517; while (index <= 2518) : (index += 1) { instance.array[index] = true; } index = 2530; while (index <= 2531) : (index += 1) { instance.array[index] = true; } index = 2560; while (index <= 2561) : (index += 1) { instance.array[index] = true; } index = 2619; while (index <= 2620) : (index += 1) { instance.array[index] = true; } instance.array[2622] = true; index = 2625; while (index <= 2628) : (index += 1) { instance.array[index] = true; } instance.array[2637] = true; instance.array[2647] = true; index = 2658; while (index <= 2659) : (index += 1) { instance.array[index] = true; } instance.array[2689] = true; instance.array[2762] = true; instance.array[2767] = true; index = 2770; while (index <= 2772) : (index += 1) { instance.array[index] = true; } instance.array[2774] = true; instance.array[2783] = true; instance.array[2865] = true; index = 2868; while (index <= 2874) : (index += 1) { instance.array[index] = true; } index = 2887; while (index <= 2894) : (index += 1) { instance.array[index] = true; } instance.array[2993] = true; index = 2996; while (index <= 3004) : (index += 1) { instance.array[index] = true; } index = 3016; while (index <= 3021) : (index += 1) { instance.array[index] = true; } index = 3096; while (index <= 3097) : (index += 1) { instance.array[index] = true; } instance.array[3125] = true; instance.array[3127] = true; instance.array[3129] = true; index = 3185; while (index <= 3198) : (index += 1) { instance.array[index] = true; } index = 3200; while (index <= 3204) : (index += 1) { instance.array[index] = true; } index = 3206; while (index <= 3207) : (index += 1) { instance.array[index] = true; } index = 3213; while (index <= 3223) : (index += 1) { instance.array[index] = true; } index = 3225; while (index <= 3260) : (index += 1) { instance.array[index] = true; } instance.array[3270] = true; index = 3373; while (index <= 3376) : (index += 1) { instance.array[index] = true; } index = 3378; while (index <= 3383) : (index += 1) { instance.array[index] = true; } index = 3385; while (index <= 3386) : (index += 1) { instance.array[index] = true; } index = 3389; while (index <= 3390) : (index += 1) { instance.array[index] = true; } index = 3416; while (index <= 3417) : (index += 1) { instance.array[index] = true; } index = 3422; while (index <= 3424) : (index += 1) { instance.array[index] = true; } index = 3441; while (index <= 3444) : (index += 1) { instance.array[index] = true; } instance.array[3458] = true; index = 3461; while (index <= 3462) : (index += 1) { instance.array[index] = true; } instance.array[3469] = true; instance.array[3485] = true; index = 4189; while (index <= 4191) : (index += 1) { instance.array[index] = true; } index = 5138; while (index <= 5140) : (index += 1) { instance.array[index] = true; } index = 5170; while (index <= 5172) : (index += 1) { instance.array[index] = true; } index = 5202; while (index <= 5203) : (index += 1) { instance.array[index] = true; } index = 5234; while (index <= 5235) : (index += 1) { instance.array[index] = true; } index = 5300; while (index <= 5301) : (index += 1) { instance.array[index] = true; } index = 5303; while (index <= 5309) : (index += 1) { instance.array[index] = true; } instance.array[5318] = true; index = 5321; while (index <= 5331) : (index += 1) { instance.array[index] = true; } instance.array[5341] = true; index = 5387; while (index <= 5389) : (index += 1) { instance.array[index] = true; } index = 5509; while (index <= 5510) : (index += 1) { instance.array[index] = true; } instance.array[5545] = true; index = 5664; while (index <= 5666) : (index += 1) { instance.array[index] = true; } index = 5671; while (index <= 5672) : (index += 1) { instance.array[index] = true; } instance.array[5682] = true; index = 5689; while (index <= 5691) : (index += 1) { instance.array[index] = true; } index = 5911; while (index <= 5912) : (index += 1) { instance.array[index] = true; } instance.array[5915] = true; instance.array[5974] = true; index = 5976; while (index <= 5982) : (index += 1) { instance.array[index] = true; } instance.array[5984] = true; instance.array[5986] = true; index = 5989; while (index <= 5996) : (index += 1) { instance.array[index] = true; } index = 6003; while (index <= 6012) : (index += 1) { instance.array[index] = true; } instance.array[6015] = true; index = 6064; while (index <= 6077) : (index += 1) { instance.array[index] = true; } instance.array[6078] = true; index = 6079; while (index <= 6080) : (index += 1) { instance.array[index] = true; } index = 6144; while (index <= 6147) : (index += 1) { instance.array[index] = true; } instance.array[6196] = true; instance.array[6197] = true; index = 6198; while (index <= 6202) : (index += 1) { instance.array[index] = true; } instance.array[6204] = true; instance.array[6210] = true; index = 6251; while (index <= 6259) : (index += 1) { instance.array[index] = true; } index = 6272; while (index <= 6273) : (index += 1) { instance.array[index] = true; } index = 6306; while (index <= 6309) : (index += 1) { instance.array[index] = true; } index = 6312; while (index <= 6313) : (index += 1) { instance.array[index] = true; } index = 6315; while (index <= 6317) : (index += 1) { instance.array[index] = true; } instance.array[6374] = true; index = 6376; while (index <= 6377) : (index += 1) { instance.array[index] = true; } instance.array[6381] = true; index = 6383; while (index <= 6385) : (index += 1) { instance.array[index] = true; } index = 6444; while (index <= 6451) : (index += 1) { instance.array[index] = true; } index = 6454; while (index <= 6455) : (index += 1) { instance.array[index] = true; } index = 6608; while (index <= 6610) : (index += 1) { instance.array[index] = true; } index = 6612; while (index <= 6624) : (index += 1) { instance.array[index] = true; } index = 6626; while (index <= 6632) : (index += 1) { instance.array[index] = true; } instance.array[6637] = true; instance.array[6644] = true; index = 6648; while (index <= 6649) : (index += 1) { instance.array[index] = true; } index = 6848; while (index <= 6905) : (index += 1) { instance.array[index] = true; } index = 6907; while (index <= 6911) : (index += 1) { instance.array[index] = true; } instance.array[7436] = true; index = 7632; while (index <= 7644) : (index += 1) { instance.array[index] = true; } index = 7645; while (index <= 7648) : (index += 1) { instance.array[index] = true; } instance.array[7649] = true; index = 7650; while (index <= 7652) : (index += 1) { instance.array[index] = true; } index = 7653; while (index <= 7664) : (index += 1) { instance.array[index] = true; } index = 10735; while (index <= 10737) : (index += 1) { instance.array[index] = true; } instance.array[10879] = true; index = 10976; while (index <= 11007) : (index += 1) { instance.array[index] = true; } index = 11562; while (index <= 11565) : (index += 1) { instance.array[index] = true; } index = 11566; while (index <= 11567) : (index += 1) { instance.array[index] = true; } index = 11673; while (index <= 11674) : (index += 1) { instance.array[index] = true; } instance.array[41839] = true; index = 41840; while (index <= 41842) : (index += 1) { instance.array[index] = true; } index = 41844; while (index <= 41853) : (index += 1) { instance.array[index] = true; } index = 41886; while (index <= 41887) : (index += 1) { instance.array[index] = true; } index = 41968; while (index <= 41969) : (index += 1) { instance.array[index] = true; } instance.array[42242] = true; instance.array[42246] = true; instance.array[42251] = true; index = 42277; while (index <= 42278) : (index += 1) { instance.array[index] = true; } instance.array[42284] = true; index = 42436; while (index <= 42437) : (index += 1) { instance.array[index] = true; } index = 42464; while (index <= 42481) : (index += 1) { instance.array[index] = true; } instance.array[42495] = true; index = 42534; while (index <= 42541) : (index += 1) { instance.array[index] = true; } index = 42567; while (index <= 42577) : (index += 1) { instance.array[index] = true; } index = 42624; while (index <= 42626) : (index += 1) { instance.array[index] = true; } instance.array[42675] = true; index = 42678; while (index <= 42681) : (index += 1) { instance.array[index] = true; } index = 42684; while (index <= 42685) : (index += 1) { instance.array[index] = true; } instance.array[42725] = true; index = 42793; while (index <= 42798) : (index += 1) { instance.array[index] = true; } index = 42801; while (index <= 42802) : (index += 1) { instance.array[index] = true; } index = 42805; while (index <= 42806) : (index += 1) { instance.array[index] = true; } instance.array[42819] = true; instance.array[42828] = true; instance.array[42876] = true; instance.array[42928] = true; index = 42930; while (index <= 42932) : (index += 1) { instance.array[index] = true; } index = 42935; while (index <= 42936) : (index += 1) { instance.array[index] = true; } index = 42942; while (index <= 42943) : (index += 1) { instance.array[index] = true; } instance.array[42945] = true; index = 42988; while (index <= 42989) : (index += 1) { instance.array[index] = true; } instance.array[42998] = true; instance.array[43237] = true; instance.array[43240] = true; instance.array[43245] = true; instance.array[63518] = true; index = 64256; while (index <= 64271) : (index += 1) { instance.array[index] = true; } index = 64288; while (index <= 64303) : (index += 1) { instance.array[index] = true; } index = 64670; while (index <= 64671) : (index += 1) { instance.array[index] = true; } instance.array[65277] = true; instance.array[65504] = true; index = 65654; while (index <= 65658) : (index += 1) { instance.array[index] = true; } index = 67329; while (index <= 67331) : (index += 1) { instance.array[index] = true; } index = 67333; while (index <= 67334) : (index += 1) { instance.array[index] = true; } index = 67340; while (index <= 67343) : (index += 1) { instance.array[index] = true; } index = 67384; while (index <= 67386) : (index += 1) { instance.array[index] = true; } instance.array[67391] = true; index = 67557; while (index <= 67558) : (index += 1) { instance.array[index] = true; } index = 68132; while (index <= 68135) : (index += 1) { instance.array[index] = true; } index = 68523; while (index <= 68524) : (index += 1) { instance.array[index] = true; } index = 68678; while (index <= 68688) : (index += 1) { instance.array[index] = true; } instance.array[68865] = true; index = 68920; while (index <= 68934) : (index += 1) { instance.array[index] = true; } index = 68991; while (index <= 68993) : (index += 1) { instance.array[index] = true; } index = 69043; while (index <= 69046) : (index += 1) { instance.array[index] = true; } index = 69049; while (index <= 69050) : (index += 1) { instance.array[index] = true; } index = 69120; while (index <= 69122) : (index += 1) { instance.array[index] = true; } index = 69159; while (index <= 69163) : (index += 1) { instance.array[index] = true; } index = 69165; while (index <= 69172) : (index += 1) { instance.array[index] = true; } instance.array[69235] = true; index = 69248; while (index <= 69249) : (index += 1) { instance.array[index] = true; } index = 69302; while (index <= 69310) : (index += 1) { instance.array[index] = true; } index = 69321; while (index <= 69324) : (index += 1) { instance.array[index] = true; } instance.array[69327] = true; index = 69423; while (index <= 69425) : (index += 1) { instance.array[index] = true; } instance.array[69428] = true; index = 69430; while (index <= 69431) : (index += 1) { instance.array[index] = true; } instance.array[69438] = true; instance.array[69599] = true; index = 69603; while (index <= 69610) : (index += 1) { instance.array[index] = true; } index = 69632; while (index <= 69633) : (index += 1) { instance.array[index] = true; } index = 69691; while (index <= 69692) : (index += 1) { instance.array[index] = true; } instance.array[69694] = true; instance.array[69696] = true; instance.array[69719] = true; index = 69734; while (index <= 69740) : (index += 1) { instance.array[index] = true; } index = 69744; while (index <= 69748) : (index += 1) { instance.array[index] = true; } index = 69944; while (index <= 69951) : (index += 1) { instance.array[index] = true; } index = 69954; while (index <= 69956) : (index += 1) { instance.array[index] = true; } instance.array[69958] = true; instance.array[69982] = true; instance.array[70064] = true; index = 70067; while (index <= 70072) : (index += 1) { instance.array[index] = true; } instance.array[70074] = true; instance.array[70077] = true; index = 70079; while (index <= 70080) : (index += 1) { instance.array[index] = true; } index = 70082; while (index <= 70083) : (index += 1) { instance.array[index] = true; } instance.array[70319] = true; index = 70322; while (index <= 70325) : (index += 1) { instance.array[index] = true; } index = 70332; while (index <= 70333) : (index += 1) { instance.array[index] = true; } index = 70335; while (index <= 70336) : (index += 1) { instance.array[index] = true; } index = 70364; while (index <= 70365) : (index += 1) { instance.array[index] = true; } index = 70451; while (index <= 70458) : (index += 1) { instance.array[index] = true; } instance.array[70461] = true; index = 70463; while (index <= 70464) : (index += 1) { instance.array[index] = true; } instance.array[70571] = true; instance.array[70573] = true; index = 70576; while (index <= 70581) : (index += 1) { instance.array[index] = true; } instance.array[70583] = true; index = 70685; while (index <= 70687) : (index += 1) { instance.array[index] = true; } index = 70690; while (index <= 70693) : (index += 1) { instance.array[index] = true; } index = 70695; while (index <= 70699) : (index += 1) { instance.array[index] = true; } index = 70959; while (index <= 70967) : (index += 1) { instance.array[index] = true; } index = 70969; while (index <= 70970) : (index += 1) { instance.array[index] = true; } instance.array[71216] = true; index = 71227; while (index <= 71228) : (index += 1) { instance.array[index] = true; } instance.array[71230] = true; instance.array[71235] = true; index = 71380; while (index <= 71383) : (index += 1) { instance.array[index] = true; } index = 71386; while (index <= 71387) : (index += 1) { instance.array[index] = true; } instance.array[71392] = true; index = 71425; while (index <= 71434) : (index += 1) { instance.array[index] = true; } index = 71475; while (index <= 71480) : (index += 1) { instance.array[index] = true; } index = 71483; while (index <= 71486) : (index += 1) { instance.array[index] = true; } instance.array[71495] = true; index = 71505; while (index <= 71510) : (index += 1) { instance.array[index] = true; } index = 71513; while (index <= 71515) : (index += 1) { instance.array[index] = true; } index = 71562; while (index <= 71574) : (index += 1) { instance.array[index] = true; } index = 71576; while (index <= 71577) : (index += 1) { instance.array[index] = true; } index = 71984; while (index <= 71990) : (index += 1) { instance.array[index] = true; } index = 71992; while (index <= 71997) : (index += 1) { instance.array[index] = true; } instance.array[71999] = true; index = 72082; while (index <= 72103) : (index += 1) { instance.array[index] = true; } index = 72106; while (index <= 72112) : (index += 1) { instance.array[index] = true; } index = 72114; while (index <= 72115) : (index += 1) { instance.array[index] = true; } index = 72117; while (index <= 72118) : (index += 1) { instance.array[index] = true; } index = 72241; while (index <= 72246) : (index += 1) { instance.array[index] = true; } instance.array[72250] = true; index = 72252; while (index <= 72253) : (index += 1) { instance.array[index] = true; } index = 72255; while (index <= 72261) : (index += 1) { instance.array[index] = true; } instance.array[72263] = true; index = 72336; while (index <= 72337) : (index += 1) { instance.array[index] = true; } instance.array[72341] = true; instance.array[72343] = true; index = 72691; while (index <= 72692) : (index += 1) { instance.array[index] = true; } index = 92144; while (index <= 92148) : (index += 1) { instance.array[index] = true; } index = 92208; while (index <= 92214) : (index += 1) { instance.array[index] = true; } instance.array[93263] = true; index = 93327; while (index <= 93330) : (index += 1) { instance.array[index] = true; } instance.array[93412] = true; index = 113053; while (index <= 113054) : (index += 1) { instance.array[index] = true; } instance.array[118373] = true; index = 118375; while (index <= 118377) : (index += 1) { instance.array[index] = true; } index = 118382; while (index <= 118386) : (index += 1) { instance.array[index] = true; } index = 118395; while (index <= 118402) : (index += 1) { instance.array[index] = true; } index = 118405; while (index <= 118411) : (index += 1) { instance.array[index] = true; } index = 118442; while (index <= 118445) : (index += 1) { instance.array[index] = true; } index = 118594; while (index <= 118596) : (index += 1) { instance.array[index] = true; } index = 120576; while (index <= 120630) : (index += 1) { instance.array[index] = true; } index = 120635; while (index <= 120684) : (index += 1) { instance.array[index] = true; } instance.array[120693] = true; instance.array[120708] = true; index = 120731; while (index <= 120735) : (index += 1) { instance.array[index] = true; } index = 120737; while (index <= 120751) : (index += 1) { instance.array[index] = true; } index = 122112; while (index <= 122118) : (index += 1) { instance.array[index] = true; } index = 122120; while (index <= 122136) : (index += 1) { instance.array[index] = true; } index = 122139; while (index <= 122145) : (index += 1) { instance.array[index] = true; } index = 122147; while (index <= 122148) : (index += 1) { instance.array[index] = true; } index = 122150; while (index <= 122154) : (index += 1) { instance.array[index] = true; } index = 122416; while (index <= 122422) : (index += 1) { instance.array[index] = true; } index = 122860; while (index <= 122863) : (index += 1) { instance.array[index] = true; } index = 124368; while (index <= 124374) : (index += 1) { instance.array[index] = true; } index = 124484; while (index <= 124490) : (index += 1) { instance.array[index] = true; } index = 916768; while (index <= 916863) : (index += 1) { instance.array[index] = true; } index = 916992; while (index <= 917231) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *GraphemeExtend) void { self.allocator.free(self.array); } // isGraphemeExtend checks if cp is of the kind Grapheme_Extend. pub fn isGraphemeExtend(self: GraphemeExtend, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedCoreProperties/GraphemeExtend.zig
const std = @import("std"); // Utility functions // /// Read a int from a file pub fn readIntFromFile(comptime T: type, file: std.fs.File) !T { var buf = [_]u8{0} ** @sizeOf(T); _ = try file.readAll(buf[0..]); return std.mem.readIntLittle(T, buf[0..]); } /// write a int n to a file pub fn writeIntToFile(file: std.fs.File, n: anytype) !void { try file.writeAll(std.mem.toBytes(n)[0..]); } /// Read a int from a file on pos pub fn readIntFromFileOnPos(comptime T: type, file: std.fs.File, pos: u64) !T { const oldPos = try file.getPos(); try file.seekTo(pos); var buf = [_]u8{0} ** @sizeOf(T); _ = try file.readAll(buf[0..]); try file.seekTo(oldPos); return std.mem.readIntLittle(T, buf[0..]); } /// write a int n to a file on pos pub fn writeIntToFileOnPos(file: std.fs.File, n: anytype, pos: u64) !void { const oldPos = try file.getPos(); try file.seekTo(pos); try file.writeAll(std.mem.toBytes(n)[0..]); try file.seekTo(oldPos); } pub fn writeFixStrToFile(file: std.fs.File, comptime capacity: u32, str: FixedSizeString(capacity)) !void { if (capacity < std.math.maxInt(u32)) { try writeIntToFile(file, @intCast(u8, str.len)); } else if (capacity < std.math.maxInt(u16)) { try writeIntToFile(file, @intCast(u16, str.len)); } else if (capacity < std.math.maxInt(u32)) { try writeIntToFile(file, @intCast(u32, str.len)); } else { try writeIntToFile(file, @intCast(u64, str.len)); } try file.writeAll(fixedStrToSlice(str)); } pub fn readFixStrToFile(file: std.fs.File, comptime capacity: u32) !FixedSizeString(capacity) { var buff = [_]u8{0} ** capacity; var len: u64 = 0; if (capacity < std.math.maxInt(u32)) { len = try readIntFromFile(u8, file); } else if (capacity < std.math.maxInt(u16)) { len = try readIntFromFile(u16, file); } else if (capacity < std.math.maxInt(u32)) { len = try readIntFromFile(u32, file); } else { len = try readIntFromFile(u64, file); } if (len > capacity) return error.StringToBig; const s = try file.readAll(buff[0..len]); _ = s; return createFixedString(capacity, buff[0..len]); } pub fn swap(a: anytype, b: anytype) void { comptime if (@TypeOf(a) != @TypeOf(b)) @compileError("Trying to swap diferent types\n"); var tmp = a.*; a.* = b.*; b.* = tmp; } pub const clamp = std.math.clamp; // #TODO(samuel): Change to use only one sort function pub fn quickSort(comptime T: type, array: []T, lesst_func: fn (a: T, b: T) bool, greatt_func: fn (a: T, b: T) bool) void { var i: isize = 0; var j: isize = @intCast(isize, array.len - 1); var pivo = array[array.len / 2]; while (i <= j) { while (lesst_func(array[@intCast(usize, i)], pivo)) i += 1; while (greatt_func(array[@intCast(usize, j)], pivo)) j -= 1; if (i <= j) { swap(&array[@intCast(usize, i)], &array[@intCast(usize, j)]); i += 1; j -= 1; } } if (0 < j) quickSort(T, array[0..@intCast(usize, (j + 1))], lesst_func, greatt_func); if (i < array.len) quickSort(T, array[@intCast(usize, (i))..], lesst_func, greatt_func); } /// This is a type return function that create a FixedSizeString type /// this create a string on the stack with the max size 'size', and an lenth /// this is usefull when you need a string on a struct and dont want to make /// heap allocations, and you can copy the string with ease #CHECK pub fn FixedSizeString(comptime size: usize) type { return struct { data: [size]u8 = [_]u8{0} ** size, len: usize = 0, }; } pub inline fn emptyFixedString(comptime size: usize) FixedSizeString(size) { return createFixedString(size, ([_]u8{0} ** size)[0..]); } pub fn fixedStringAppend(comptime size: usize, fstr: *FixedSizeString(size), astr: []const u8) !void { if (size - fstr.len < astr.len) { return error.CapacityFull; } for (fstr.data[fstr.len..][0..astr.len]) |*it, i| { it.* = astr[i]; } fstr.len += astr.len; } /// recive a FixedSizeString and return a []const u8 slice with its size /// if you pass a pointer to a FixedSizeString it will return a []u8 pub inline fn fixedStrToSlice(str: anytype) switch (@typeInfo(@TypeOf(str))) { .Pointer => []u8, else => []const u8, } { return str.data[0..str.len]; } pub fn createFixedString(comptime size: usize, str: []const u8) FixedSizeString(size) { var result: FixedSizeString(size) = undefined; result.len = str.len; for (str) |c, i| { if (i >= size) break; result.data[i] = c; } return result; } /// return the current line and advances the buffer to the next pub fn nextLineSlice(slice: *[]u8) []u8 { if (slice.len == 0) return slice.*; var i: usize = 0; while (i < slice.len and slice.*[i] != '\n') { i += 1; } var result = slice.*[0..i]; if (i > 0 and slice.*[i - 1] == '\r') { result.len -= 1; } slice.* = slice.*[i + 1 ..]; return result; } pub fn removeLeadingSpaces(slice: *[]u8) void { if (slice.len == 0) return; var i: usize = 0; while (slice.*[i] == ' ' or slice.*[i] == '\t') { i += 1; } slice.* = slice.*[i..]; } pub fn removeTrailingSpaces(slice: *[]u8) void { if (slice.len == 0) return; var i: usize = slice.len - 1; while (slice.*[i] == ' ' or slice.*[i] == '\t') { i -= 1; } slice.* = slice.*[0 .. i + 1]; } /// Return the token and advances the buffer pub fn getToken(slice: *[]u8, separator: u8) []u8 { if (slice.len == 0) return slice.*; var i: usize = 0; while (i < slice.len and slice.*[i] != separator) { i += 1; } var result = slice.*[0..i]; if (i < slice.len) { slice.* = slice.*[i + 1 ..]; } else { slice.* = slice.*[0..0]; } return result; } pub fn hasChar(str: []const u8, char: u8) bool { for (str) |c| if (c == char) return true; return false; } /// Compares two slices pub fn sliceCmp(comptime T: type, a: []const T, b: []const T) bool { if (a.len != b.len) return false; if (a.ptr == b.ptr) return true; for (a) |it, index| { if (it != b[index]) return false; } return true; } /// Compares two strings pub inline fn strCmp(a: []const u8, b: []const u8) bool { return sliceCmp(u8, a, b); } /// Compares two FixedSizeString of any size pub fn fixStrCmp(a: anytype, b: anytype) bool { if (a.len != b.len) return false; var index: usize = 0; while (index > a.len) : (index += 1) { if (a.data[index] != b.data[index]) return false; } return true; } /// Return a random float from 0 to 1 var prng = std.rand.DefaultPrng.init(0); pub inline fn randomFloat(comptime T: type) T { return prng.random.float(T); } pub inline fn randomInt(comptime T: type) T { return prng.random.int(T); } // TODO(Samuel): A List with comtime known capacity pub fn StaticList(comptime T: type, comptime size: u64, zero_value: T) type { return struct { data: [size]T = [_]T{zero_value} ** size, list: []T = undefined, len: u64 = 0, const Self = @This(); pub fn push(l: *Self, value: T) !void { if (l.len >= l.data.len) return error.ListIsFull; l.data[l.len] = value; l.len += 1; l.list = l.data[0..l.len]; } pub fn pop(l: *Self) T { if (l.len == 0) return zero_value; l.len -= 1; l.list = l.data[0..l.len]; return l.data[l.len]; } pub fn remove(l: *Self, pos: usize) T { if (l.len == 0) return zero_value; if (pos >= l.len) return zero_value; const result = l.data[pos]; var i: usize = pos; while (i < l.len - 1) { l.data[i] = l.data[i + 1]; } l.list = l.data[0..l.len]; return result; } }; }
src/util.zig
const std = @import("std"); const mem = std.mem; const math = std.math; const io = std.io; const fs = std.fs; const platform = @import("platform.zig"); const util = @import("util.zig"); const c = @cImport({ @cInclude("signal.h"); // SIGINT }); const Trap = enum(u16) { GETC = 0x20, // get character from keyboard, not echoed onto the terminal OUT = 0x21, // output a character PUTS = 0x22, // output a word string IN = 0x23, // get character from keyboard, echoed onto the terminal PUTSP = 0x24, // output a byte string HALT = 0x25 // halt the program }; const MMRegisters = enum(u16) { KBSR = 0xFE00, // keyboard status KBDR = 0xFE02, // keyboard data }; const Register = enum(u16) { R0 = 0b0000, R1 = 0b0001, R2 = 0b0010, R3 = 0b0011, R4 = 0b0100, R5 = 0b0101, R6 = 0b0110, R7 = 0b0111, PC = 0b1000, // program counter COND = 0b1001, // conditional flags }; const Opcode = enum(u16) { BR = 0b0000, // branch ADD = 0b0001, // add LD = 0b0010, // load ST = 0b0011, // store JSR = 0b0100, // jump register AND = 0b0101, // bitwise and LDR = 0b0110, // load register STR = 0b0111, // store register RTI = 0b1000, // unused NOT = 0b1001, // bitwise not LDI = 0b1010, // load indirect STI = 0b1011, // store indirect JMP = 0b1100, // jump RES = 0b1101, // reserved (unused) LEA = 0b1110, // load effective address TRAP = 0b1111, // execute trap }; const Flag = enum(u16) { POS = 0b001, ZRO = 0b010, NEG = 0b100, }; var stdout: fs.File.Writer = undefined; var stdin: fs.File.Reader = undefined; var memory = [_]u16{0} ** math.maxInt(u16); var reg = [_]u16{0} ** @typeInfo(Register).Enum.fields.len; fn update_flags(r0: u16) void { if (reg[r0] == 0) { reg_write(.COND, @enumToInt(Flag.ZRO)); } else if (reg[r0] >> 15 != 0) { reg_write(.COND, @enumToInt(Flag.NEG)); } else { reg_write(.COND, @enumToInt(Flag.POS)); } } fn reg_write(r: Register, val: u16) void { reg[@enumToInt(r)] = val; } fn reg_read(r: Register) u16 { return reg[@enumToInt(r)]; } fn mmr_read(r: MMRegisters) u16 { return memory[@enumToInt(r)]; } fn mmr_ptr(r: MMRegisters) *u16 { return &memory[@enumToInt(r)]; } fn mem_read(addr: i16) !u16 { if (addr == @enumToInt(MMRegisters.KBSR)) { if (platform.check_key() != 0) { const ch = try stdin.readIntNative(u8); mmr_ptr(.KBSR).* = (1 << 15); mmr_ptr(.KBDR).* = @intCast(u16, ch); } else { mmr_ptr(.KBSR).* = 0; } } return memory[addr]; } fn mem_write(addr: u16, val: u16) void { memory[addr] = val; } fn lc3() !u16 { stdout = io.getStdOut().writer(); stdin = io.getStdIn().reader(); const pc_start = 0x3000; reg_write(.PC, pc_start); var running = true; while (running) { if (std.builtin.mode == .Debug) { std.time.sleep(60_000_000); } var instr = memory[reg_read(.PC)]; reg_write(.PC, reg_read(.PC) + 1); var op = @intToEnum(Opcode, instr >> 12); switch (op) { // Unused .RTI, .RES => return error.BadOpcode, // Binary ops .ADD => { const r0 = (instr >> 9) & 0b111; const r1 = (instr >> 6) & 0b111; const imm_flag = (instr >> 5) & 1; if (imm_flag == 1) { const imm5 = sign_extend(instr, 5); reg[r0] = reg[r1] +% imm5; // TODO: what's the overflow behaviour on lc3? } else { const r2 = instr & 0b111; reg[r0] = reg[r1] +% reg[r2]; } update_flags(r0); }, .AND => { const r0 = (instr >> 9) & 0b111; const r1 = (instr >> 6) & 0b111; const imm_flag = (instr >> 5) & 1; if (imm_flag == 1) { const imm5 = sign_extend(instr, 5); reg[r0] = reg[r1] & imm5; } else { const r2 = instr & 0b111; reg[r0] = reg[r1] & reg[r2]; } update_flags(r0); }, .NOT => { const r0 = (instr >> 9) & 0b111; const r1 = (instr >> 6) & 0b111; reg[r0] = ~reg[r1]; update_flags(r0); }, // Loads .LD => { const r0 = (instr >> 9) & 0b111; const pc_offset = sign_extend(instr, 9); reg[r0] = try mem_read(reg_read(.PC) + pc_offset); update_flags(r0); }, .LDR => { const r0 = (instr >> 9) & 0b111; const r1 = (instr >> 6) & 0b111; const offset = sign_extend(instr, 6); reg[r0] = try mem_read(reg[r1] + offset); update_flags(r0); }, .LDI => { const r0 = (instr >> 9) & 0b111; const pc_offset = sign_extend(instr, 9); reg[r0] = try mem_read(try mem_read(reg_read(.PC) + pc_offset)); update_flags(r0); }, .LEA => { const r0 = (instr >> 9) & 0b111; const pc_offset = sign_extend(instr, 9); reg[r0] = reg_read(.PC) + pc_offset; update_flags(r0); }, // Stores .ST => { const r0 = (instr >> 9) & 0b111; const pc_offset = sign_extend(instr, 9); mem_write(reg_read(.PC) + pc_offset, reg[r0]); }, .STR => { const r0 = (instr >> 9) & 0b111; const r1 = (instr >> 6) & 0b111; const offset = sign_extend(instr, 6); mem_write(reg[r1] + offset, reg[r0]); }, .STI => { const r0 = (instr >> 9) & 0b111; const pc_offset = sign_extend(instr, 9); mem_write(try mem_read(reg_read(.PC) + pc_offset), reg[r0]); }, // Jumps, branches .BR => { const pc_offset = sign_extend(instr, 9); const cond_flag = (instr >> 9) & 0b111; if (cond_flag & reg_read(.COND) != 0) { reg_write(.PC, reg_read(.PC) + pc_offset); } }, .JMP => { const r1 = (instr >> 6) & 0b111; reg_write(.PC, reg[r1]); }, .JSR => { const long_flag = (instr >> 11) & 1; reg_write(.R7, reg_read(.PC)); if (long_flag == 1) { const long_pc_offset = sign_extend(instr, 11); reg_write(.PC, reg_read(.PC) + long_pc_offset); // JSR } else { const r1 = (instr >> 6) & 0b111; reg_write(.PC, reg[r1]); // JSRR } }, // Trap codes .TRAP => { var code = @intToEnum(Trap, instr & 0xFF); switch (code) { .IN => { const ch8 = try stdin.readIntNative(u8); reg_write(.R0, @intCast(u16, ch8)); try stdout.writeByte(ch8); }, .OUT => { const ch8 = @truncate(u8, reg_read(.R0)); try stdout.writeByte(ch8); }, .GETC => { const ch16 = @intCast(u16, try stdin.readIntNative(u8)); reg_write(.R0, ch16); }, .PUTS => { const str = mem.spanZ(memory[reg_read(.R0)..]); for (str) |ch16| { try stdout.writeByte(@truncate(u8, ch16)); } }, .PUTSP => { const str = mem.spanZ(memory[reg_read(.R0)..]); for (mem.sliceAsBytes(str)) |ch8| { try stdout.writeByte(ch8); } }, .HALT => { _ = try stdout.write("HALT"); running = false; }, } }, } } return reg_read(.R0); } fn handle_interrupt(signal: c_int) callconv(.C) void { platform.restore_input_buffering(); if (stdout.writeByte('\n')) { std.os.exit(0x41); // -2 } else |e| { std.debug.panic("Unable to write exit byte: {}\n", .{e}); } } pub fn main() anyerror!void { const al = std.heap.page_allocator; _ = c.signal(std.c.SIGINT, handle_interrupt); try platform.disable_input_buffering(); const args = try std.process.argsAlloc(al); defer std.process.argsFree(al, args); if (args.len < 2) { std.debug.panic("lc3 [image-file1] ...\n"); } // TODO: Hard to find reasons to open files in a loop like this. Don't think we'd want to load more than one image at a time? for (args[1..]) |arg| { read_image(arg) catch |e| { std.debug.warn("Failed to load file: {}\n", .{arg}); return e; }; } _ = try lc3(); }
src/main.zig
pub const WMT_VIDEOIMAGE_SAMPLE_INPUT_FRAME = @as(u32, 1); pub const WMT_VIDEOIMAGE_SAMPLE_OUTPUT_FRAME = @as(u32, 2); pub const WMT_VIDEOIMAGE_SAMPLE_USES_CURRENT_INPUT_FRAME = @as(u32, 4); pub const WMT_VIDEOIMAGE_SAMPLE_USES_PREVIOUS_INPUT_FRAME = @as(u32, 8); pub const WMT_VIDEOIMAGE_SAMPLE_MOTION = @as(u32, 1); pub const WMT_VIDEOIMAGE_SAMPLE_ROTATION = @as(u32, 2); pub const WMT_VIDEOIMAGE_SAMPLE_BLENDING = @as(u32, 4); pub const WMT_VIDEOIMAGE_SAMPLE_ADV_BLENDING = @as(u32, 8); pub const WMT_VIDEOIMAGE_INTEGER_DENOMINATOR = @as(i32, 65536); pub const WMT_VIDEOIMAGE_MAGIC_NUMBER = @as(u32, 491406834); pub const WMT_VIDEOIMAGE_MAGIC_NUMBER_2 = @as(u32, 491406835); pub const WMT_VIDEOIMAGE_TRANSITION_BOW_TIE = @as(u32, 11); pub const WMT_VIDEOIMAGE_TRANSITION_CIRCLE = @as(u32, 12); pub const WMT_VIDEOIMAGE_TRANSITION_CROSS_FADE = @as(u32, 13); pub const WMT_VIDEOIMAGE_TRANSITION_DIAGONAL = @as(u32, 14); pub const WMT_VIDEOIMAGE_TRANSITION_DIAMOND = @as(u32, 15); pub const WMT_VIDEOIMAGE_TRANSITION_FADE_TO_COLOR = @as(u32, 16); pub const WMT_VIDEOIMAGE_TRANSITION_FILLED_V = @as(u32, 17); pub const WMT_VIDEOIMAGE_TRANSITION_FLIP = @as(u32, 18); pub const WMT_VIDEOIMAGE_TRANSITION_INSET = @as(u32, 19); pub const WMT_VIDEOIMAGE_TRANSITION_IRIS = @as(u32, 20); pub const WMT_VIDEOIMAGE_TRANSITION_PAGE_ROLL = @as(u32, 21); pub const WMT_VIDEOIMAGE_TRANSITION_RECTANGLE = @as(u32, 23); pub const WMT_VIDEOIMAGE_TRANSITION_REVEAL = @as(u32, 24); pub const WMT_VIDEOIMAGE_TRANSITION_SLIDE = @as(u32, 27); pub const WMT_VIDEOIMAGE_TRANSITION_SPLIT = @as(u32, 29); pub const WMT_VIDEOIMAGE_TRANSITION_STAR = @as(u32, 30); pub const WMT_VIDEOIMAGE_TRANSITION_WHEEL = @as(u32, 31); pub const WM_SampleExtension_ContentType_Size = @as(u32, 1); pub const WM_SampleExtension_PixelAspectRatio_Size = @as(u32, 2); pub const WM_SampleExtension_Timecode_Size = @as(u32, 14); pub const WM_SampleExtension_SampleDuration_Size = @as(u32, 2); pub const WM_SampleExtension_ChromaLocation_Size = @as(u32, 1); pub const WM_SampleExtension_ColorSpaceInfo_Size = @as(u32, 3); pub const WM_CT_REPEAT_FIRST_FIELD = @as(u32, 16); pub const WM_CT_BOTTOM_FIELD_FIRST = @as(u32, 32); pub const WM_CT_TOP_FIELD_FIRST = @as(u32, 64); pub const WM_CT_INTERLACED = @as(u32, 128); pub const WM_CL_INTERLACED420 = @as(u32, 0); pub const WM_CL_PROGRESSIVE420 = @as(u32, 1); pub const WM_MAX_VIDEO_STREAMS = @as(u32, 63); pub const WM_MAX_STREAMS = @as(u32, 63); pub const WMDRM_IMPORT_INIT_STRUCT_DEFINED = @as(u32, 1); pub const DRM_OPL_TYPES = @as(u32, 1); pub const g_dwWMSpecialAttributes = @as(u32, 20); pub const g_wszWMDuration = "Duration"; pub const g_wszWMBitrate = "Bitrate"; pub const g_wszWMSeekable = "Seekable"; pub const g_wszWMStridable = "Stridable"; pub const g_wszWMBroadcast = "Broadcast"; pub const g_wszWMProtected = "Is_Protected"; pub const g_wszWMTrusted = "Is_Trusted"; pub const g_wszWMSignature_Name = "Signature_Name"; pub const g_wszWMHasAudio = "HasAudio"; pub const g_wszWMHasImage = "HasImage"; pub const g_wszWMHasScript = "HasScript"; pub const g_wszWMHasVideo = "HasVideo"; pub const g_wszWMCurrentBitrate = "CurrentBitrate"; pub const g_wszWMOptimalBitrate = "OptimalBitrate"; pub const g_wszWMHasAttachedImages = "HasAttachedImages"; pub const g_wszWMSkipBackward = "Can_Skip_Backward"; pub const g_wszWMSkipForward = "Can_Skip_Forward"; pub const g_wszWMNumberOfFrames = "NumberOfFrames"; pub const g_wszWMFileSize = "FileSize"; pub const g_wszWMHasArbitraryDataStream = "HasArbitraryDataStream"; pub const g_wszWMHasFileTransferStream = "HasFileTransferStream"; pub const g_wszWMContainerFormat = "WM/ContainerFormat"; pub const g_dwWMContentAttributes = @as(u32, 5); pub const g_wszWMTitle = "Title"; pub const g_wszWMTitleSort = "TitleSort"; pub const g_wszWMAuthor = "Author"; pub const g_wszWMAuthorSort = "AuthorSort"; pub const g_wszWMDescription = "Description"; pub const g_wszWMRating = "Rating"; pub const g_wszWMCopyright = "Copyright"; pub const g_wszWMUse_DRM = "Use_DRM"; pub const g_wszWMDRM_Flags = "DRM_Flags"; pub const g_wszWMDRM_Level = "DRM_Level"; pub const g_wszWMUse_Advanced_DRM = "Use_Advanced_DRM"; pub const g_wszWMDRM_KeySeed = "DRM_KeySeed"; pub const g_wszWMDRM_KeyID = "DRM_KeyID"; pub const g_wszWMDRM_ContentID = "DRM_ContentID"; pub const g_wszWMDRM_SourceID = "DRM_SourceID"; pub const g_wszWMDRM_IndividualizedVersion = "DRM_IndividualizedVersion"; pub const g_wszWMDRM_LicenseAcqURL = "DRM_LicenseAcqURL"; pub const g_wszWMDRM_V1LicenseAcqURL = "DRM_V1LicenseAcqURL"; pub const g_wszWMDRM_HeaderSignPrivKey = "DRM_HeaderSignPrivKey"; pub const g_wszWMDRM_LASignaturePrivKey = "DRM_LASignaturePrivKey"; pub const g_wszWMDRM_LASignatureCert = "DRM_LASignatureCert"; pub const g_wszWMDRM_LASignatureLicSrvCert = "DRM_LASignatureLicSrvCert"; pub const g_wszWMDRM_LASignatureRootCert = "DRM_LASignatureRootCert"; pub const g_wszWMAlbumTitle = "WM/AlbumTitle"; pub const g_wszWMAlbumTitleSort = "WM/AlbumTitleSort"; pub const g_wszWMTrack = "WM/Track"; pub const g_wszWMPromotionURL = "WM/PromotionURL"; pub const g_wszWMAlbumCoverURL = "WM/AlbumCoverURL"; pub const g_wszWMGenre = "WM/Genre"; pub const g_wszWMYear = "WM/Year"; pub const g_wszWMGenreID = "WM/GenreID"; pub const g_wszWMMCDI = "WM/MCDI"; pub const g_wszWMComposer = "WM/Composer"; pub const g_wszWMComposerSort = "WM/ComposerSort"; pub const g_wszWMLyrics = "WM/Lyrics"; pub const g_wszWMTrackNumber = "WM/TrackNumber"; pub const g_wszWMToolName = "WM/ToolName"; pub const g_wszWMToolVersion = "WM/ToolVersion"; pub const g_wszWMIsVBR = "IsVBR"; pub const g_wszWMAlbumArtist = "WM/AlbumArtist"; pub const g_wszWMAlbumArtistSort = "WM/AlbumArtistSort"; pub const g_wszWMBannerImageType = "BannerImageType"; pub const g_wszWMBannerImageData = "BannerImageData"; pub const g_wszWMBannerImageURL = "BannerImageURL"; pub const g_wszWMCopyrightURL = "CopyrightURL"; pub const g_wszWMAspectRatioX = "AspectRatioX"; pub const g_wszWMAspectRatioY = "AspectRatioY"; pub const g_wszASFLeakyBucketPairs = "ASFLeakyBucketPairs"; pub const g_dwWMNSCAttributes = @as(u32, 5); pub const g_wszWMNSCName = "NSC_Name"; pub const g_wszWMNSCAddress = "NSC_Address"; pub const g_wszWMNSCPhone = "NSC_Phone"; pub const g_wszWMNSCEmail = "NSC_Email"; pub const g_wszWMNSCDescription = "NSC_Description"; pub const g_wszWMWriter = "WM/Writer"; pub const g_wszWMConductor = "WM/Conductor"; pub const g_wszWMProducer = "WM/Producer"; pub const g_wszWMDirector = "WM/Director"; pub const g_wszWMContentGroupDescription = "WM/ContentGroupDescription"; pub const g_wszWMSubTitle = "WM/SubTitle"; pub const g_wszWMPartOfSet = "WM/PartOfSet"; pub const g_wszWMProtectionType = "WM/ProtectionType"; pub const g_wszWMVideoHeight = "WM/VideoHeight"; pub const g_wszWMVideoWidth = "WM/VideoWidth"; pub const g_wszWMVideoFrameRate = "WM/VideoFrameRate"; pub const g_wszWMMediaClassPrimaryID = "WM/MediaClassPrimaryID"; pub const g_wszWMMediaClassSecondaryID = "WM/MediaClassSecondaryID"; pub const g_wszWMPeriod = "WM/Period"; pub const g_wszWMCategory = "WM/Category"; pub const g_wszWMPicture = "WM/Picture"; pub const g_wszWMLyrics_Synchronised = "WM/Lyrics_Synchronised"; pub const g_wszWMOriginalLyricist = "WM/OriginalLyricist"; pub const g_wszWMOriginalArtist = "WM/OriginalArtist"; pub const g_wszWMOriginalAlbumTitle = "WM/OriginalAlbumTitle"; pub const g_wszWMOriginalReleaseYear = "WM/OriginalReleaseYear"; pub const g_wszWMOriginalFilename = "WM/OriginalFilename"; pub const g_wszWMPublisher = "WM/Publisher"; pub const g_wszWMEncodedBy = "WM/EncodedBy"; pub const g_wszWMEncodingSettings = "WM/EncodingSettings"; pub const g_wszWMEncodingTime = "WM/EncodingTime"; pub const g_wszWMAuthorURL = "WM/AuthorURL"; pub const g_wszWMUserWebURL = "WM/UserWebURL"; pub const g_wszWMAudioFileURL = "WM/AudioFileURL"; pub const g_wszWMAudioSourceURL = "WM/AudioSourceURL"; pub const g_wszWMLanguage = "WM/Language"; pub const g_wszWMParentalRating = "WM/ParentalRating"; pub const g_wszWMBeatsPerMinute = "WM/BeatsPerMinute"; pub const g_wszWMInitialKey = "WM/InitialKey"; pub const g_wszWMMood = "WM/Mood"; pub const g_wszWMText = "WM/Text"; pub const g_wszWMDVDID = "WM/DVDID"; pub const g_wszWMWMContentID = "WM/WMContentID"; pub const g_wszWMWMCollectionID = "WM/WMCollectionID"; pub const g_wszWMWMCollectionGroupID = "WM/WMCollectionGroupID"; pub const g_wszWMUniqueFileIdentifier = "WM/UniqueFileIdentifier"; pub const g_wszWMModifiedBy = "WM/ModifiedBy"; pub const g_wszWMRadioStationName = "WM/RadioStationName"; pub const g_wszWMRadioStationOwner = "WM/RadioStationOwner"; pub const g_wszWMPlaylistDelay = "WM/PlaylistDelay"; pub const g_wszWMCodec = "WM/Codec"; pub const g_wszWMDRM = "WM/DRM"; pub const g_wszWMISRC = "WM/ISRC"; pub const g_wszWMProvider = "WM/Provider"; pub const g_wszWMProviderRating = "WM/ProviderRating"; pub const g_wszWMProviderStyle = "WM/ProviderStyle"; pub const g_wszWMContentDistributor = "WM/ContentDistributor"; pub const g_wszWMSubscriptionContentID = "WM/SubscriptionContentID"; pub const g_wszWMWMADRCPeakReference = "WM/WMADRCPeakReference"; pub const g_wszWMWMADRCPeakTarget = "WM/WMADRCPeakTarget"; pub const g_wszWMWMADRCAverageReference = "WM/WMADRCAverageReference"; pub const g_wszWMWMADRCAverageTarget = "WM/WMADRCAverageTarget"; pub const g_wszWMStreamTypeInfo = "WM/StreamTypeInfo"; pub const g_wszWMPeakBitrate = "WM/PeakBitrate"; pub const g_wszWMASFPacketCount = "WM/ASFPacketCount"; pub const g_wszWMASFSecurityObjectsSize = "WM/ASFSecurityObjectsSize"; pub const g_wszWMSharedUserRating = "WM/SharedUserRating"; pub const g_wszWMSubTitleDescription = "WM/SubTitleDescription"; pub const g_wszWMMediaCredits = "WM/MediaCredits"; pub const g_wszWMParentalRatingReason = "WM/ParentalRatingReason"; pub const g_wszWMOriginalReleaseTime = "WM/OriginalReleaseTime"; pub const g_wszWMMediaStationCallSign = "WM/MediaStationCallSign"; pub const g_wszWMMediaStationName = "WM/MediaStationName"; pub const g_wszWMMediaNetworkAffiliation = "WM/MediaNetworkAffiliation"; pub const g_wszWMMediaOriginalChannel = "WM/MediaOriginalChannel"; pub const g_wszWMMediaOriginalBroadcastDateTime = "WM/MediaOriginalBroadcastDateTime"; pub const g_wszWMMediaIsStereo = "WM/MediaIsStereo"; pub const g_wszWMVideoClosedCaptioning = "WM/VideoClosedCaptioning"; pub const g_wszWMMediaIsRepeat = "WM/MediaIsRepeat"; pub const g_wszWMMediaIsLive = "WM/MediaIsLive"; pub const g_wszWMMediaIsTape = "WM/MediaIsTape"; pub const g_wszWMMediaIsDelay = "WM/MediaIsDelay"; pub const g_wszWMMediaIsSubtitled = "WM/MediaIsSubtitled"; pub const g_wszWMMediaIsPremiere = "WM/MediaIsPremiere"; pub const g_wszWMMediaIsFinale = "WM/MediaIsFinale"; pub const g_wszWMMediaIsSAP = "WM/MediaIsSAP"; pub const g_wszWMProviderCopyright = "WM/ProviderCopyright"; pub const g_wszWMISAN = "WM/ISAN"; pub const g_wszWMADID = "WM/ADID"; pub const g_wszWMWMShadowFileSourceFileType = "WM/WMShadowFileSourceFileType"; pub const g_wszWMWMShadowFileSourceDRMType = "WM/WMShadowFileSourceDRMType"; pub const g_wszWMWMCPDistributor = "WM/WMCPDistributor"; pub const g_wszWMWMCPDistributorID = "WM/WMCPDistributorID"; pub const g_wszWMSeasonNumber = "WM/SeasonNumber"; pub const g_wszWMEpisodeNumber = "WM/EpisodeNumber"; pub const g_wszEarlyDataDelivery = "EarlyDataDelivery"; pub const g_wszJustInTimeDecode = "JustInTimeDecode"; pub const g_wszSingleOutputBuffer = "SingleOutputBuffer"; pub const g_wszSoftwareScaling = "SoftwareScaling"; pub const g_wszDeliverOnReceive = "DeliverOnReceive"; pub const g_wszScrambledAudio = "ScrambledAudio"; pub const g_wszDedicatedDeliveryThread = "DedicatedDeliveryThread"; pub const g_wszEnableDiscreteOutput = "EnableDiscreteOutput"; pub const g_wszSpeakerConfig = "SpeakerConfig"; pub const g_wszDynamicRangeControl = "DynamicRangeControl"; pub const g_wszAllowInterlacedOutput = "AllowInterlacedOutput"; pub const g_wszVideoSampleDurations = "VideoSampleDurations"; pub const g_wszStreamLanguage = "StreamLanguage"; pub const g_wszEnableWMAProSPDIFOutput = "EnableWMAProSPDIFOutput"; pub const g_wszDeinterlaceMode = "DeinterlaceMode"; pub const g_wszInitialPatternForInverseTelecine = "InitialPatternForInverseTelecine"; pub const g_wszJPEGCompressionQuality = "JPEGCompressionQuality"; pub const g_wszWatermarkCLSID = "WatermarkCLSID"; pub const g_wszWatermarkConfig = "WatermarkConfig"; pub const g_wszInterlacedCoding = "InterlacedCoding"; pub const g_wszFixedFrameRate = "FixedFrameRate"; pub const g_wszOriginalSourceFormatTag = "_SOURCEFORMATTAG"; pub const g_wszOriginalWaveFormat = "_ORIGINALWAVEFORMAT"; pub const g_wszEDL = "_EDL"; pub const g_wszComplexity = "_COMPLEXITYEX"; pub const g_wszDecoderComplexityRequested = "_DECODERCOMPLEXITYPROFILE"; pub const g_wszReloadIndexOnSeek = "ReloadIndexOnSeek"; pub const g_wszStreamNumIndexObjects = "StreamNumIndexObjects"; pub const g_wszFailSeekOnError = "FailSeekOnError"; pub const g_wszPermitSeeksBeyondEndOfStream = "PermitSeeksBeyondEndOfStream"; pub const g_wszUsePacketAtSeekPoint = "UsePacketAtSeekPoint"; pub const g_wszSourceBufferTime = "SourceBufferTime"; pub const g_wszSourceMaxBytesAtOnce = "SourceMaxBytesAtOnce"; pub const g_wszVBREnabled = "_VBRENABLED"; pub const g_wszVBRQuality = "_VBRQUALITY"; pub const g_wszVBRBitrateMax = "_RMAX"; pub const g_wszVBRBufferWindowMax = "_BMAX"; pub const g_wszVBRPeak = "VBR Peak"; pub const g_wszBufferAverage = "Buffer Average"; pub const g_wszComplexityMax = "_COMPLEXITYEXMAX"; pub const g_wszComplexityOffline = "_COMPLEXITYEXOFFLINE"; pub const g_wszComplexityLive = "_COMPLEXITYEXLIVE"; pub const g_wszIsVBRSupported = "_ISVBRSUPPORTED"; pub const g_wszNumPasses = "_PASSESUSED"; pub const g_wszMusicSpeechClassMode = "MusicSpeechClassMode"; pub const g_wszMusicClassMode = "MusicClassMode"; pub const g_wszSpeechClassMode = "SpeechClassMode"; pub const g_wszMixedClassMode = "MixedClassMode"; pub const g_wszSpeechCaps = "SpeechFormatCap"; pub const g_wszPeakValue = "PeakValue"; pub const g_wszAverageLevel = "AverageLevel"; pub const g_wszFold6To2Channels3 = "Fold6To2Channels3"; pub const g_wszFoldToChannelsTemplate = "Fold%luTo%luChannels%lu"; pub const g_wszDeviceConformanceTemplate = "DeviceConformanceTemplate"; pub const g_wszEnableFrameInterpolation = "EnableFrameInterpolation"; pub const g_wszNeedsPreviousSample = "NeedsPreviousSample"; pub const g_wszWMIsCompilation = "WM/IsCompilation"; pub const WMMEDIASUBTYPE_Base = Guid.initString("00000000-0000-0010-8000-00aa00389b71"); pub const WMMEDIATYPE_Video = Guid.initString("73646976-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_RGB1 = Guid.initString("e436eb78-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB4 = Guid.initString("e436eb79-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB8 = Guid.initString("e436eb7a-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB565 = Guid.initString("e436eb7b-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB555 = Guid.initString("e436eb7c-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB24 = Guid.initString("e436eb7d-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_RGB32 = Guid.initString("e436eb7e-524f-11ce-9f53-0020af0ba770"); pub const WMMEDIASUBTYPE_I420 = Guid.initString("30323449-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_IYUV = Guid.initString("56555949-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_YV12 = Guid.initString("32315659-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_YUY2 = Guid.initString("32595559-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_P422 = Guid.initString("32323450-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_UYVY = Guid.initString("59565955-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_YVYU = Guid.initString("55595659-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_YVU9 = Guid.initString("39555659-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_VIDEOIMAGE = Guid.initString("1d4a45f2-e5f6-4b44-8388-f0ae5c0e0c37"); pub const WMMEDIASUBTYPE_MP43 = Guid.initString("3334504d-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_MP4S = Guid.initString("5334504d-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_M4S2 = Guid.initString("3253344d-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMV1 = Guid.initString("31564d57-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMV2 = Guid.initString("32564d57-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_MSS1 = Guid.initString("3153534d-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_MPEG2_VIDEO = Guid.initString("e06d8026-db46-11cf-b4d1-00805f6cbbea"); pub const WMMEDIATYPE_Audio = Guid.initString("73647561-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_PCM = Guid.initString("00000001-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_DRM = Guid.initString("00000009-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMAudioV9 = Guid.initString("00000162-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMAudio_Lossless = Guid.initString("00000163-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_MSS2 = Guid.initString("3253534d-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMSP1 = Guid.initString("0000000a-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMSP2 = Guid.initString("0000000b-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMV3 = Guid.initString("33564d57-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMVP = Guid.initString("50564d57-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WVP2 = Guid.initString("32505657-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMVA = Guid.initString("41564d57-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WVC1 = Guid.initString("31435657-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMAudioV8 = Guid.initString("00000161-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMAudioV7 = Guid.initString("00000161-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WMAudioV2 = Guid.initString("00000161-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_ACELPnet = Guid.initString("00000130-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_MP3 = Guid.initString("00000055-0000-0010-8000-00aa00389b71"); pub const WMMEDIASUBTYPE_WebStream = Guid.initString("776257d4-c627-41cb-8f81-7ac7ff1c40cc"); pub const WMMEDIATYPE_Script = Guid.initString("73636d64-0000-0010-8000-00aa00389b71"); pub const WMMEDIATYPE_Image = Guid.initString("34a50fd8-8aa5-4386-81fe-a0efe0488e31"); pub const WMMEDIATYPE_FileTransfer = Guid.initString("d9e47579-930e-4427-adfc-ad80f290e470"); pub const WMMEDIATYPE_Text = Guid.initString("9bba1ea7-5ab2-4829-ba57-0940209bcf3e"); pub const WMFORMAT_VideoInfo = Guid.initString("05589f80-c356-11ce-bf01-00aa0055595a"); pub const WMFORMAT_MPEG2Video = Guid.initString("e06d80e3-db46-11cf-b4d1-00805f6cbbea"); pub const WMFORMAT_WaveFormatEx = Guid.initString("05589f81-c356-11ce-bf01-00aa0055595a"); pub const WMFORMAT_Script = Guid.initString("5c8510f2-debe-4ca7-bba5-f07a104f8dff"); pub const WMFORMAT_WebStream = Guid.initString("da1e6b13-8359-4050-b398-388e965bf00c"); pub const WMSCRIPTTYPE_TwoStrings = Guid.initString("82f38a70-c29f-11d1-97ad-00a0c95ea850"); pub const WM_SampleExtensionGUID_OutputCleanPoint = Guid.initString("f72a3c6f-6eb4-4ebc-b192-09ad9759e828"); pub const WM_SampleExtensionGUID_Timecode = Guid.initString("399595ec-8667-4e2d-8fdb-98814ce76c1e"); pub const WM_SampleExtensionGUID_ChromaLocation = Guid.initString("4c5acca0-9276-4b2c-9e4c-a0edefdd217e"); pub const WM_SampleExtensionGUID_ColorSpaceInfo = Guid.initString("f79ada56-30eb-4f2b-9f7a-f24b139a1157"); pub const WM_SampleExtensionGUID_UserDataInfo = Guid.initString("732bb4fa-78be-4549-99bd-02db1a55b7a8"); pub const WM_SampleExtensionGUID_FileName = Guid.initString("e165ec0e-19ed-45d7-b4a7-25cbd1e28e9b"); pub const WM_SampleExtensionGUID_ContentType = Guid.initString("d590dc20-07bc-436c-9cf7-f3bbfbf1a4dc"); pub const WM_SampleExtensionGUID_PixelAspectRatio = Guid.initString("1b1ee554-f9ea-4bc8-821a-376b74e4c4b8"); pub const WM_SampleExtensionGUID_SampleDuration = Guid.initString("c6bd9450-867f-4907-83a3-c77921b733ad"); pub const WM_SampleExtensionGUID_SampleProtectionSalt = Guid.initString("5403deee-b9ee-438f-aa83-3804997e569d"); pub const CLSID_WMMUTEX_Language = Guid.initString("d6e22a00-35da-11d1-9034-00a0c90349be"); pub const CLSID_WMMUTEX_Bitrate = Guid.initString("d6e22a01-35da-11d1-9034-00a0c90349be"); pub const CLSID_WMMUTEX_Presentation = Guid.initString("d6e22a02-35da-11d1-9034-00a0c90349be"); pub const CLSID_WMMUTEX_Unknown = Guid.initString("d6e22a03-35da-11d1-9034-00a0c90349be"); pub const CLSID_WMBandwidthSharing_Exclusive = Guid.initString("af6060aa-5197-11d2-b6af-00c04fd908e9"); pub const CLSID_WMBandwidthSharing_Partial = Guid.initString("af6060ab-5197-11d2-b6af-00c04fd908e9"); pub const WMT_DMOCATEGORY_AUDIO_WATERMARK = Guid.initString("65221c5a-fa75-4b39-b50c-06c336b6a3ef"); pub const WMT_DMOCATEGORY_VIDEO_WATERMARK = Guid.initString("187cc922-8efc-4404-9daf-63f4830df1bc"); pub const CLSID_ClientNetManager = Guid.initString("cd12a3ce-9c42-11d2-beed-0060082f2054"); //-------------------------------------------------------------------------------- // Section: Types (180) //-------------------------------------------------------------------------------- const IID_IAMWMBufferPass_Value = Guid.initString("6dd816d7-e740-4123-9e24-2444412644d8"); pub const IID_IAMWMBufferPass = &IID_IAMWMBufferPass_Value; pub const IAMWMBufferPass = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetNotify: fn( self: *const IAMWMBufferPass, pCallback: ?*IAMWMBufferPassCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAMWMBufferPass_SetNotify(self: *const T, pCallback: ?*IAMWMBufferPassCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IAMWMBufferPass.VTable, self.vtable).SetNotify(@ptrCast(*const IAMWMBufferPass, self), pCallback); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IAMWMBufferPassCallback_Value = Guid.initString("b25b8372-d2d2-44b2-8653-1b8dae332489"); pub const IID_IAMWMBufferPassCallback = &IID_IAMWMBufferPassCallback_Value; pub const IAMWMBufferPassCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Notify: fn( self: *const IAMWMBufferPassCallback, pNSSBuffer3: ?*INSSBuffer3, pPin: ?*IPin, prtStart: ?*i64, prtEnd: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAMWMBufferPassCallback_Notify(self: *const T, pNSSBuffer3: ?*INSSBuffer3, pPin: ?*IPin, prtStart: ?*i64, prtEnd: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IAMWMBufferPassCallback.VTable, self.vtable).Notify(@ptrCast(*const IAMWMBufferPassCallback, self), pNSSBuffer3, pPin, prtStart, prtEnd); } };} pub usingnamespace MethodMixin(@This()); }; pub const _AM_ASFWRITERCONFIG_PARAM = enum(i32) { AUTOINDEX = 1, MULTIPASS = 2, DONTCOMPRESS = 3, }; pub const AM_CONFIGASFWRITER_PARAM_AUTOINDEX = _AM_ASFWRITERCONFIG_PARAM.AUTOINDEX; pub const AM_CONFIGASFWRITER_PARAM_MULTIPASS = _AM_ASFWRITERCONFIG_PARAM.MULTIPASS; pub const AM_CONFIGASFWRITER_PARAM_DONTCOMPRESS = _AM_ASFWRITERCONFIG_PARAM.DONTCOMPRESS; pub const AM_WMT_EVENT_DATA = extern struct { hrStatus: HRESULT, pData: ?*anyopaque, }; const IID_INSSBuffer_Value = Guid.initString("e1cd3524-03d7-11d2-9eed-006097d2d7cf"); pub const IID_INSSBuffer = &IID_INSSBuffer_Value; pub const INSSBuffer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLength: fn( self: *const INSSBuffer, pdwLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLength: fn( self: *const INSSBuffer, dwLength: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxLength: fn( self: *const INSSBuffer, pdwLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBuffer: fn( self: *const INSSBuffer, ppdwBuffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBufferAndLength: fn( self: *const INSSBuffer, ppdwBuffer: ?*?*u8, pdwLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer_GetLength(self: *const T, pdwLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer.VTable, self.vtable).GetLength(@ptrCast(*const INSSBuffer, self), pdwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer_SetLength(self: *const T, dwLength: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer.VTable, self.vtable).SetLength(@ptrCast(*const INSSBuffer, self), dwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer_GetMaxLength(self: *const T, pdwLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer.VTable, self.vtable).GetMaxLength(@ptrCast(*const INSSBuffer, self), pdwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer_GetBuffer(self: *const T, ppdwBuffer: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer.VTable, self.vtable).GetBuffer(@ptrCast(*const INSSBuffer, self), ppdwBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer_GetBufferAndLength(self: *const T, ppdwBuffer: ?*?*u8, pdwLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer.VTable, self.vtable).GetBufferAndLength(@ptrCast(*const INSSBuffer, self), ppdwBuffer, pdwLength); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INSSBuffer2_Value = Guid.initString("4f528693-1035-43fe-b428-757561ad3a68"); pub const IID_INSSBuffer2 = &IID_INSSBuffer2_Value; pub const INSSBuffer2 = extern struct { pub const VTable = extern struct { base: INSSBuffer.VTable, GetSampleProperties: fn( self: *const INSSBuffer2, cbProperties: u32, pbProperties: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSampleProperties: fn( self: *const INSSBuffer2, cbProperties: u32, pbProperties: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace INSSBuffer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer2_GetSampleProperties(self: *const T, cbProperties: u32, pbProperties: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer2.VTable, self.vtable).GetSampleProperties(@ptrCast(*const INSSBuffer2, self), cbProperties, pbProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer2_SetSampleProperties(self: *const T, cbProperties: u32, pbProperties: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer2.VTable, self.vtable).SetSampleProperties(@ptrCast(*const INSSBuffer2, self), cbProperties, pbProperties); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INSSBuffer3_Value = Guid.initString("c87ceaaf-75be-4bc4-84eb-ac2798507672"); pub const IID_INSSBuffer3 = &IID_INSSBuffer3_Value; pub const INSSBuffer3 = extern struct { pub const VTable = extern struct { base: INSSBuffer2.VTable, SetProperty: fn( self: *const INSSBuffer3, guidBufferProperty: Guid, pvBufferProperty: ?*anyopaque, dwBufferPropertySize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const INSSBuffer3, guidBufferProperty: Guid, pvBufferProperty: ?*anyopaque, pdwBufferPropertySize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace INSSBuffer2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer3_SetProperty(self: *const T, guidBufferProperty: Guid, pvBufferProperty: ?*anyopaque, dwBufferPropertySize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer3.VTable, self.vtable).SetProperty(@ptrCast(*const INSSBuffer3, self), guidBufferProperty, pvBufferProperty, dwBufferPropertySize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer3_GetProperty(self: *const T, guidBufferProperty: Guid, pvBufferProperty: ?*anyopaque, pdwBufferPropertySize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer3.VTable, self.vtable).GetProperty(@ptrCast(*const INSSBuffer3, self), guidBufferProperty, pvBufferProperty, pdwBufferPropertySize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INSSBuffer4_Value = Guid.initString("b6b8fd5a-32e2-49d4-a910-c26cc85465ed"); pub const IID_INSSBuffer4 = &IID_INSSBuffer4_Value; pub const INSSBuffer4 = extern struct { pub const VTable = extern struct { base: INSSBuffer3.VTable, GetPropertyCount: fn( self: *const INSSBuffer4, pcBufferProperties: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyByIndex: fn( self: *const INSSBuffer4, dwBufferPropertyIndex: u32, pguidBufferProperty: ?*Guid, pvBufferProperty: ?*anyopaque, pdwBufferPropertySize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace INSSBuffer3.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer4_GetPropertyCount(self: *const T, pcBufferProperties: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer4.VTable, self.vtable).GetPropertyCount(@ptrCast(*const INSSBuffer4, self), pcBufferProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSSBuffer4_GetPropertyByIndex(self: *const T, dwBufferPropertyIndex: u32, pguidBufferProperty: ?*Guid, pvBufferProperty: ?*anyopaque, pdwBufferPropertySize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSSBuffer4.VTable, self.vtable).GetPropertyByIndex(@ptrCast(*const INSSBuffer4, self), dwBufferPropertyIndex, pguidBufferProperty, pvBufferProperty, pdwBufferPropertySize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMSBufferAllocator_Value = Guid.initString("61103ca4-2033-11d2-9ef1-006097d2d7cf"); pub const IID_IWMSBufferAllocator = &IID_IWMSBufferAllocator_Value; pub const IWMSBufferAllocator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AllocateBuffer: fn( self: *const IWMSBufferAllocator, dwMaxBufferSize: u32, ppBuffer: ?*?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocatePageSizeBuffer: fn( self: *const IWMSBufferAllocator, dwMaxBufferSize: u32, ppBuffer: ?*?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSBufferAllocator_AllocateBuffer(self: *const T, dwMaxBufferSize: u32, ppBuffer: ?*?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSBufferAllocator.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IWMSBufferAllocator, self), dwMaxBufferSize, ppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSBufferAllocator_AllocatePageSizeBuffer(self: *const T, dwMaxBufferSize: u32, ppBuffer: ?*?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSBufferAllocator.VTable, self.vtable).AllocatePageSizeBuffer(@ptrCast(*const IWMSBufferAllocator, self), dwMaxBufferSize, ppBuffer); } };} pub usingnamespace MethodMixin(@This()); }; pub const WEBSTREAM_SAMPLE_TYPE = enum(i32) { FILE = 1, RENDER = 2, }; pub const WEBSTREAM_SAMPLE_TYPE_FILE = WEBSTREAM_SAMPLE_TYPE.FILE; pub const WEBSTREAM_SAMPLE_TYPE_RENDER = WEBSTREAM_SAMPLE_TYPE.RENDER; pub const WM_SF_TYPE = enum(i32) { CLEANPOINT = 1, DISCONTINUITY = 2, DATALOSS = 4, }; pub const WM_SF_CLEANPOINT = WM_SF_TYPE.CLEANPOINT; pub const WM_SF_DISCONTINUITY = WM_SF_TYPE.DISCONTINUITY; pub const WM_SF_DATALOSS = WM_SF_TYPE.DATALOSS; pub const WM_SFEX_TYPE = enum(i32) { NOTASYNCPOINT = 2, DATALOSS = 4, }; pub const WM_SFEX_NOTASYNCPOINT = WM_SFEX_TYPE.NOTASYNCPOINT; pub const WM_SFEX_DATALOSS = WM_SFEX_TYPE.DATALOSS; pub const WMT_STATUS = enum(i32) { ERROR = 0, OPENED = 1, BUFFERING_START = 2, BUFFERING_STOP = 3, EOF = 4, // END_OF_FILE = 4, this enum value conflicts with EOF END_OF_SEGMENT = 5, END_OF_STREAMING = 6, LOCATING = 7, CONNECTING = 8, NO_RIGHTS = 9, MISSING_CODEC = 10, STARTED = 11, STOPPED = 12, CLOSED = 13, STRIDING = 14, TIMER = 15, INDEX_PROGRESS = 16, SAVEAS_START = 17, SAVEAS_STOP = 18, NEW_SOURCEFLAGS = 19, NEW_METADATA = 20, BACKUPRESTORE_BEGIN = 21, SOURCE_SWITCH = 22, ACQUIRE_LICENSE = 23, INDIVIDUALIZE = 24, NEEDS_INDIVIDUALIZATION = 25, NO_RIGHTS_EX = 26, BACKUPRESTORE_END = 27, BACKUPRESTORE_CONNECTING = 28, BACKUPRESTORE_DISCONNECTING = 29, ERROR_WITHURL = 30, RESTRICTED_LICENSE = 31, CLIENT_CONNECT = 32, CLIENT_DISCONNECT = 33, NATIVE_OUTPUT_PROPS_CHANGED = 34, RECONNECT_START = 35, RECONNECT_END = 36, CLIENT_CONNECT_EX = 37, CLIENT_DISCONNECT_EX = 38, SET_FEC_SPAN = 39, PREROLL_READY = 40, PREROLL_COMPLETE = 41, CLIENT_PROPERTIES = 42, LICENSEURL_SIGNATURE_STATE = 43, INIT_PLAYLIST_BURN = 44, TRANSCRYPTOR_INIT = 45, TRANSCRYPTOR_SEEKED = 46, TRANSCRYPTOR_READ = 47, TRANSCRYPTOR_CLOSED = 48, PROXIMITY_RESULT = 49, PROXIMITY_COMPLETED = 50, CONTENT_ENABLER = 51, }; pub const WMT_ERROR = WMT_STATUS.ERROR; pub const WMT_OPENED = WMT_STATUS.OPENED; pub const WMT_BUFFERING_START = WMT_STATUS.BUFFERING_START; pub const WMT_BUFFERING_STOP = WMT_STATUS.BUFFERING_STOP; pub const WMT_EOF = WMT_STATUS.EOF; pub const WMT_END_OF_FILE = WMT_STATUS.EOF; pub const WMT_END_OF_SEGMENT = WMT_STATUS.END_OF_SEGMENT; pub const WMT_END_OF_STREAMING = WMT_STATUS.END_OF_STREAMING; pub const WMT_LOCATING = WMT_STATUS.LOCATING; pub const WMT_CONNECTING = WMT_STATUS.CONNECTING; pub const WMT_NO_RIGHTS = WMT_STATUS.NO_RIGHTS; pub const WMT_MISSING_CODEC = WMT_STATUS.MISSING_CODEC; pub const WMT_STARTED = WMT_STATUS.STARTED; pub const WMT_STOPPED = WMT_STATUS.STOPPED; pub const WMT_CLOSED = WMT_STATUS.CLOSED; pub const WMT_STRIDING = WMT_STATUS.STRIDING; pub const WMT_TIMER = WMT_STATUS.TIMER; pub const WMT_INDEX_PROGRESS = WMT_STATUS.INDEX_PROGRESS; pub const WMT_SAVEAS_START = WMT_STATUS.SAVEAS_START; pub const WMT_SAVEAS_STOP = WMT_STATUS.SAVEAS_STOP; pub const WMT_NEW_SOURCEFLAGS = WMT_STATUS.NEW_SOURCEFLAGS; pub const WMT_NEW_METADATA = WMT_STATUS.NEW_METADATA; pub const WMT_BACKUPRESTORE_BEGIN = WMT_STATUS.BACKUPRESTORE_BEGIN; pub const WMT_SOURCE_SWITCH = WMT_STATUS.SOURCE_SWITCH; pub const WMT_ACQUIRE_LICENSE = WMT_STATUS.ACQUIRE_LICENSE; pub const WMT_INDIVIDUALIZE = WMT_STATUS.INDIVIDUALIZE; pub const WMT_NEEDS_INDIVIDUALIZATION = WMT_STATUS.NEEDS_INDIVIDUALIZATION; pub const WMT_NO_RIGHTS_EX = WMT_STATUS.NO_RIGHTS_EX; pub const WMT_BACKUPRESTORE_END = WMT_STATUS.BACKUPRESTORE_END; pub const WMT_BACKUPRESTORE_CONNECTING = WMT_STATUS.BACKUPRESTORE_CONNECTING; pub const WMT_BACKUPRESTORE_DISCONNECTING = WMT_STATUS.BACKUPRESTORE_DISCONNECTING; pub const WMT_ERROR_WITHURL = WMT_STATUS.ERROR_WITHURL; pub const WMT_RESTRICTED_LICENSE = WMT_STATUS.RESTRICTED_LICENSE; pub const WMT_CLIENT_CONNECT = WMT_STATUS.CLIENT_CONNECT; pub const WMT_CLIENT_DISCONNECT = WMT_STATUS.CLIENT_DISCONNECT; pub const WMT_NATIVE_OUTPUT_PROPS_CHANGED = WMT_STATUS.NATIVE_OUTPUT_PROPS_CHANGED; pub const WMT_RECONNECT_START = WMT_STATUS.RECONNECT_START; pub const WMT_RECONNECT_END = WMT_STATUS.RECONNECT_END; pub const WMT_CLIENT_CONNECT_EX = WMT_STATUS.CLIENT_CONNECT_EX; pub const WMT_CLIENT_DISCONNECT_EX = WMT_STATUS.CLIENT_DISCONNECT_EX; pub const WMT_SET_FEC_SPAN = WMT_STATUS.SET_FEC_SPAN; pub const WMT_PREROLL_READY = WMT_STATUS.PREROLL_READY; pub const WMT_PREROLL_COMPLETE = WMT_STATUS.PREROLL_COMPLETE; pub const WMT_CLIENT_PROPERTIES = WMT_STATUS.CLIENT_PROPERTIES; pub const WMT_LICENSEURL_SIGNATURE_STATE = WMT_STATUS.LICENSEURL_SIGNATURE_STATE; pub const WMT_INIT_PLAYLIST_BURN = WMT_STATUS.INIT_PLAYLIST_BURN; pub const WMT_TRANSCRYPTOR_INIT = WMT_STATUS.TRANSCRYPTOR_INIT; pub const WMT_TRANSCRYPTOR_SEEKED = WMT_STATUS.TRANSCRYPTOR_SEEKED; pub const WMT_TRANSCRYPTOR_READ = WMT_STATUS.TRANSCRYPTOR_READ; pub const WMT_TRANSCRYPTOR_CLOSED = WMT_STATUS.TRANSCRYPTOR_CLOSED; pub const WMT_PROXIMITY_RESULT = WMT_STATUS.PROXIMITY_RESULT; pub const WMT_PROXIMITY_COMPLETED = WMT_STATUS.PROXIMITY_COMPLETED; pub const WMT_CONTENT_ENABLER = WMT_STATUS.CONTENT_ENABLER; pub const WMT_STREAM_SELECTION = enum(i32) { OFF = 0, CLEANPOINT_ONLY = 1, ON = 2, }; pub const WMT_OFF = WMT_STREAM_SELECTION.OFF; pub const WMT_CLEANPOINT_ONLY = WMT_STREAM_SELECTION.CLEANPOINT_ONLY; pub const WMT_ON = WMT_STREAM_SELECTION.ON; pub const WMT_IMAGE_TYPE = enum(i32) { NONE = 0, BITMAP = 1, JPEG = 2, GIF = 3, }; pub const WMT_IT_NONE = WMT_IMAGE_TYPE.NONE; pub const WMT_IT_BITMAP = WMT_IMAGE_TYPE.BITMAP; pub const WMT_IT_JPEG = WMT_IMAGE_TYPE.JPEG; pub const WMT_IT_GIF = WMT_IMAGE_TYPE.GIF; pub const WMT_ATTR_DATATYPE = enum(i32) { DWORD = 0, STRING = 1, BINARY = 2, BOOL = 3, QWORD = 4, WORD = 5, GUID = 6, }; pub const WMT_TYPE_DWORD = WMT_ATTR_DATATYPE.DWORD; pub const WMT_TYPE_STRING = WMT_ATTR_DATATYPE.STRING; pub const WMT_TYPE_BINARY = WMT_ATTR_DATATYPE.BINARY; pub const WMT_TYPE_BOOL = WMT_ATTR_DATATYPE.BOOL; pub const WMT_TYPE_QWORD = WMT_ATTR_DATATYPE.QWORD; pub const WMT_TYPE_WORD = WMT_ATTR_DATATYPE.WORD; pub const WMT_TYPE_GUID = WMT_ATTR_DATATYPE.GUID; pub const WMT_ATTR_IMAGETYPE = enum(i32) { BITMAP = 1, JPEG = 2, GIF = 3, }; pub const WMT_IMAGETYPE_BITMAP = WMT_ATTR_IMAGETYPE.BITMAP; pub const WMT_IMAGETYPE_JPEG = WMT_ATTR_IMAGETYPE.JPEG; pub const WMT_IMAGETYPE_GIF = WMT_ATTR_IMAGETYPE.GIF; pub const WMT_VERSION = enum(i32) { @"4_0" = 262144, @"7_0" = 458752, @"8_0" = 524288, @"9_0" = 589824, }; pub const WMT_VER_4_0 = WMT_VERSION.@"4_0"; pub const WMT_VER_7_0 = WMT_VERSION.@"7_0"; pub const WMT_VER_8_0 = WMT_VERSION.@"8_0"; pub const WMT_VER_9_0 = WMT_VERSION.@"9_0"; pub const WMT_STORAGE_FORMAT = enum(i32) { MP3 = 0, V1 = 1, }; pub const WMT_Storage_Format_MP3 = WMT_STORAGE_FORMAT.MP3; pub const WMT_Storage_Format_V1 = WMT_STORAGE_FORMAT.V1; pub const WMT_DRMLA_TRUST = enum(i32) { UNTRUSTED = 0, TRUSTED = 1, TAMPERED = 2, }; pub const WMT_DRMLA_UNTRUSTED = WMT_DRMLA_TRUST.UNTRUSTED; pub const WMT_DRMLA_TRUSTED = WMT_DRMLA_TRUST.TRUSTED; pub const WMT_DRMLA_TAMPERED = WMT_DRMLA_TRUST.TAMPERED; pub const WMT_TRANSPORT_TYPE = enum(i32) { Unreliable = 0, Reliable = 1, }; pub const WMT_Transport_Type_Unreliable = WMT_TRANSPORT_TYPE.Unreliable; pub const WMT_Transport_Type_Reliable = WMT_TRANSPORT_TYPE.Reliable; pub const WMT_NET_PROTOCOL = enum(i32) { P = 0, }; pub const WMT_PROTOCOL_HTTP = WMT_NET_PROTOCOL.P; pub const WMT_PLAY_MODE = enum(i32) { AUTOSELECT = 0, LOCAL = 1, DOWNLOAD = 2, STREAMING = 3, }; pub const WMT_PLAY_MODE_AUTOSELECT = WMT_PLAY_MODE.AUTOSELECT; pub const WMT_PLAY_MODE_LOCAL = WMT_PLAY_MODE.LOCAL; pub const WMT_PLAY_MODE_DOWNLOAD = WMT_PLAY_MODE.DOWNLOAD; pub const WMT_PLAY_MODE_STREAMING = WMT_PLAY_MODE.STREAMING; pub const WMT_PROXY_SETTINGS = enum(i32) { NONE = 0, MANUAL = 1, AUTO = 2, BROWSER = 3, MAX = 4, }; pub const WMT_PROXY_SETTING_NONE = WMT_PROXY_SETTINGS.NONE; pub const WMT_PROXY_SETTING_MANUAL = WMT_PROXY_SETTINGS.MANUAL; pub const WMT_PROXY_SETTING_AUTO = WMT_PROXY_SETTINGS.AUTO; pub const WMT_PROXY_SETTING_BROWSER = WMT_PROXY_SETTINGS.BROWSER; pub const WMT_PROXY_SETTING_MAX = WMT_PROXY_SETTINGS.MAX; pub const WMT_CODEC_INFO_TYPE = enum(i32) { AUDIO = 0, VIDEO = 1, UNKNOWN = -1, }; pub const WMT_CODECINFO_AUDIO = WMT_CODEC_INFO_TYPE.AUDIO; pub const WMT_CODECINFO_VIDEO = WMT_CODEC_INFO_TYPE.VIDEO; pub const WMT_CODECINFO_UNKNOWN = WMT_CODEC_INFO_TYPE.UNKNOWN; pub const WM_DM_INTERLACED_TYPE = enum(i32) { NOTINTERLACED = 0, DEINTERLACE_NORMAL = 1, DEINTERLACE_HALFSIZE = 2, DEINTERLACE_HALFSIZEDOUBLERATE = 3, DEINTERLACE_INVERSETELECINE = 4, DEINTERLACE_VERTICALHALFSIZEDOUBLERATE = 5, }; pub const WM_DM_NOTINTERLACED = WM_DM_INTERLACED_TYPE.NOTINTERLACED; pub const WM_DM_DEINTERLACE_NORMAL = WM_DM_INTERLACED_TYPE.DEINTERLACE_NORMAL; pub const WM_DM_DEINTERLACE_HALFSIZE = WM_DM_INTERLACED_TYPE.DEINTERLACE_HALFSIZE; pub const WM_DM_DEINTERLACE_HALFSIZEDOUBLERATE = WM_DM_INTERLACED_TYPE.DEINTERLACE_HALFSIZEDOUBLERATE; pub const WM_DM_DEINTERLACE_INVERSETELECINE = WM_DM_INTERLACED_TYPE.DEINTERLACE_INVERSETELECINE; pub const WM_DM_DEINTERLACE_VERTICALHALFSIZEDOUBLERATE = WM_DM_INTERLACED_TYPE.DEINTERLACE_VERTICALHALFSIZEDOUBLERATE; pub const WM_DM_IT_FIRST_FRAME_COHERENCY = enum(i32) { DISABLE_COHERENT_MODE = 0, FIRST_FRAME_IN_CLIP_IS_AA_TOP = 1, FIRST_FRAME_IN_CLIP_IS_BB_TOP = 2, FIRST_FRAME_IN_CLIP_IS_BC_TOP = 3, FIRST_FRAME_IN_CLIP_IS_CD_TOP = 4, FIRST_FRAME_IN_CLIP_IS_DD_TOP = 5, FIRST_FRAME_IN_CLIP_IS_AA_BOTTOM = 6, FIRST_FRAME_IN_CLIP_IS_BB_BOTTOM = 7, FIRST_FRAME_IN_CLIP_IS_BC_BOTTOM = 8, FIRST_FRAME_IN_CLIP_IS_CD_BOTTOM = 9, FIRST_FRAME_IN_CLIP_IS_DD_BOTTOM = 10, }; pub const WM_DM_IT_DISABLE_COHERENT_MODE = WM_DM_IT_FIRST_FRAME_COHERENCY.DISABLE_COHERENT_MODE; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_AA_TOP = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_AA_TOP; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_BB_TOP = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_BB_TOP; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_BC_TOP = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_BC_TOP; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_CD_TOP = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_CD_TOP; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_DD_TOP = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_DD_TOP; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_AA_BOTTOM = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_AA_BOTTOM; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_BB_BOTTOM = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_BB_BOTTOM; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_BC_BOTTOM = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_BC_BOTTOM; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_CD_BOTTOM = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_CD_BOTTOM; pub const WM_DM_IT_FIRST_FRAME_IN_CLIP_IS_DD_BOTTOM = WM_DM_IT_FIRST_FRAME_COHERENCY.FIRST_FRAME_IN_CLIP_IS_DD_BOTTOM; pub const WMT_OFFSET_FORMAT = enum(i32) { @"100NS" = 0, FRAME_NUMBERS = 1, PLAYLIST_OFFSET = 2, TIMECODE = 3, @"100NS_APPROXIMATE" = 4, }; pub const WMT_OFFSET_FORMAT_100NS = WMT_OFFSET_FORMAT.@"100NS"; pub const WMT_OFFSET_FORMAT_FRAME_NUMBERS = WMT_OFFSET_FORMAT.FRAME_NUMBERS; pub const WMT_OFFSET_FORMAT_PLAYLIST_OFFSET = WMT_OFFSET_FORMAT.PLAYLIST_OFFSET; pub const WMT_OFFSET_FORMAT_TIMECODE = WMT_OFFSET_FORMAT.TIMECODE; pub const WMT_OFFSET_FORMAT_100NS_APPROXIMATE = WMT_OFFSET_FORMAT.@"100NS_APPROXIMATE"; pub const WMT_INDEXER_TYPE = enum(i32) { PRESENTATION_TIME = 0, FRAME_NUMBERS = 1, TIMECODE = 2, }; pub const WMT_IT_PRESENTATION_TIME = WMT_INDEXER_TYPE.PRESENTATION_TIME; pub const WMT_IT_FRAME_NUMBERS = WMT_INDEXER_TYPE.FRAME_NUMBERS; pub const WMT_IT_TIMECODE = WMT_INDEXER_TYPE.TIMECODE; pub const WMT_INDEX_TYPE = enum(i32) { DATA_UNIT = 1, OBJECT = 2, CLEAN_POINT = 3, }; pub const WMT_IT_NEAREST_DATA_UNIT = WMT_INDEX_TYPE.DATA_UNIT; pub const WMT_IT_NEAREST_OBJECT = WMT_INDEX_TYPE.OBJECT; pub const WMT_IT_NEAREST_CLEAN_POINT = WMT_INDEX_TYPE.CLEAN_POINT; pub const WMT_FILESINK_MODE = enum(i32) { SINGLE_BUFFERS = 1, FILESINK_DATA_UNITS = 2, FILESINK_UNBUFFERED = 4, }; pub const WMT_FM_SINGLE_BUFFERS = WMT_FILESINK_MODE.SINGLE_BUFFERS; pub const WMT_FM_FILESINK_DATA_UNITS = WMT_FILESINK_MODE.FILESINK_DATA_UNITS; pub const WMT_FM_FILESINK_UNBUFFERED = WMT_FILESINK_MODE.FILESINK_UNBUFFERED; pub const WMT_MUSICSPEECH_CLASS_MODE = enum(i32) { MUSIC = 0, SPEECH = 1, MIXED = 2, }; pub const WMT_MS_CLASS_MUSIC = WMT_MUSICSPEECH_CLASS_MODE.MUSIC; pub const WMT_MS_CLASS_SPEECH = WMT_MUSICSPEECH_CLASS_MODE.SPEECH; pub const WMT_MS_CLASS_MIXED = WMT_MUSICSPEECH_CLASS_MODE.MIXED; pub const WMT_WATERMARK_ENTRY_TYPE = enum(i32) { AUDIO = 1, VIDEO = 2, }; pub const WMT_WMETYPE_AUDIO = WMT_WATERMARK_ENTRY_TYPE.AUDIO; pub const WMT_WMETYPE_VIDEO = WMT_WATERMARK_ENTRY_TYPE.VIDEO; pub const WM_PLAYBACK_DRC_LEVEL = enum(i32) { HIGH = 0, MEDIUM = 1, LOW = 2, }; pub const WM_PLAYBACK_DRC_HIGH = WM_PLAYBACK_DRC_LEVEL.HIGH; pub const WM_PLAYBACK_DRC_MEDIUM = WM_PLAYBACK_DRC_LEVEL.MEDIUM; pub const WM_PLAYBACK_DRC_LOW = WM_PLAYBACK_DRC_LEVEL.LOW; pub const WMT_TIMECODE_FRAMERATE = enum(i32) { @"30" = 0, @"30DROP" = 1, @"25" = 2, @"24" = 3, }; pub const WMT_TIMECODE_FRAMERATE_30 = WMT_TIMECODE_FRAMERATE.@"30"; pub const WMT_TIMECODE_FRAMERATE_30DROP = WMT_TIMECODE_FRAMERATE.@"30DROP"; pub const WMT_TIMECODE_FRAMERATE_25 = WMT_TIMECODE_FRAMERATE.@"25"; pub const WMT_TIMECODE_FRAMERATE_24 = WMT_TIMECODE_FRAMERATE.@"24"; pub const WMT_CREDENTIAL_FLAGS = enum(i32) { SAVE = 1, DONT_CACHE = 2, CLEAR_TEXT = 4, PROXY = 8, ENCRYPT = 16, }; pub const WMT_CREDENTIAL_SAVE = WMT_CREDENTIAL_FLAGS.SAVE; pub const WMT_CREDENTIAL_DONT_CACHE = WMT_CREDENTIAL_FLAGS.DONT_CACHE; pub const WMT_CREDENTIAL_CLEAR_TEXT = WMT_CREDENTIAL_FLAGS.CLEAR_TEXT; pub const WMT_CREDENTIAL_PROXY = WMT_CREDENTIAL_FLAGS.PROXY; pub const WMT_CREDENTIAL_ENCRYPT = WMT_CREDENTIAL_FLAGS.ENCRYPT; pub const WM_AETYPE = enum(i32) { INCLUDE = 105, EXCLUDE = 101, }; pub const WM_AETYPE_INCLUDE = WM_AETYPE.INCLUDE; pub const WM_AETYPE_EXCLUDE = WM_AETYPE.EXCLUDE; pub const WMT_RIGHTS = enum(i32) { PLAYBACK = 1, COPY_TO_NON_SDMI_DEVICE = 2, COPY_TO_CD = 8, COPY_TO_SDMI_DEVICE = 16, ONE_TIME = 32, SAVE_STREAM_PROTECTED = 64, COPY = 128, COLLABORATIVE_PLAY = 256, SDMI_TRIGGER = 65536, SDMI_NOMORECOPIES = 131072, }; pub const WMT_RIGHT_PLAYBACK = WMT_RIGHTS.PLAYBACK; pub const WMT_RIGHT_COPY_TO_NON_SDMI_DEVICE = WMT_RIGHTS.COPY_TO_NON_SDMI_DEVICE; pub const WMT_RIGHT_COPY_TO_CD = WMT_RIGHTS.COPY_TO_CD; pub const WMT_RIGHT_COPY_TO_SDMI_DEVICE = WMT_RIGHTS.COPY_TO_SDMI_DEVICE; pub const WMT_RIGHT_ONE_TIME = WMT_RIGHTS.ONE_TIME; pub const WMT_RIGHT_SAVE_STREAM_PROTECTED = WMT_RIGHTS.SAVE_STREAM_PROTECTED; pub const WMT_RIGHT_COPY = WMT_RIGHTS.COPY; pub const WMT_RIGHT_COLLABORATIVE_PLAY = WMT_RIGHTS.COLLABORATIVE_PLAY; pub const WMT_RIGHT_SDMI_TRIGGER = WMT_RIGHTS.SDMI_TRIGGER; pub const WMT_RIGHT_SDMI_NOMORECOPIES = WMT_RIGHTS.SDMI_NOMORECOPIES; pub const WM_STREAM_PRIORITY_RECORD = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug wStreamNumber: u16, fMandatory: BOOL, }; pub const WM_WRITER_STATISTICS = extern struct { qwSampleCount: u64, qwByteCount: u64, qwDroppedSampleCount: u64, qwDroppedByteCount: u64, dwCurrentBitrate: u32, dwAverageBitrate: u32, dwExpectedBitrate: u32, dwCurrentSampleRate: u32, dwAverageSampleRate: u32, dwExpectedSampleRate: u32, }; pub const WM_WRITER_STATISTICS_EX = extern struct { dwBitratePlusOverhead: u32, dwCurrentSampleDropRateInQueue: u32, dwCurrentSampleDropRateInCodec: u32, dwCurrentSampleDropRateInMultiplexer: u32, dwTotalSampleDropsInQueue: u32, dwTotalSampleDropsInCodec: u32, dwTotalSampleDropsInMultiplexer: u32, }; pub const WM_READER_STATISTICS = extern struct { cbSize: u32, dwBandwidth: u32, cPacketsReceived: u32, cPacketsRecovered: u32, cPacketsLost: u32, wQuality: u16, }; pub const WM_READER_CLIENTINFO = extern struct { cbSize: u32, wszLang: ?PWSTR, wszBrowserUserAgent: ?PWSTR, wszBrowserWebPage: ?PWSTR, qwReserved: u64, pReserved: ?*LPARAM, wszHostExe: ?PWSTR, qwHostVersion: u64, wszPlayerUserAgent: ?PWSTR, }; pub const WM_CLIENT_PROPERTIES = extern struct { dwIPAddress: u32, dwPort: u32, }; pub const WM_CLIENT_PROPERTIES_EX = extern struct { cbSize: u32, pwszIPAddress: ?[*:0]const u16, pwszPort: ?[*:0]const u16, pwszDNSName: ?[*:0]const u16, }; pub const WM_PORT_NUMBER_RANGE = extern struct { wPortBegin: u16, wPortEnd: u16, }; pub const WMT_BUFFER_SEGMENT = extern struct { pBuffer: ?*INSSBuffer, cbOffset: u32, cbLength: u32, }; pub const WMT_PAYLOAD_FRAGMENT = extern struct { dwPayloadIndex: u32, segmentData: WMT_BUFFER_SEGMENT, }; pub const WMT_FILESINK_DATA_UNIT = extern struct { packetHeaderBuffer: WMT_BUFFER_SEGMENT, cPayloads: u32, pPayloadHeaderBuffers: ?*WMT_BUFFER_SEGMENT, cPayloadDataFragments: u32, pPayloadDataFragments: ?*WMT_PAYLOAD_FRAGMENT, }; pub const WMT_WEBSTREAM_FORMAT = extern struct { cbSize: u16, cbSampleHeaderFixedData: u16, wVersion: u16, wReserved: u16, }; pub const WMT_WEBSTREAM_SAMPLE_HEADER = extern struct { cbLength: u16, wPart: u16, cTotalParts: u16, wSampleType: u16, wszURL: [1]u16, }; pub const WM_ADDRESS_ACCESSENTRY = extern struct { dwIPAddress: u32, dwMask: u32, }; pub const WM_PICTURE = packed struct { pwszMIMEType: ?PWSTR, bPictureType: u8, pwszDescription: ?PWSTR, dwDataLen: u32, pbData: ?*u8, }; pub const WM_SYNCHRONISED_LYRICS = packed struct { bTimeStampFormat: u8, bContentType: u8, pwszContentDescriptor: ?PWSTR, dwLyricsLen: u32, pbLyrics: ?*u8, }; pub const WM_USER_WEB_URL = packed struct { pwszDescription: ?PWSTR, pwszURL: ?PWSTR, }; pub const WM_USER_TEXT = packed struct { pwszDescription: ?PWSTR, pwszText: ?PWSTR, }; pub const WM_LEAKY_BUCKET_PAIR = packed struct { dwBitrate: u32, msBufferWindow: u32, }; pub const WM_STREAM_TYPE_INFO = packed struct { guidMajorType: Guid, cbFormat: u32, }; pub const WMT_WATERMARK_ENTRY = extern struct { wmetType: WMT_WATERMARK_ENTRY_TYPE, clsid: Guid, cbDisplayName: u32, pwszDisplayName: ?PWSTR, }; pub const WMT_VIDEOIMAGE_SAMPLE = extern struct { dwMagic: u32, cbStruct: u32, dwControlFlags: u32, dwInputFlagsCur: u32, lCurMotionXtoX: i32, lCurMotionYtoX: i32, lCurMotionXoffset: i32, lCurMotionXtoY: i32, lCurMotionYtoY: i32, lCurMotionYoffset: i32, lCurBlendCoef1: i32, lCurBlendCoef2: i32, dwInputFlagsPrev: u32, lPrevMotionXtoX: i32, lPrevMotionYtoX: i32, lPrevMotionXoffset: i32, lPrevMotionXtoY: i32, lPrevMotionYtoY: i32, lPrevMotionYoffset: i32, lPrevBlendCoef1: i32, lPrevBlendCoef2: i32, }; pub const WMT_VIDEOIMAGE_SAMPLE2 = extern struct { dwMagic: u32, dwStructSize: u32, dwControlFlags: u32, dwViewportWidth: u32, dwViewportHeight: u32, dwCurrImageWidth: u32, dwCurrImageHeight: u32, fCurrRegionX0: f32, fCurrRegionY0: f32, fCurrRegionWidth: f32, fCurrRegionHeight: f32, fCurrBlendCoef: f32, dwPrevImageWidth: u32, dwPrevImageHeight: u32, fPrevRegionX0: f32, fPrevRegionY0: f32, fPrevRegionWidth: f32, fPrevRegionHeight: f32, fPrevBlendCoef: f32, dwEffectType: u32, dwNumEffectParas: u32, fEffectPara0: f32, fEffectPara1: f32, fEffectPara2: f32, fEffectPara3: f32, fEffectPara4: f32, bKeepPrevImage: BOOL, }; pub const WM_MEDIA_TYPE = extern struct { majortype: Guid, subtype: Guid, bFixedSizeSamples: BOOL, bTemporalCompression: BOOL, lSampleSize: u32, formattype: Guid, pUnk: ?*IUnknown, cbFormat: u32, pbFormat: ?*u8, }; pub const WMVIDEOINFOHEADER = extern struct { rcSource: RECT, rcTarget: RECT, dwBitRate: u32, dwBitErrorRate: u32, AvgTimePerFrame: i64, bmiHeader: BITMAPINFOHEADER, }; pub const WMVIDEOINFOHEADER2 = extern struct { rcSource: RECT, rcTarget: RECT, dwBitRate: u32, dwBitErrorRate: u32, AvgTimePerFrame: i64, dwInterlaceFlags: u32, dwCopyProtectFlags: u32, dwPictAspectRatioX: u32, dwPictAspectRatioY: u32, dwReserved1: u32, dwReserved2: u32, bmiHeader: BITMAPINFOHEADER, }; pub const WMMPEG2VIDEOINFO = extern struct { hdr: WMVIDEOINFOHEADER2, dwStartTimeCode: u32, cbSequenceHeader: u32, dwProfile: u32, dwLevel: u32, dwFlags: u32, dwSequenceHeader: [1]u32, }; pub const WMSCRIPTFORMAT = extern struct { scriptType: Guid, }; pub const WMT_COLORSPACEINFO_EXTENSION_DATA = extern struct { ucColorPrimaries: u8, ucColorTransferChar: u8, ucColorMatrixCoef: u8, }; pub const WMT_TIMECODE_EXTENSION_DATA = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug wRange: u16, dwTimecode: u32, dwUserbits: u32, dwAmFlags: u32, }; pub const DRM_VAL16 = extern struct { val: [16]u8, }; const IID_IWMMediaProps_Value = Guid.initString("96406bce-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMMediaProps = &IID_IWMMediaProps_Value; pub const IWMMediaProps = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetType: fn( self: *const IWMMediaProps, pguidType: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMediaType: fn( self: *const IWMMediaProps, pType: ?*WM_MEDIA_TYPE, pcbType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMediaType: fn( self: *const IWMMediaProps, pType: ?*WM_MEDIA_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMediaProps_GetType(self: *const T, pguidType: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMediaProps.VTable, self.vtable).GetType(@ptrCast(*const IWMMediaProps, self), pguidType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMediaProps_GetMediaType(self: *const T, pType: ?*WM_MEDIA_TYPE, pcbType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMediaProps.VTable, self.vtable).GetMediaType(@ptrCast(*const IWMMediaProps, self), pType, pcbType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMediaProps_SetMediaType(self: *const T, pType: ?*WM_MEDIA_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMediaProps.VTable, self.vtable).SetMediaType(@ptrCast(*const IWMMediaProps, self), pType); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMVideoMediaProps_Value = Guid.initString("96406bcf-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMVideoMediaProps = &IID_IWMVideoMediaProps_Value; pub const IWMVideoMediaProps = extern struct { pub const VTable = extern struct { base: IWMMediaProps.VTable, GetMaxKeyFrameSpacing: fn( self: *const IWMVideoMediaProps, pllTime: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMaxKeyFrameSpacing: fn( self: *const IWMVideoMediaProps, llTime: i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQuality: fn( self: *const IWMVideoMediaProps, pdwQuality: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetQuality: fn( self: *const IWMVideoMediaProps, dwQuality: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMMediaProps.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMVideoMediaProps_GetMaxKeyFrameSpacing(self: *const T, pllTime: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMVideoMediaProps.VTable, self.vtable).GetMaxKeyFrameSpacing(@ptrCast(*const IWMVideoMediaProps, self), pllTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMVideoMediaProps_SetMaxKeyFrameSpacing(self: *const T, llTime: i64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMVideoMediaProps.VTable, self.vtable).SetMaxKeyFrameSpacing(@ptrCast(*const IWMVideoMediaProps, self), llTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMVideoMediaProps_GetQuality(self: *const T, pdwQuality: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMVideoMediaProps.VTable, self.vtable).GetQuality(@ptrCast(*const IWMVideoMediaProps, self), pdwQuality); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMVideoMediaProps_SetQuality(self: *const T, dwQuality: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMVideoMediaProps.VTable, self.vtable).SetQuality(@ptrCast(*const IWMVideoMediaProps, self), dwQuality); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriter_Value = Guid.initString("96406bd4-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMWriter = &IID_IWMWriter_Value; pub const IWMWriter = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetProfileByID: fn( self: *const IWMWriter, guidProfile: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProfile: fn( self: *const IWMWriter, pProfile: ?*IWMProfile, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputFilename: fn( self: *const IWMWriter, pwszFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputCount: fn( self: *const IWMWriter, pcInputs: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputProps: fn( self: *const IWMWriter, dwInputNum: u32, ppInput: ?*?*IWMInputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetInputProps: fn( self: *const IWMWriter, dwInputNum: u32, pInput: ?*IWMInputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputFormatCount: fn( self: *const IWMWriter, dwInputNumber: u32, pcFormats: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputFormat: fn( self: *const IWMWriter, dwInputNumber: u32, dwFormatNumber: u32, pProps: ?*?*IWMInputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginWriting: fn( self: *const IWMWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndWriting: fn( self: *const IWMWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateSample: fn( self: *const IWMWriter, dwSampleSize: u32, ppSample: ?*?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteSample: fn( self: *const IWMWriter, dwInputNum: u32, cnsSampleTime: u64, dwFlags: u32, pSample: ?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flush: fn( self: *const IWMWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_SetProfileByID(self: *const T, guidProfile: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).SetProfileByID(@ptrCast(*const IWMWriter, self), guidProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_SetProfile(self: *const T, pProfile: ?*IWMProfile) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).SetProfile(@ptrCast(*const IWMWriter, self), pProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_SetOutputFilename(self: *const T, pwszFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).SetOutputFilename(@ptrCast(*const IWMWriter, self), pwszFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_GetInputCount(self: *const T, pcInputs: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).GetInputCount(@ptrCast(*const IWMWriter, self), pcInputs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_GetInputProps(self: *const T, dwInputNum: u32, ppInput: ?*?*IWMInputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).GetInputProps(@ptrCast(*const IWMWriter, self), dwInputNum, ppInput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_SetInputProps(self: *const T, dwInputNum: u32, pInput: ?*IWMInputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).SetInputProps(@ptrCast(*const IWMWriter, self), dwInputNum, pInput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_GetInputFormatCount(self: *const T, dwInputNumber: u32, pcFormats: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).GetInputFormatCount(@ptrCast(*const IWMWriter, self), dwInputNumber, pcFormats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_GetInputFormat(self: *const T, dwInputNumber: u32, dwFormatNumber: u32, pProps: ?*?*IWMInputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).GetInputFormat(@ptrCast(*const IWMWriter, self), dwInputNumber, dwFormatNumber, pProps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_BeginWriting(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).BeginWriting(@ptrCast(*const IWMWriter, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_EndWriting(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).EndWriting(@ptrCast(*const IWMWriter, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_AllocateSample(self: *const T, dwSampleSize: u32, ppSample: ?*?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).AllocateSample(@ptrCast(*const IWMWriter, self), dwSampleSize, ppSample); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_WriteSample(self: *const T, dwInputNum: u32, cnsSampleTime: u64, dwFlags: u32, pSample: ?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).WriteSample(@ptrCast(*const IWMWriter, self), dwInputNum, cnsSampleTime, dwFlags, pSample); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriter_Flush(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriter.VTable, self.vtable).Flush(@ptrCast(*const IWMWriter, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMDRMWriter_Value = Guid.initString("d6ea5dd0-12a0-43f4-90ab-a3fd451e6a07"); pub const IID_IWMDRMWriter = &IID_IWMDRMWriter_Value; pub const IWMDRMWriter = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GenerateKeySeed: fn( self: *const IWMDRMWriter, pwszKeySeed: [*:0]u16, pcwchLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateKeyID: fn( self: *const IWMDRMWriter, pwszKeyID: [*:0]u16, pcwchLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateSigningKeyPair: fn( self: *const IWMDRMWriter, pwszPrivKey: [*:0]u16, pcwchPrivKeyLength: ?*u32, pwszPubKey: [*:0]u16, pcwchPubKeyLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDRMAttribute: fn( self: *const IWMDRMWriter, wStreamNum: u16, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter_GenerateKeySeed(self: *const T, pwszKeySeed: [*:0]u16, pcwchLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter.VTable, self.vtable).GenerateKeySeed(@ptrCast(*const IWMDRMWriter, self), pwszKeySeed, pcwchLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter_GenerateKeyID(self: *const T, pwszKeyID: [*:0]u16, pcwchLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter.VTable, self.vtable).GenerateKeyID(@ptrCast(*const IWMDRMWriter, self), pwszKeyID, pcwchLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter_GenerateSigningKeyPair(self: *const T, pwszPrivKey: [*:0]u16, pcwchPrivKeyLength: ?*u32, pwszPubKey: [*:0]u16, pcwchPubKeyLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter.VTable, self.vtable).GenerateSigningKeyPair(@ptrCast(*const IWMDRMWriter, self), pwszPrivKey, pcwchPrivKeyLength, pwszPubKey, pcwchPubKeyLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter_SetDRMAttribute(self: *const T, wStreamNum: u16, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter.VTable, self.vtable).SetDRMAttribute(@ptrCast(*const IWMDRMWriter, self), wStreamNum, pszName, Type, pValue, cbLength); } };} pub usingnamespace MethodMixin(@This()); }; pub const WMDRM_IMPORT_INIT_STRUCT = extern struct { dwVersion: u32, cbEncryptedSessionKeyMessage: u32, pbEncryptedSessionKeyMessage: ?*u8, cbEncryptedKeyMessage: u32, pbEncryptedKeyMessage: ?*u8, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMWriter2_Value = Guid.initString("38ee7a94-40e2-4e10-aa3f-33fd3210ed5b"); pub const IID_IWMDRMWriter2 = &IID_IWMDRMWriter2_Value; pub const IWMDRMWriter2 = extern struct { pub const VTable = extern struct { base: IWMDRMWriter.VTable, SetWMDRMNetEncryption: fn( self: *const IWMDRMWriter2, fSamplesEncrypted: BOOL, pbKeyID: ?*u8, cbKeyID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMDRMWriter.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter2_SetWMDRMNetEncryption(self: *const T, fSamplesEncrypted: BOOL, pbKeyID: ?*u8, cbKeyID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter2.VTable, self.vtable).SetWMDRMNetEncryption(@ptrCast(*const IWMDRMWriter2, self), fSamplesEncrypted, pbKeyID, cbKeyID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMWriter3_Value = Guid.initString("a7184082-a4aa-4dde-ac9c-e75dbd1117ce"); pub const IID_IWMDRMWriter3 = &IID_IWMDRMWriter3_Value; pub const IWMDRMWriter3 = extern struct { pub const VTable = extern struct { base: IWMDRMWriter2.VTable, SetProtectStreamSamples: fn( self: *const IWMDRMWriter3, pImportInitStruct: ?*WMDRM_IMPORT_INIT_STRUCT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMDRMWriter2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMWriter3_SetProtectStreamSamples(self: *const T, pImportInitStruct: ?*WMDRM_IMPORT_INIT_STRUCT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMWriter3.VTable, self.vtable).SetProtectStreamSamples(@ptrCast(*const IWMDRMWriter3, self), pImportInitStruct); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMInputMediaProps_Value = Guid.initString("96406bd5-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMInputMediaProps = &IID_IWMInputMediaProps_Value; pub const IWMInputMediaProps = extern struct { pub const VTable = extern struct { base: IWMMediaProps.VTable, GetConnectionName: fn( self: *const IWMInputMediaProps, pwszName: [*:0]u16, pcchName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGroupName: fn( self: *const IWMInputMediaProps, pwszName: [*:0]u16, pcchName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMMediaProps.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMInputMediaProps_GetConnectionName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMInputMediaProps.VTable, self.vtable).GetConnectionName(@ptrCast(*const IWMInputMediaProps, self), pwszName, pcchName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMInputMediaProps_GetGroupName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMInputMediaProps.VTable, self.vtable).GetGroupName(@ptrCast(*const IWMInputMediaProps, self), pwszName, pcchName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMPropertyVault_Value = Guid.initString("72995a79-5090-42a4-9c8c-d9d0b6d34be5"); pub const IID_IWMPropertyVault = &IID_IWMPropertyVault_Value; pub const IWMPropertyVault = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPropertyCount: fn( self: *const IWMPropertyVault, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyByName: fn( self: *const IWMPropertyVault, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IWMPropertyVault, pszName: ?[*:0]const u16, pType: WMT_ATTR_DATATYPE, pValue: ?*u8, dwSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyByIndex: fn( self: *const IWMPropertyVault, dwIndex: u32, pszName: [*:0]u16, pdwNameLen: ?*u32, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPropertiesFrom: fn( self: *const IWMPropertyVault, pIWMPropertyVault: ?*IWMPropertyVault, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IWMPropertyVault, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_GetPropertyCount(self: *const T, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).GetPropertyCount(@ptrCast(*const IWMPropertyVault, self), pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_GetPropertyByName(self: *const T, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).GetPropertyByName(@ptrCast(*const IWMPropertyVault, self), pszName, pType, pValue, pdwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_SetProperty(self: *const T, pszName: ?[*:0]const u16, pType: WMT_ATTR_DATATYPE, pValue: ?*u8, dwSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).SetProperty(@ptrCast(*const IWMPropertyVault, self), pszName, pType, pValue, dwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_GetPropertyByIndex(self: *const T, dwIndex: u32, pszName: [*:0]u16, pdwNameLen: ?*u32, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).GetPropertyByIndex(@ptrCast(*const IWMPropertyVault, self), dwIndex, pszName, pdwNameLen, pType, pValue, pdwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_CopyPropertiesFrom(self: *const T, pIWMPropertyVault: ?*IWMPropertyVault) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).CopyPropertiesFrom(@ptrCast(*const IWMPropertyVault, self), pIWMPropertyVault); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPropertyVault_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPropertyVault.VTable, self.vtable).Clear(@ptrCast(*const IWMPropertyVault, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMIStreamProps_Value = Guid.initString("6816dad3-2b4b-4c8e-8149-874c3483a753"); pub const IID_IWMIStreamProps = &IID_IWMIStreamProps_Value; pub const IWMIStreamProps = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetProperty: fn( self: *const IWMIStreamProps, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMIStreamProps_GetProperty(self: *const T, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMIStreamProps.VTable, self.vtable).GetProperty(@ptrCast(*const IWMIStreamProps, self), pszName, pType, pValue, pdwSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReader_Value = Guid.initString("96406bd6-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReader = &IID_IWMReader_Value; pub const IWMReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IWMReader, pwszURL: ?[*:0]const u16, pCallback: ?*IWMReaderCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputCount: fn( self: *const IWMReader, pcOutputs: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputProps: fn( self: *const IWMReader, dwOutputNum: u32, ppOutput: ?*?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputProps: fn( self: *const IWMReader, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputFormatCount: fn( self: *const IWMReader, dwOutputNumber: u32, pcFormats: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputFormat: fn( self: *const IWMReader, dwOutputNumber: u32, dwFormatNumber: u32, ppProps: ?*?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Start: fn( self: *const IWMReader, cnsStart: u64, cnsDuration: u64, fRate: f32, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IWMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pause: fn( self: *const IWMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Resume: fn( self: *const IWMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Open(self: *const T, pwszURL: ?[*:0]const u16, pCallback: ?*IWMReaderCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Open(@ptrCast(*const IWMReader, self), pwszURL, pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Close(@ptrCast(*const IWMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_GetOutputCount(self: *const T, pcOutputs: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).GetOutputCount(@ptrCast(*const IWMReader, self), pcOutputs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_GetOutputProps(self: *const T, dwOutputNum: u32, ppOutput: ?*?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).GetOutputProps(@ptrCast(*const IWMReader, self), dwOutputNum, ppOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_SetOutputProps(self: *const T, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).SetOutputProps(@ptrCast(*const IWMReader, self), dwOutputNum, pOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_GetOutputFormatCount(self: *const T, dwOutputNumber: u32, pcFormats: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).GetOutputFormatCount(@ptrCast(*const IWMReader, self), dwOutputNumber, pcFormats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_GetOutputFormat(self: *const T, dwOutputNumber: u32, dwFormatNumber: u32, ppProps: ?*?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).GetOutputFormat(@ptrCast(*const IWMReader, self), dwOutputNumber, dwFormatNumber, ppProps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Start(self: *const T, cnsStart: u64, cnsDuration: u64, fRate: f32, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Start(@ptrCast(*const IWMReader, self), cnsStart, cnsDuration, fRate, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Stop(@ptrCast(*const IWMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Pause(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Pause(@ptrCast(*const IWMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReader_Resume(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReader.VTable, self.vtable).Resume(@ptrCast(*const IWMReader, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMSyncReader_Value = Guid.initString("9397f121-7705-4dc9-b049-98b698188414"); pub const IID_IWMSyncReader = &IID_IWMSyncReader_Value; pub const IWMSyncReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IWMSyncReader, pwszFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMSyncReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRange: fn( self: *const IWMSyncReader, cnsStartTime: u64, cnsDuration: i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRangeByFrame: fn( self: *const IWMSyncReader, wStreamNum: u16, qwFrameNumber: u64, cFramesToRead: i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextSample: fn( self: *const IWMSyncReader, wStreamNum: u16, ppSample: ?*?*INSSBuffer, pcnsSampleTime: ?*u64, pcnsDuration: ?*u64, pdwFlags: ?*u32, pdwOutputNum: ?*u32, pwStreamNum: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamsSelected: fn( self: *const IWMSyncReader, cStreamCount: u16, pwStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamSelected: fn( self: *const IWMSyncReader, wStreamNum: u16, pSelection: ?*WMT_STREAM_SELECTION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadStreamSamples: fn( self: *const IWMSyncReader, wStreamNum: u16, fCompressed: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReadStreamSamples: fn( self: *const IWMSyncReader, wStreamNum: u16, pfCompressed: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputSetting: fn( self: *const IWMSyncReader, dwOutputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputSetting: fn( self: *const IWMSyncReader, dwOutputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputCount: fn( self: *const IWMSyncReader, pcOutputs: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputProps: fn( self: *const IWMSyncReader, dwOutputNum: u32, ppOutput: ?*?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputProps: fn( self: *const IWMSyncReader, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputFormatCount: fn( self: *const IWMSyncReader, dwOutputNum: u32, pcFormats: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputFormat: fn( self: *const IWMSyncReader, dwOutputNum: u32, dwFormatNum: u32, ppProps: ?*?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputNumberForStream: fn( self: *const IWMSyncReader, wStreamNum: u16, pdwOutputNum: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamNumberForOutput: fn( self: *const IWMSyncReader, dwOutputNum: u32, pwStreamNum: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxOutputSampleSize: fn( self: *const IWMSyncReader, dwOutput: u32, pcbMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxStreamSampleSize: fn( self: *const IWMSyncReader, wStream: u16, pcbMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenStream: fn( self: *const IWMSyncReader, pStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_Open(self: *const T, pwszFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).Open(@ptrCast(*const IWMSyncReader, self), pwszFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).Close(@ptrCast(*const IWMSyncReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetRange(self: *const T, cnsStartTime: u64, cnsDuration: i64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetRange(@ptrCast(*const IWMSyncReader, self), cnsStartTime, cnsDuration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetRangeByFrame(self: *const T, wStreamNum: u16, qwFrameNumber: u64, cFramesToRead: i64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetRangeByFrame(@ptrCast(*const IWMSyncReader, self), wStreamNum, qwFrameNumber, cFramesToRead); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetNextSample(self: *const T, wStreamNum: u16, ppSample: ?*?*INSSBuffer, pcnsSampleTime: ?*u64, pcnsDuration: ?*u64, pdwFlags: ?*u32, pdwOutputNum: ?*u32, pwStreamNum: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetNextSample(@ptrCast(*const IWMSyncReader, self), wStreamNum, ppSample, pcnsSampleTime, pcnsDuration, pdwFlags, pdwOutputNum, pwStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetStreamsSelected(self: *const T, cStreamCount: u16, pwStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetStreamsSelected(@ptrCast(*const IWMSyncReader, self), cStreamCount, pwStreamNumbers, pSelections); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetStreamSelected(self: *const T, wStreamNum: u16, pSelection: ?*WMT_STREAM_SELECTION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetStreamSelected(@ptrCast(*const IWMSyncReader, self), wStreamNum, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetReadStreamSamples(self: *const T, wStreamNum: u16, fCompressed: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetReadStreamSamples(@ptrCast(*const IWMSyncReader, self), wStreamNum, fCompressed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetReadStreamSamples(self: *const T, wStreamNum: u16, pfCompressed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetReadStreamSamples(@ptrCast(*const IWMSyncReader, self), wStreamNum, pfCompressed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputSetting(self: *const T, dwOutputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputSetting(@ptrCast(*const IWMSyncReader, self), dwOutputNum, pszName, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetOutputSetting(self: *const T, dwOutputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetOutputSetting(@ptrCast(*const IWMSyncReader, self), dwOutputNum, pszName, Type, pValue, cbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputCount(self: *const T, pcOutputs: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputCount(@ptrCast(*const IWMSyncReader, self), pcOutputs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputProps(self: *const T, dwOutputNum: u32, ppOutput: ?*?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputProps(@ptrCast(*const IWMSyncReader, self), dwOutputNum, ppOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_SetOutputProps(self: *const T, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).SetOutputProps(@ptrCast(*const IWMSyncReader, self), dwOutputNum, pOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputFormatCount(self: *const T, dwOutputNum: u32, pcFormats: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputFormatCount(@ptrCast(*const IWMSyncReader, self), dwOutputNum, pcFormats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputFormat(self: *const T, dwOutputNum: u32, dwFormatNum: u32, ppProps: ?*?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputFormat(@ptrCast(*const IWMSyncReader, self), dwOutputNum, dwFormatNum, ppProps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetOutputNumberForStream(self: *const T, wStreamNum: u16, pdwOutputNum: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetOutputNumberForStream(@ptrCast(*const IWMSyncReader, self), wStreamNum, pdwOutputNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetStreamNumberForOutput(self: *const T, dwOutputNum: u32, pwStreamNum: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetStreamNumberForOutput(@ptrCast(*const IWMSyncReader, self), dwOutputNum, pwStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetMaxOutputSampleSize(self: *const T, dwOutput: u32, pcbMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetMaxOutputSampleSize(@ptrCast(*const IWMSyncReader, self), dwOutput, pcbMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_GetMaxStreamSampleSize(self: *const T, wStream: u16, pcbMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).GetMaxStreamSampleSize(@ptrCast(*const IWMSyncReader, self), wStream, pcbMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader_OpenStream(self: *const T, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader.VTable, self.vtable).OpenStream(@ptrCast(*const IWMSyncReader, self), pStream); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMSyncReader2_Value = Guid.initString("faed3d21-1b6b-4af7-8cb6-3e189bbc187b"); pub const IID_IWMSyncReader2 = &IID_IWMSyncReader2_Value; pub const IWMSyncReader2 = extern struct { pub const VTable = extern struct { base: IWMSyncReader.VTable, SetRangeByTimecode: fn( self: *const IWMSyncReader2, wStreamNum: u16, pStart: ?*WMT_TIMECODE_EXTENSION_DATA, pEnd: ?*WMT_TIMECODE_EXTENSION_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRangeByFrameEx: fn( self: *const IWMSyncReader2, wStreamNum: u16, qwFrameNumber: u64, cFramesToRead: i64, pcnsStartTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllocateForOutput: fn( self: *const IWMSyncReader2, dwOutputNum: u32, pAllocator: ?*IWMReaderAllocatorEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllocateForOutput: fn( self: *const IWMSyncReader2, dwOutputNum: u32, ppAllocator: ?*?*IWMReaderAllocatorEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllocateForStream: fn( self: *const IWMSyncReader2, wStreamNum: u16, pAllocator: ?*IWMReaderAllocatorEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllocateForStream: fn( self: *const IWMSyncReader2, dwSreamNum: u16, ppAllocator: ?*?*IWMReaderAllocatorEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMSyncReader.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_SetRangeByTimecode(self: *const T, wStreamNum: u16, pStart: ?*WMT_TIMECODE_EXTENSION_DATA, pEnd: ?*WMT_TIMECODE_EXTENSION_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).SetRangeByTimecode(@ptrCast(*const IWMSyncReader2, self), wStreamNum, pStart, pEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_SetRangeByFrameEx(self: *const T, wStreamNum: u16, qwFrameNumber: u64, cFramesToRead: i64, pcnsStartTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).SetRangeByFrameEx(@ptrCast(*const IWMSyncReader2, self), wStreamNum, qwFrameNumber, cFramesToRead, pcnsStartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_SetAllocateForOutput(self: *const T, dwOutputNum: u32, pAllocator: ?*IWMReaderAllocatorEx) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).SetAllocateForOutput(@ptrCast(*const IWMSyncReader2, self), dwOutputNum, pAllocator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_GetAllocateForOutput(self: *const T, dwOutputNum: u32, ppAllocator: ?*?*IWMReaderAllocatorEx) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).GetAllocateForOutput(@ptrCast(*const IWMSyncReader2, self), dwOutputNum, ppAllocator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_SetAllocateForStream(self: *const T, wStreamNum: u16, pAllocator: ?*IWMReaderAllocatorEx) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).SetAllocateForStream(@ptrCast(*const IWMSyncReader2, self), wStreamNum, pAllocator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSyncReader2_GetAllocateForStream(self: *const T, dwSreamNum: u16, ppAllocator: ?*?*IWMReaderAllocatorEx) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSyncReader2.VTable, self.vtable).GetAllocateForStream(@ptrCast(*const IWMSyncReader2, self), dwSreamNum, ppAllocator); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMOutputMediaProps_Value = Guid.initString("96406bd7-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMOutputMediaProps = &IID_IWMOutputMediaProps_Value; pub const IWMOutputMediaProps = extern struct { pub const VTable = extern struct { base: IWMMediaProps.VTable, GetStreamGroupName: fn( self: *const IWMOutputMediaProps, pwszName: [*:0]u16, pcchName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectionName: fn( self: *const IWMOutputMediaProps, pwszName: [*:0]u16, pcchName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMMediaProps.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMOutputMediaProps_GetStreamGroupName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMOutputMediaProps.VTable, self.vtable).GetStreamGroupName(@ptrCast(*const IWMOutputMediaProps, self), pwszName, pcchName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMOutputMediaProps_GetConnectionName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMOutputMediaProps.VTable, self.vtable).GetConnectionName(@ptrCast(*const IWMOutputMediaProps, self), pwszName, pcchName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStatusCallback_Value = Guid.initString("6d7cdc70-9888-11d3-8edc-00c04f6109cf"); pub const IID_IWMStatusCallback = &IID_IWMStatusCallback_Value; pub const IWMStatusCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStatus: fn( self: *const IWMStatusCallback, Status: WMT_STATUS, hr: HRESULT, dwType: WMT_ATTR_DATATYPE, pValue: ?*u8, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStatusCallback_OnStatus(self: *const T, Status: WMT_STATUS, hr: HRESULT, dwType: WMT_ATTR_DATATYPE, pValue: ?*u8, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStatusCallback.VTable, self.vtable).OnStatus(@ptrCast(*const IWMStatusCallback, self), Status, hr, dwType, pValue, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderCallback_Value = Guid.initString("96406bd8-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReaderCallback = &IID_IWMReaderCallback_Value; pub const IWMReaderCallback = extern struct { pub const VTable = extern struct { base: IWMStatusCallback.VTable, OnSample: fn( self: *const IWMReaderCallback, dwOutputNum: u32, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStatusCallback.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallback_OnSample(self: *const T, dwOutputNum: u32, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallback.VTable, self.vtable).OnSample(@ptrCast(*const IWMReaderCallback, self), dwOutputNum, cnsSampleTime, cnsSampleDuration, dwFlags, pSample, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCredentialCallback_Value = Guid.initString("342e0eb7-e651-450c-975b-2ace2c90c48e"); pub const IID_IWMCredentialCallback = &IID_IWMCredentialCallback_Value; pub const IWMCredentialCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AcquireCredentials: fn( self: *const IWMCredentialCallback, pwszRealm: ?PWSTR, pwszSite: ?PWSTR, pwszUser: [*:0]u16, cchUser: u32, pwszPassword: [*:0]u16, cchPassword: u32, hrStatus: HRESULT, pdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCredentialCallback_AcquireCredentials(self: *const T, pwszRealm: ?PWSTR, pwszSite: ?PWSTR, pwszUser: [*:0]u16, cchUser: u32, pwszPassword: [*:0]u16, cchPassword: u32, hrStatus: HRESULT, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCredentialCallback.VTable, self.vtable).AcquireCredentials(@ptrCast(*const IWMCredentialCallback, self), pwszRealm, pwszSite, pwszUser, cchUser, pwszPassword, cchPassword, hrStatus, pdwFlags); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMMetadataEditor_Value = Guid.initString("96406bd9-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMMetadataEditor = &IID_IWMMetadataEditor_Value; pub const IWMMetadataEditor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IWMMetadataEditor, pwszFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMMetadataEditor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flush: fn( self: *const IWMMetadataEditor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMetadataEditor_Open(self: *const T, pwszFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMetadataEditor.VTable, self.vtable).Open(@ptrCast(*const IWMMetadataEditor, self), pwszFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMetadataEditor_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMetadataEditor.VTable, self.vtable).Close(@ptrCast(*const IWMMetadataEditor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMetadataEditor_Flush(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMetadataEditor.VTable, self.vtable).Flush(@ptrCast(*const IWMMetadataEditor, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMMetadataEditor2_Value = Guid.initString("203cffe3-2e18-4fdf-b59d-6e71530534cf"); pub const IID_IWMMetadataEditor2 = &IID_IWMMetadataEditor2_Value; pub const IWMMetadataEditor2 = extern struct { pub const VTable = extern struct { base: IWMMetadataEditor.VTable, OpenEx: fn( self: *const IWMMetadataEditor2, pwszFilename: ?[*:0]const u16, dwDesiredAccess: u32, dwShareMode: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMMetadataEditor.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMetadataEditor2_OpenEx(self: *const T, pwszFilename: ?[*:0]const u16, dwDesiredAccess: u32, dwShareMode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMetadataEditor2.VTable, self.vtable).OpenEx(@ptrCast(*const IWMMetadataEditor2, self), pwszFilename, dwDesiredAccess, dwShareMode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMDRMEditor_Value = Guid.initString("ff130ebc-a6c3-42a6-b401-c3382c3e08b3"); pub const IID_IWMDRMEditor = &IID_IWMDRMEditor_Value; pub const IWMDRMEditor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDRMProperty: fn( self: *const IWMDRMEditor, pwstrName: ?[*:0]const u16, pdwType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMEditor_GetDRMProperty(self: *const T, pwstrName: ?[*:0]const u16, pdwType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMEditor.VTable, self.vtable).GetDRMProperty(@ptrCast(*const IWMDRMEditor, self), pwstrName, pdwType, pValue, pcbLength); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMHeaderInfo_Value = Guid.initString("96406bda-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMHeaderInfo = &IID_IWMHeaderInfo_Value; pub const IWMHeaderInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAttributeCount: fn( self: *const IWMHeaderInfo, wStreamNum: u16, pcAttributes: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeByIndex: fn( self: *const IWMHeaderInfo, wIndex: u16, pwStreamNum: ?*u16, pwszName: [*:0]u16, pcchNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeByName: fn( self: *const IWMHeaderInfo, pwStreamNum: ?*u16, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAttribute: fn( self: *const IWMHeaderInfo, wStreamNum: u16, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMarkerCount: fn( self: *const IWMHeaderInfo, pcMarkers: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMarker: fn( self: *const IWMHeaderInfo, wIndex: u16, pwszMarkerName: [*:0]u16, pcchMarkerNameLen: ?*u16, pcnsMarkerTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMarker: fn( self: *const IWMHeaderInfo, pwszMarkerName: ?PWSTR, cnsMarkerTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveMarker: fn( self: *const IWMHeaderInfo, wIndex: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScriptCount: fn( self: *const IWMHeaderInfo, pcScripts: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScript: fn( self: *const IWMHeaderInfo, wIndex: u16, pwszType: [*:0]u16, pcchTypeLen: ?*u16, pwszCommand: [*:0]u16, pcchCommandLen: ?*u16, pcnsScriptTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddScript: fn( self: *const IWMHeaderInfo, pwszType: ?PWSTR, pwszCommand: ?PWSTR, cnsScriptTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveScript: fn( self: *const IWMHeaderInfo, wIndex: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetAttributeCount(self: *const T, wStreamNum: u16, pcAttributes: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetAttributeCount(@ptrCast(*const IWMHeaderInfo, self), wStreamNum, pcAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetAttributeByIndex(self: *const T, wIndex: u16, pwStreamNum: ?*u16, pwszName: [*:0]u16, pcchNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetAttributeByIndex(@ptrCast(*const IWMHeaderInfo, self), wIndex, pwStreamNum, pwszName, pcchNameLen, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetAttributeByName(self: *const T, pwStreamNum: ?*u16, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetAttributeByName(@ptrCast(*const IWMHeaderInfo, self), pwStreamNum, pszName, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_SetAttribute(self: *const T, wStreamNum: u16, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).SetAttribute(@ptrCast(*const IWMHeaderInfo, self), wStreamNum, pszName, Type, pValue, cbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetMarkerCount(self: *const T, pcMarkers: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetMarkerCount(@ptrCast(*const IWMHeaderInfo, self), pcMarkers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetMarker(self: *const T, wIndex: u16, pwszMarkerName: [*:0]u16, pcchMarkerNameLen: ?*u16, pcnsMarkerTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetMarker(@ptrCast(*const IWMHeaderInfo, self), wIndex, pwszMarkerName, pcchMarkerNameLen, pcnsMarkerTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_AddMarker(self: *const T, pwszMarkerName: ?PWSTR, cnsMarkerTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).AddMarker(@ptrCast(*const IWMHeaderInfo, self), pwszMarkerName, cnsMarkerTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_RemoveMarker(self: *const T, wIndex: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).RemoveMarker(@ptrCast(*const IWMHeaderInfo, self), wIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetScriptCount(self: *const T, pcScripts: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetScriptCount(@ptrCast(*const IWMHeaderInfo, self), pcScripts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_GetScript(self: *const T, wIndex: u16, pwszType: [*:0]u16, pcchTypeLen: ?*u16, pwszCommand: [*:0]u16, pcchCommandLen: ?*u16, pcnsScriptTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).GetScript(@ptrCast(*const IWMHeaderInfo, self), wIndex, pwszType, pcchTypeLen, pwszCommand, pcchCommandLen, pcnsScriptTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_AddScript(self: *const T, pwszType: ?PWSTR, pwszCommand: ?PWSTR, cnsScriptTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).AddScript(@ptrCast(*const IWMHeaderInfo, self), pwszType, pwszCommand, cnsScriptTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo_RemoveScript(self: *const T, wIndex: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo.VTable, self.vtable).RemoveScript(@ptrCast(*const IWMHeaderInfo, self), wIndex); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMHeaderInfo2_Value = Guid.initString("15cf9781-454e-482e-b393-85fae487a810"); pub const IID_IWMHeaderInfo2 = &IID_IWMHeaderInfo2_Value; pub const IWMHeaderInfo2 = extern struct { pub const VTable = extern struct { base: IWMHeaderInfo.VTable, GetCodecInfoCount: fn( self: *const IWMHeaderInfo2, pcCodecInfos: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecInfo: fn( self: *const IWMHeaderInfo2, wIndex: u32, pcchName: ?*u16, pwszName: [*:0]u16, pcchDescription: ?*u16, pwszDescription: [*:0]u16, pCodecType: ?*WMT_CODEC_INFO_TYPE, pcbCodecInfo: ?*u16, pbCodecInfo: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMHeaderInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo2_GetCodecInfoCount(self: *const T, pcCodecInfos: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo2.VTable, self.vtable).GetCodecInfoCount(@ptrCast(*const IWMHeaderInfo2, self), pcCodecInfos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo2_GetCodecInfo(self: *const T, wIndex: u32, pcchName: ?*u16, pwszName: [*:0]u16, pcchDescription: ?*u16, pwszDescription: [*:0]u16, pCodecType: ?*WMT_CODEC_INFO_TYPE, pcbCodecInfo: ?*u16, pbCodecInfo: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo2.VTable, self.vtable).GetCodecInfo(@ptrCast(*const IWMHeaderInfo2, self), wIndex, pcchName, pwszName, pcchDescription, pwszDescription, pCodecType, pcbCodecInfo, pbCodecInfo); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMHeaderInfo3_Value = Guid.initString("15cc68e3-27cc-4ecd-b222-3f5d02d80bd5"); pub const IID_IWMHeaderInfo3 = &IID_IWMHeaderInfo3_Value; pub const IWMHeaderInfo3 = extern struct { pub const VTable = extern struct { base: IWMHeaderInfo2.VTable, GetAttributeCountEx: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, pcAttributes: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeIndices: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, pwszName: ?[*:0]const u16, pwLangIndex: ?*u16, pwIndices: [*:0]u16, pwCount: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeByIndexEx: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, wIndex: u16, pwszName: [*:0]u16, pwNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pwLangIndex: ?*u16, pValue: [*:0]u8, pdwDataLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyAttribute: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, wIndex: u16, Type: WMT_ATTR_DATATYPE, wLangIndex: u16, pValue: [*:0]const u8, dwLength: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAttribute: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, pszName: ?[*:0]const u16, pwIndex: ?*u16, Type: WMT_ATTR_DATATYPE, wLangIndex: u16, pValue: [*:0]const u8, dwLength: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttribute: fn( self: *const IWMHeaderInfo3, wStreamNum: u16, wIndex: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddCodecInfo: fn( self: *const IWMHeaderInfo3, pwszName: ?PWSTR, pwszDescription: ?PWSTR, codecType: WMT_CODEC_INFO_TYPE, cbCodecInfo: u16, pbCodecInfo: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMHeaderInfo2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_GetAttributeCountEx(self: *const T, wStreamNum: u16, pcAttributes: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).GetAttributeCountEx(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, pcAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_GetAttributeIndices(self: *const T, wStreamNum: u16, pwszName: ?[*:0]const u16, pwLangIndex: ?*u16, pwIndices: [*:0]u16, pwCount: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).GetAttributeIndices(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, pwszName, pwLangIndex, pwIndices, pwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_GetAttributeByIndexEx(self: *const T, wStreamNum: u16, wIndex: u16, pwszName: [*:0]u16, pwNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pwLangIndex: ?*u16, pValue: [*:0]u8, pdwDataLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).GetAttributeByIndexEx(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, wIndex, pwszName, pwNameLen, pType, pwLangIndex, pValue, pdwDataLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_ModifyAttribute(self: *const T, wStreamNum: u16, wIndex: u16, Type: WMT_ATTR_DATATYPE, wLangIndex: u16, pValue: [*:0]const u8, dwLength: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).ModifyAttribute(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, wIndex, Type, wLangIndex, pValue, dwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_AddAttribute(self: *const T, wStreamNum: u16, pszName: ?[*:0]const u16, pwIndex: ?*u16, Type: WMT_ATTR_DATATYPE, wLangIndex: u16, pValue: [*:0]const u8, dwLength: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).AddAttribute(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, pszName, pwIndex, Type, wLangIndex, pValue, dwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_DeleteAttribute(self: *const T, wStreamNum: u16, wIndex: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).DeleteAttribute(@ptrCast(*const IWMHeaderInfo3, self), wStreamNum, wIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMHeaderInfo3_AddCodecInfo(self: *const T, pwszName: ?PWSTR, pwszDescription: ?PWSTR, codecType: WMT_CODEC_INFO_TYPE, cbCodecInfo: u16, pbCodecInfo: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMHeaderInfo3.VTable, self.vtable).AddCodecInfo(@ptrCast(*const IWMHeaderInfo3, self), pwszName, pwszDescription, codecType, cbCodecInfo, pbCodecInfo); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfileManager_Value = Guid.initString("d16679f2-6ca0-472d-8d31-2f5d55aee155"); pub const IID_IWMProfileManager = &IID_IWMProfileManager_Value; pub const IWMProfileManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateEmptyProfile: fn( self: *const IWMProfileManager, dwVersion: WMT_VERSION, ppProfile: ?*?*IWMProfile, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadProfileByID: fn( self: *const IWMProfileManager, guidProfile: ?*const Guid, ppProfile: ?*?*IWMProfile, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadProfileByData: fn( self: *const IWMProfileManager, pwszProfile: ?[*:0]const u16, ppProfile: ?*?*IWMProfile, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveProfile: fn( self: *const IWMProfileManager, pIWMProfile: ?*IWMProfile, pwszProfile: ?PWSTR, pdwLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSystemProfileCount: fn( self: *const IWMProfileManager, pcProfiles: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadSystemProfile: fn( self: *const IWMProfileManager, dwProfileIndex: u32, ppProfile: ?*?*IWMProfile, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_CreateEmptyProfile(self: *const T, dwVersion: WMT_VERSION, ppProfile: ?*?*IWMProfile) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).CreateEmptyProfile(@ptrCast(*const IWMProfileManager, self), dwVersion, ppProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_LoadProfileByID(self: *const T, guidProfile: ?*const Guid, ppProfile: ?*?*IWMProfile) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).LoadProfileByID(@ptrCast(*const IWMProfileManager, self), guidProfile, ppProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_LoadProfileByData(self: *const T, pwszProfile: ?[*:0]const u16, ppProfile: ?*?*IWMProfile) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).LoadProfileByData(@ptrCast(*const IWMProfileManager, self), pwszProfile, ppProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_SaveProfile(self: *const T, pIWMProfile: ?*IWMProfile, pwszProfile: ?PWSTR, pdwLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).SaveProfile(@ptrCast(*const IWMProfileManager, self), pIWMProfile, pwszProfile, pdwLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_GetSystemProfileCount(self: *const T, pcProfiles: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).GetSystemProfileCount(@ptrCast(*const IWMProfileManager, self), pcProfiles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager_LoadSystemProfile(self: *const T, dwProfileIndex: u32, ppProfile: ?*?*IWMProfile) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager.VTable, self.vtable).LoadSystemProfile(@ptrCast(*const IWMProfileManager, self), dwProfileIndex, ppProfile); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfileManager2_Value = Guid.initString("7a924e51-73c1-494d-8019-23d37ed9b89a"); pub const IID_IWMProfileManager2 = &IID_IWMProfileManager2_Value; pub const IWMProfileManager2 = extern struct { pub const VTable = extern struct { base: IWMProfileManager.VTable, GetSystemProfileVersion: fn( self: *const IWMProfileManager2, pdwVersion: ?*WMT_VERSION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSystemProfileVersion: fn( self: *const IWMProfileManager2, dwVersion: WMT_VERSION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMProfileManager.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager2_GetSystemProfileVersion(self: *const T, pdwVersion: ?*WMT_VERSION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager2.VTable, self.vtable).GetSystemProfileVersion(@ptrCast(*const IWMProfileManager2, self), pdwVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManager2_SetSystemProfileVersion(self: *const T, dwVersion: WMT_VERSION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManager2.VTable, self.vtable).SetSystemProfileVersion(@ptrCast(*const IWMProfileManager2, self), dwVersion); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfileManagerLanguage_Value = Guid.initString("ba4dcc78-7ee0-4ab8-b27a-dbce8bc51454"); pub const IID_IWMProfileManagerLanguage = &IID_IWMProfileManagerLanguage_Value; pub const IWMProfileManagerLanguage = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetUserLanguageID: fn( self: *const IWMProfileManagerLanguage, wLangID: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUserLanguageID: fn( self: *const IWMProfileManagerLanguage, wLangID: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManagerLanguage_GetUserLanguageID(self: *const T, wLangID: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManagerLanguage.VTable, self.vtable).GetUserLanguageID(@ptrCast(*const IWMProfileManagerLanguage, self), wLangID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfileManagerLanguage_SetUserLanguageID(self: *const T, wLangID: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfileManagerLanguage.VTable, self.vtable).SetUserLanguageID(@ptrCast(*const IWMProfileManagerLanguage, self), wLangID); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfile_Value = Guid.initString("96406bdb-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMProfile = &IID_IWMProfile_Value; pub const IWMProfile = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetVersion: fn( self: *const IWMProfile, pdwVersion: ?*WMT_VERSION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetName: fn( self: *const IWMProfile, pwszName: [*:0]u16, pcchName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const IWMProfile, pwszName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const IWMProfile, pwszDescription: [*:0]u16, pcchDescription: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDescription: fn( self: *const IWMProfile, pwszDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamCount: fn( self: *const IWMProfile, pcStreams: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStream: fn( self: *const IWMProfile, dwStreamIndex: u32, ppConfig: ?*?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamByNumber: fn( self: *const IWMProfile, wStreamNum: u16, ppConfig: ?*?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveStream: fn( self: *const IWMProfile, pConfig: ?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveStreamByNumber: fn( self: *const IWMProfile, wStreamNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddStream: fn( self: *const IWMProfile, pConfig: ?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReconfigStream: fn( self: *const IWMProfile, pConfig: ?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewStream: fn( self: *const IWMProfile, guidStreamType: ?*const Guid, ppConfig: ?*?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMutualExclusionCount: fn( self: *const IWMProfile, pcME: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMutualExclusion: fn( self: *const IWMProfile, dwMEIndex: u32, ppME: ?*?*IWMMutualExclusion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveMutualExclusion: fn( self: *const IWMProfile, pME: ?*IWMMutualExclusion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddMutualExclusion: fn( self: *const IWMProfile, pME: ?*IWMMutualExclusion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewMutualExclusion: fn( self: *const IWMProfile, ppME: ?*?*IWMMutualExclusion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetVersion(self: *const T, pdwVersion: ?*WMT_VERSION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetVersion(@ptrCast(*const IWMProfile, self), pdwVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetName(@ptrCast(*const IWMProfile, self), pwszName, pcchName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_SetName(self: *const T, pwszName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).SetName(@ptrCast(*const IWMProfile, self), pwszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetDescription(self: *const T, pwszDescription: [*:0]u16, pcchDescription: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetDescription(@ptrCast(*const IWMProfile, self), pwszDescription, pcchDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_SetDescription(self: *const T, pwszDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).SetDescription(@ptrCast(*const IWMProfile, self), pwszDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetStreamCount(self: *const T, pcStreams: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetStreamCount(@ptrCast(*const IWMProfile, self), pcStreams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetStream(self: *const T, dwStreamIndex: u32, ppConfig: ?*?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetStream(@ptrCast(*const IWMProfile, self), dwStreamIndex, ppConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetStreamByNumber(self: *const T, wStreamNum: u16, ppConfig: ?*?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetStreamByNumber(@ptrCast(*const IWMProfile, self), wStreamNum, ppConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_RemoveStream(self: *const T, pConfig: ?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).RemoveStream(@ptrCast(*const IWMProfile, self), pConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_RemoveStreamByNumber(self: *const T, wStreamNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).RemoveStreamByNumber(@ptrCast(*const IWMProfile, self), wStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_AddStream(self: *const T, pConfig: ?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).AddStream(@ptrCast(*const IWMProfile, self), pConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_ReconfigStream(self: *const T, pConfig: ?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).ReconfigStream(@ptrCast(*const IWMProfile, self), pConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_CreateNewStream(self: *const T, guidStreamType: ?*const Guid, ppConfig: ?*?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).CreateNewStream(@ptrCast(*const IWMProfile, self), guidStreamType, ppConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetMutualExclusionCount(self: *const T, pcME: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetMutualExclusionCount(@ptrCast(*const IWMProfile, self), pcME); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_GetMutualExclusion(self: *const T, dwMEIndex: u32, ppME: ?*?*IWMMutualExclusion) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).GetMutualExclusion(@ptrCast(*const IWMProfile, self), dwMEIndex, ppME); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_RemoveMutualExclusion(self: *const T, pME: ?*IWMMutualExclusion) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).RemoveMutualExclusion(@ptrCast(*const IWMProfile, self), pME); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_AddMutualExclusion(self: *const T, pME: ?*IWMMutualExclusion) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).AddMutualExclusion(@ptrCast(*const IWMProfile, self), pME); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile_CreateNewMutualExclusion(self: *const T, ppME: ?*?*IWMMutualExclusion) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile.VTable, self.vtable).CreateNewMutualExclusion(@ptrCast(*const IWMProfile, self), ppME); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfile2_Value = Guid.initString("07e72d33-d94e-4be7-8843-60ae5ff7e5f5"); pub const IID_IWMProfile2 = &IID_IWMProfile2_Value; pub const IWMProfile2 = extern struct { pub const VTable = extern struct { base: IWMProfile.VTable, GetProfileID: fn( self: *const IWMProfile2, pguidID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMProfile.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile2_GetProfileID(self: *const T, pguidID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile2.VTable, self.vtable).GetProfileID(@ptrCast(*const IWMProfile2, self), pguidID); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMProfile3_Value = Guid.initString("00ef96cc-a461-4546-8bcd-c9a28f0e06f5"); pub const IID_IWMProfile3 = &IID_IWMProfile3_Value; pub const IWMProfile3 = extern struct { pub const VTable = extern struct { base: IWMProfile2.VTable, GetStorageFormat: fn( self: *const IWMProfile3, pnStorageFormat: ?*WMT_STORAGE_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStorageFormat: fn( self: *const IWMProfile3, nStorageFormat: WMT_STORAGE_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBandwidthSharingCount: fn( self: *const IWMProfile3, pcBS: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBandwidthSharing: fn( self: *const IWMProfile3, dwBSIndex: u32, ppBS: ?*?*IWMBandwidthSharing, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveBandwidthSharing: fn( self: *const IWMProfile3, pBS: ?*IWMBandwidthSharing, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddBandwidthSharing: fn( self: *const IWMProfile3, pBS: ?*IWMBandwidthSharing, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewBandwidthSharing: fn( self: *const IWMProfile3, ppBS: ?*?*IWMBandwidthSharing, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamPrioritization: fn( self: *const IWMProfile3, ppSP: ?*?*IWMStreamPrioritization, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamPrioritization: fn( self: *const IWMProfile3, pSP: ?*IWMStreamPrioritization, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveStreamPrioritization: fn( self: *const IWMProfile3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewStreamPrioritization: fn( self: *const IWMProfile3, ppSP: ?*?*IWMStreamPrioritization, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExpectedPacketCount: fn( self: *const IWMProfile3, msDuration: u64, pcPackets: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMProfile2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_GetStorageFormat(self: *const T, pnStorageFormat: ?*WMT_STORAGE_FORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).GetStorageFormat(@ptrCast(*const IWMProfile3, self), pnStorageFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_SetStorageFormat(self: *const T, nStorageFormat: WMT_STORAGE_FORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).SetStorageFormat(@ptrCast(*const IWMProfile3, self), nStorageFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_GetBandwidthSharingCount(self: *const T, pcBS: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).GetBandwidthSharingCount(@ptrCast(*const IWMProfile3, self), pcBS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_GetBandwidthSharing(self: *const T, dwBSIndex: u32, ppBS: ?*?*IWMBandwidthSharing) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).GetBandwidthSharing(@ptrCast(*const IWMProfile3, self), dwBSIndex, ppBS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_RemoveBandwidthSharing(self: *const T, pBS: ?*IWMBandwidthSharing) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).RemoveBandwidthSharing(@ptrCast(*const IWMProfile3, self), pBS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_AddBandwidthSharing(self: *const T, pBS: ?*IWMBandwidthSharing) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).AddBandwidthSharing(@ptrCast(*const IWMProfile3, self), pBS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_CreateNewBandwidthSharing(self: *const T, ppBS: ?*?*IWMBandwidthSharing) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).CreateNewBandwidthSharing(@ptrCast(*const IWMProfile3, self), ppBS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_GetStreamPrioritization(self: *const T, ppSP: ?*?*IWMStreamPrioritization) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).GetStreamPrioritization(@ptrCast(*const IWMProfile3, self), ppSP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_SetStreamPrioritization(self: *const T, pSP: ?*IWMStreamPrioritization) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).SetStreamPrioritization(@ptrCast(*const IWMProfile3, self), pSP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_RemoveStreamPrioritization(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).RemoveStreamPrioritization(@ptrCast(*const IWMProfile3, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_CreateNewStreamPrioritization(self: *const T, ppSP: ?*?*IWMStreamPrioritization) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).CreateNewStreamPrioritization(@ptrCast(*const IWMProfile3, self), ppSP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProfile3_GetExpectedPacketCount(self: *const T, msDuration: u64, pcPackets: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProfile3.VTable, self.vtable).GetExpectedPacketCount(@ptrCast(*const IWMProfile3, self), msDuration, pcPackets); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStreamConfig_Value = Guid.initString("96406bdc-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMStreamConfig = &IID_IWMStreamConfig_Value; pub const IWMStreamConfig = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStreamType: fn( self: *const IWMStreamConfig, pguidStreamType: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamNumber: fn( self: *const IWMStreamConfig, pwStreamNum: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamNumber: fn( self: *const IWMStreamConfig, wStreamNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamName: fn( self: *const IWMStreamConfig, pwszStreamName: [*:0]u16, pcchStreamName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamName: fn( self: *const IWMStreamConfig, pwszStreamName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectionName: fn( self: *const IWMStreamConfig, pwszInputName: [*:0]u16, pcchInputName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConnectionName: fn( self: *const IWMStreamConfig, pwszInputName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBitrate: fn( self: *const IWMStreamConfig, pdwBitrate: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBitrate: fn( self: *const IWMStreamConfig, pdwBitrate: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBufferWindow: fn( self: *const IWMStreamConfig, pmsBufferWindow: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBufferWindow: fn( self: *const IWMStreamConfig, msBufferWindow: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetStreamType(self: *const T, pguidStreamType: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetStreamType(@ptrCast(*const IWMStreamConfig, self), pguidStreamType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetStreamNumber(self: *const T, pwStreamNum: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetStreamNumber(@ptrCast(*const IWMStreamConfig, self), pwStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_SetStreamNumber(self: *const T, wStreamNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).SetStreamNumber(@ptrCast(*const IWMStreamConfig, self), wStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetStreamName(self: *const T, pwszStreamName: [*:0]u16, pcchStreamName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetStreamName(@ptrCast(*const IWMStreamConfig, self), pwszStreamName, pcchStreamName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_SetStreamName(self: *const T, pwszStreamName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).SetStreamName(@ptrCast(*const IWMStreamConfig, self), pwszStreamName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetConnectionName(self: *const T, pwszInputName: [*:0]u16, pcchInputName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetConnectionName(@ptrCast(*const IWMStreamConfig, self), pwszInputName, pcchInputName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_SetConnectionName(self: *const T, pwszInputName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).SetConnectionName(@ptrCast(*const IWMStreamConfig, self), pwszInputName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetBitrate(self: *const T, pdwBitrate: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetBitrate(@ptrCast(*const IWMStreamConfig, self), pdwBitrate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_SetBitrate(self: *const T, pdwBitrate: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).SetBitrate(@ptrCast(*const IWMStreamConfig, self), pdwBitrate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_GetBufferWindow(self: *const T, pmsBufferWindow: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).GetBufferWindow(@ptrCast(*const IWMStreamConfig, self), pmsBufferWindow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig_SetBufferWindow(self: *const T, msBufferWindow: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig.VTable, self.vtable).SetBufferWindow(@ptrCast(*const IWMStreamConfig, self), msBufferWindow); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStreamConfig2_Value = Guid.initString("7688d8cb-fc0d-43bd-9459-5a8dec200cfa"); pub const IID_IWMStreamConfig2 = &IID_IWMStreamConfig2_Value; pub const IWMStreamConfig2 = extern struct { pub const VTable = extern struct { base: IWMStreamConfig.VTable, GetTransportType: fn( self: *const IWMStreamConfig2, pnTransportType: ?*WMT_TRANSPORT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransportType: fn( self: *const IWMStreamConfig2, nTransportType: WMT_TRANSPORT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDataUnitExtension: fn( self: *const IWMStreamConfig2, guidExtensionSystemID: Guid, cbExtensionDataSize: u16, pbExtensionSystemInfo: [*:0]u8, cbExtensionSystemInfo: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataUnitExtensionCount: fn( self: *const IWMStreamConfig2, pcDataUnitExtensions: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataUnitExtension: fn( self: *const IWMStreamConfig2, wDataUnitExtensionNumber: u16, pguidExtensionSystemID: ?*Guid, pcbExtensionDataSize: ?*u16, pbExtensionSystemInfo: [*:0]u8, pcbExtensionSystemInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAllDataUnitExtensions: fn( self: *const IWMStreamConfig2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStreamConfig.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_GetTransportType(self: *const T, pnTransportType: ?*WMT_TRANSPORT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).GetTransportType(@ptrCast(*const IWMStreamConfig2, self), pnTransportType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_SetTransportType(self: *const T, nTransportType: WMT_TRANSPORT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).SetTransportType(@ptrCast(*const IWMStreamConfig2, self), nTransportType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_AddDataUnitExtension(self: *const T, guidExtensionSystemID: Guid, cbExtensionDataSize: u16, pbExtensionSystemInfo: [*:0]u8, cbExtensionSystemInfo: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).AddDataUnitExtension(@ptrCast(*const IWMStreamConfig2, self), guidExtensionSystemID, cbExtensionDataSize, pbExtensionSystemInfo, cbExtensionSystemInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_GetDataUnitExtensionCount(self: *const T, pcDataUnitExtensions: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).GetDataUnitExtensionCount(@ptrCast(*const IWMStreamConfig2, self), pcDataUnitExtensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_GetDataUnitExtension(self: *const T, wDataUnitExtensionNumber: u16, pguidExtensionSystemID: ?*Guid, pcbExtensionDataSize: ?*u16, pbExtensionSystemInfo: [*:0]u8, pcbExtensionSystemInfo: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).GetDataUnitExtension(@ptrCast(*const IWMStreamConfig2, self), wDataUnitExtensionNumber, pguidExtensionSystemID, pcbExtensionDataSize, pbExtensionSystemInfo, pcbExtensionSystemInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig2_RemoveAllDataUnitExtensions(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig2.VTable, self.vtable).RemoveAllDataUnitExtensions(@ptrCast(*const IWMStreamConfig2, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStreamConfig3_Value = Guid.initString("cb164104-3aa9-45a7-9ac9-4daee131d6e1"); pub const IID_IWMStreamConfig3 = &IID_IWMStreamConfig3_Value; pub const IWMStreamConfig3 = extern struct { pub const VTable = extern struct { base: IWMStreamConfig2.VTable, GetLanguage: fn( self: *const IWMStreamConfig3, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLanguage: fn( self: *const IWMStreamConfig3, pwszLanguageString: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStreamConfig2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig3_GetLanguage(self: *const T, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig3.VTable, self.vtable).GetLanguage(@ptrCast(*const IWMStreamConfig3, self), pwszLanguageString, pcchLanguageStringLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamConfig3_SetLanguage(self: *const T, pwszLanguageString: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamConfig3.VTable, self.vtable).SetLanguage(@ptrCast(*const IWMStreamConfig3, self), pwszLanguageString); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMPacketSize_Value = Guid.initString("cdfb97ab-188f-40b3-b643-5b7903975c59"); pub const IID_IWMPacketSize = &IID_IWMPacketSize_Value; pub const IWMPacketSize = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMaxPacketSize: fn( self: *const IWMPacketSize, pdwMaxPacketSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMaxPacketSize: fn( self: *const IWMPacketSize, dwMaxPacketSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPacketSize_GetMaxPacketSize(self: *const T, pdwMaxPacketSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPacketSize.VTable, self.vtable).GetMaxPacketSize(@ptrCast(*const IWMPacketSize, self), pdwMaxPacketSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPacketSize_SetMaxPacketSize(self: *const T, dwMaxPacketSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPacketSize.VTable, self.vtable).SetMaxPacketSize(@ptrCast(*const IWMPacketSize, self), dwMaxPacketSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMPacketSize2_Value = Guid.initString("8bfc2b9e-b646-4233-a877-1c6a079669dc"); pub const IID_IWMPacketSize2 = &IID_IWMPacketSize2_Value; pub const IWMPacketSize2 = extern struct { pub const VTable = extern struct { base: IWMPacketSize.VTable, GetMinPacketSize: fn( self: *const IWMPacketSize2, pdwMinPacketSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMinPacketSize: fn( self: *const IWMPacketSize2, dwMinPacketSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMPacketSize.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPacketSize2_GetMinPacketSize(self: *const T, pdwMinPacketSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPacketSize2.VTable, self.vtable).GetMinPacketSize(@ptrCast(*const IWMPacketSize2, self), pdwMinPacketSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPacketSize2_SetMinPacketSize(self: *const T, dwMinPacketSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPacketSize2.VTable, self.vtable).SetMinPacketSize(@ptrCast(*const IWMPacketSize2, self), dwMinPacketSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStreamList_Value = Guid.initString("96406bdd-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMStreamList = &IID_IWMStreamList_Value; pub const IWMStreamList = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStreams: fn( self: *const IWMStreamList, pwStreamNumArray: [*:0]u16, pcStreams: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddStream: fn( self: *const IWMStreamList, wStreamNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveStream: fn( self: *const IWMStreamList, wStreamNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamList_GetStreams(self: *const T, pwStreamNumArray: [*:0]u16, pcStreams: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamList.VTable, self.vtable).GetStreams(@ptrCast(*const IWMStreamList, self), pwStreamNumArray, pcStreams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamList_AddStream(self: *const T, wStreamNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamList.VTable, self.vtable).AddStream(@ptrCast(*const IWMStreamList, self), wStreamNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamList_RemoveStream(self: *const T, wStreamNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamList.VTable, self.vtable).RemoveStream(@ptrCast(*const IWMStreamList, self), wStreamNum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMMutualExclusion_Value = Guid.initString("96406bde-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMMutualExclusion = &IID_IWMMutualExclusion_Value; pub const IWMMutualExclusion = extern struct { pub const VTable = extern struct { base: IWMStreamList.VTable, GetType: fn( self: *const IWMMutualExclusion, pguidType: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetType: fn( self: *const IWMMutualExclusion, guidType: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStreamList.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion_GetType(self: *const T, pguidType: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion.VTable, self.vtable).GetType(@ptrCast(*const IWMMutualExclusion, self), pguidType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion_SetType(self: *const T, guidType: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion.VTable, self.vtable).SetType(@ptrCast(*const IWMMutualExclusion, self), guidType); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMMutualExclusion2_Value = Guid.initString("0302b57d-89d1-4ba2-85c9-166f2c53eb91"); pub const IID_IWMMutualExclusion2 = &IID_IWMMutualExclusion2_Value; pub const IWMMutualExclusion2 = extern struct { pub const VTable = extern struct { base: IWMMutualExclusion.VTable, GetName: fn( self: *const IWMMutualExclusion2, pwszName: [*:0]u16, pcchName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const IWMMutualExclusion2, pwszName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRecordCount: fn( self: *const IWMMutualExclusion2, pwRecordCount: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRecord: fn( self: *const IWMMutualExclusion2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveRecord: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRecordName: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, pwszRecordName: [*:0]u16, pcchRecordName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRecordName: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, pwszRecordName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamsForRecord: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, pwStreamNumArray: [*:0]u16, pcStreams: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddStreamForRecord: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, wStreamNumber: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveStreamForRecord: fn( self: *const IWMMutualExclusion2, wRecordNumber: u16, wStreamNumber: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMMutualExclusion.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_GetName(self: *const T, pwszName: [*:0]u16, pcchName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).GetName(@ptrCast(*const IWMMutualExclusion2, self), pwszName, pcchName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_SetName(self: *const T, pwszName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).SetName(@ptrCast(*const IWMMutualExclusion2, self), pwszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_GetRecordCount(self: *const T, pwRecordCount: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).GetRecordCount(@ptrCast(*const IWMMutualExclusion2, self), pwRecordCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_AddRecord(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).AddRecord(@ptrCast(*const IWMMutualExclusion2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_RemoveRecord(self: *const T, wRecordNumber: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).RemoveRecord(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_GetRecordName(self: *const T, wRecordNumber: u16, pwszRecordName: [*:0]u16, pcchRecordName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).GetRecordName(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber, pwszRecordName, pcchRecordName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_SetRecordName(self: *const T, wRecordNumber: u16, pwszRecordName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).SetRecordName(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber, pwszRecordName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_GetStreamsForRecord(self: *const T, wRecordNumber: u16, pwStreamNumArray: [*:0]u16, pcStreams: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).GetStreamsForRecord(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber, pwStreamNumArray, pcStreams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_AddStreamForRecord(self: *const T, wRecordNumber: u16, wStreamNumber: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).AddStreamForRecord(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber, wStreamNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMMutualExclusion2_RemoveStreamForRecord(self: *const T, wRecordNumber: u16, wStreamNumber: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMMutualExclusion2.VTable, self.vtable).RemoveStreamForRecord(@ptrCast(*const IWMMutualExclusion2, self), wRecordNumber, wStreamNumber); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMBandwidthSharing_Value = Guid.initString("ad694af1-f8d9-42f8-bc47-70311b0c4f9e"); pub const IID_IWMBandwidthSharing = &IID_IWMBandwidthSharing_Value; pub const IWMBandwidthSharing = extern struct { pub const VTable = extern struct { base: IWMStreamList.VTable, GetType: fn( self: *const IWMBandwidthSharing, pguidType: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetType: fn( self: *const IWMBandwidthSharing, guidType: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBandwidth: fn( self: *const IWMBandwidthSharing, pdwBitrate: ?*u32, pmsBufferWindow: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBandwidth: fn( self: *const IWMBandwidthSharing, dwBitrate: u32, msBufferWindow: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStreamList.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBandwidthSharing_GetType(self: *const T, pguidType: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBandwidthSharing.VTable, self.vtable).GetType(@ptrCast(*const IWMBandwidthSharing, self), pguidType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBandwidthSharing_SetType(self: *const T, guidType: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBandwidthSharing.VTable, self.vtable).SetType(@ptrCast(*const IWMBandwidthSharing, self), guidType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBandwidthSharing_GetBandwidth(self: *const T, pdwBitrate: ?*u32, pmsBufferWindow: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBandwidthSharing.VTable, self.vtable).GetBandwidth(@ptrCast(*const IWMBandwidthSharing, self), pdwBitrate, pmsBufferWindow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBandwidthSharing_SetBandwidth(self: *const T, dwBitrate: u32, msBufferWindow: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBandwidthSharing.VTable, self.vtable).SetBandwidth(@ptrCast(*const IWMBandwidthSharing, self), dwBitrate, msBufferWindow); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMStreamPrioritization_Value = Guid.initString("8c1c6090-f9a8-4748-8ec3-dd1108ba1e77"); pub const IID_IWMStreamPrioritization = &IID_IWMStreamPrioritization_Value; pub const IWMStreamPrioritization = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPriorityRecords: fn( self: *const IWMStreamPrioritization, pRecordArray: [*]WM_STREAM_PRIORITY_RECORD, pcRecords: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPriorityRecords: fn( self: *const IWMStreamPrioritization, pRecordArray: ?*WM_STREAM_PRIORITY_RECORD, cRecords: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamPrioritization_GetPriorityRecords(self: *const T, pRecordArray: [*]WM_STREAM_PRIORITY_RECORD, pcRecords: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamPrioritization.VTable, self.vtable).GetPriorityRecords(@ptrCast(*const IWMStreamPrioritization, self), pRecordArray, pcRecords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMStreamPrioritization_SetPriorityRecords(self: *const T, pRecordArray: ?*WM_STREAM_PRIORITY_RECORD, cRecords: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMStreamPrioritization.VTable, self.vtable).SetPriorityRecords(@ptrCast(*const IWMStreamPrioritization, self), pRecordArray, cRecords); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterAdvanced_Value = Guid.initString("96406be3-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMWriterAdvanced = &IID_IWMWriterAdvanced_Value; pub const IWMWriterAdvanced = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSinkCount: fn( self: *const IWMWriterAdvanced, pcSinks: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSink: fn( self: *const IWMWriterAdvanced, dwSinkNum: u32, ppSink: ?*?*IWMWriterSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddSink: fn( self: *const IWMWriterAdvanced, pSink: ?*IWMWriterSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveSink: fn( self: *const IWMWriterAdvanced, pSink: ?*IWMWriterSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteStreamSample: fn( self: *const IWMWriterAdvanced, wStreamNum: u16, cnsSampleTime: u64, msSampleSendTime: u32, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLiveSource: fn( self: *const IWMWriterAdvanced, fIsLiveSource: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsRealTime: fn( self: *const IWMWriterAdvanced, pfRealTime: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWriterTime: fn( self: *const IWMWriterAdvanced, pcnsCurrentTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatistics: fn( self: *const IWMWriterAdvanced, wStreamNum: u16, pStats: ?*WM_WRITER_STATISTICS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSyncTolerance: fn( self: *const IWMWriterAdvanced, msWindow: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSyncTolerance: fn( self: *const IWMWriterAdvanced, pmsWindow: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_GetSinkCount(self: *const T, pcSinks: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).GetSinkCount(@ptrCast(*const IWMWriterAdvanced, self), pcSinks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_GetSink(self: *const T, dwSinkNum: u32, ppSink: ?*?*IWMWriterSink) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).GetSink(@ptrCast(*const IWMWriterAdvanced, self), dwSinkNum, ppSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_AddSink(self: *const T, pSink: ?*IWMWriterSink) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).AddSink(@ptrCast(*const IWMWriterAdvanced, self), pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_RemoveSink(self: *const T, pSink: ?*IWMWriterSink) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).RemoveSink(@ptrCast(*const IWMWriterAdvanced, self), pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_WriteStreamSample(self: *const T, wStreamNum: u16, cnsSampleTime: u64, msSampleSendTime: u32, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).WriteStreamSample(@ptrCast(*const IWMWriterAdvanced, self), wStreamNum, cnsSampleTime, msSampleSendTime, cnsSampleDuration, dwFlags, pSample); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_SetLiveSource(self: *const T, fIsLiveSource: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).SetLiveSource(@ptrCast(*const IWMWriterAdvanced, self), fIsLiveSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_IsRealTime(self: *const T, pfRealTime: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).IsRealTime(@ptrCast(*const IWMWriterAdvanced, self), pfRealTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_GetWriterTime(self: *const T, pcnsCurrentTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).GetWriterTime(@ptrCast(*const IWMWriterAdvanced, self), pcnsCurrentTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_GetStatistics(self: *const T, wStreamNum: u16, pStats: ?*WM_WRITER_STATISTICS) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).GetStatistics(@ptrCast(*const IWMWriterAdvanced, self), wStreamNum, pStats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_SetSyncTolerance(self: *const T, msWindow: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).SetSyncTolerance(@ptrCast(*const IWMWriterAdvanced, self), msWindow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced_GetSyncTolerance(self: *const T, pmsWindow: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced.VTable, self.vtable).GetSyncTolerance(@ptrCast(*const IWMWriterAdvanced, self), pmsWindow); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterAdvanced2_Value = Guid.initString("962dc1ec-c046-4db8-9cc7-26ceae500817"); pub const IID_IWMWriterAdvanced2 = &IID_IWMWriterAdvanced2_Value; pub const IWMWriterAdvanced2 = extern struct { pub const VTable = extern struct { base: IWMWriterAdvanced.VTable, GetInputSetting: fn( self: *const IWMWriterAdvanced2, dwInputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetInputSetting: fn( self: *const IWMWriterAdvanced2, dwInputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterAdvanced.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced2_GetInputSetting(self: *const T, dwInputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced2.VTable, self.vtable).GetInputSetting(@ptrCast(*const IWMWriterAdvanced2, self), dwInputNum, pszName, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced2_SetInputSetting(self: *const T, dwInputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced2.VTable, self.vtable).SetInputSetting(@ptrCast(*const IWMWriterAdvanced2, self), dwInputNum, pszName, Type, pValue, cbLength); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterAdvanced3_Value = Guid.initString("2cd6492d-7c37-4e76-9d3b-59261183a22e"); pub const IID_IWMWriterAdvanced3 = &IID_IWMWriterAdvanced3_Value; pub const IWMWriterAdvanced3 = extern struct { pub const VTable = extern struct { base: IWMWriterAdvanced2.VTable, GetStatisticsEx: fn( self: *const IWMWriterAdvanced3, wStreamNum: u16, pStats: ?*WM_WRITER_STATISTICS_EX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNonBlocking: fn( self: *const IWMWriterAdvanced3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterAdvanced2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced3_GetStatisticsEx(self: *const T, wStreamNum: u16, pStats: ?*WM_WRITER_STATISTICS_EX) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced3.VTable, self.vtable).GetStatisticsEx(@ptrCast(*const IWMWriterAdvanced3, self), wStreamNum, pStats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterAdvanced3_SetNonBlocking(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterAdvanced3.VTable, self.vtable).SetNonBlocking(@ptrCast(*const IWMWriterAdvanced3, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterPreprocess_Value = Guid.initString("fc54a285-38c4-45b5-aa23-85b9f7cb424b"); pub const IID_IWMWriterPreprocess = &IID_IWMWriterPreprocess_Value; pub const IWMWriterPreprocess = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMaxPreprocessingPasses: fn( self: *const IWMWriterPreprocess, dwInputNum: u32, dwFlags: u32, pdwMaxNumPasses: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNumPreprocessingPasses: fn( self: *const IWMWriterPreprocess, dwInputNum: u32, dwFlags: u32, dwNumPasses: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginPreprocessingPass: fn( self: *const IWMWriterPreprocess, dwInputNum: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PreprocessSample: fn( self: *const IWMWriterPreprocess, dwInputNum: u32, cnsSampleTime: u64, dwFlags: u32, pSample: ?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndPreprocessingPass: fn( self: *const IWMWriterPreprocess, dwInputNum: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPreprocess_GetMaxPreprocessingPasses(self: *const T, dwInputNum: u32, dwFlags: u32, pdwMaxNumPasses: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPreprocess.VTable, self.vtable).GetMaxPreprocessingPasses(@ptrCast(*const IWMWriterPreprocess, self), dwInputNum, dwFlags, pdwMaxNumPasses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPreprocess_SetNumPreprocessingPasses(self: *const T, dwInputNum: u32, dwFlags: u32, dwNumPasses: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPreprocess.VTable, self.vtable).SetNumPreprocessingPasses(@ptrCast(*const IWMWriterPreprocess, self), dwInputNum, dwFlags, dwNumPasses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPreprocess_BeginPreprocessingPass(self: *const T, dwInputNum: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPreprocess.VTable, self.vtable).BeginPreprocessingPass(@ptrCast(*const IWMWriterPreprocess, self), dwInputNum, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPreprocess_PreprocessSample(self: *const T, dwInputNum: u32, cnsSampleTime: u64, dwFlags: u32, pSample: ?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPreprocess.VTable, self.vtable).PreprocessSample(@ptrCast(*const IWMWriterPreprocess, self), dwInputNum, cnsSampleTime, dwFlags, pSample); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPreprocess_EndPreprocessingPass(self: *const T, dwInputNum: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPreprocess.VTable, self.vtable).EndPreprocessingPass(@ptrCast(*const IWMWriterPreprocess, self), dwInputNum, dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterPostViewCallback_Value = Guid.initString("d9d6549d-a193-4f24-b308-03123d9b7f8d"); pub const IID_IWMWriterPostViewCallback = &IID_IWMWriterPostViewCallback_Value; pub const IWMWriterPostViewCallback = extern struct { pub const VTable = extern struct { base: IWMStatusCallback.VTable, OnPostViewSample: fn( self: *const IWMWriterPostViewCallback, wStreamNumber: u16, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateForPostView: fn( self: *const IWMWriterPostViewCallback, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMStatusCallback.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostViewCallback_OnPostViewSample(self: *const T, wStreamNumber: u16, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostViewCallback.VTable, self.vtable).OnPostViewSample(@ptrCast(*const IWMWriterPostViewCallback, self), wStreamNumber, cnsSampleTime, cnsSampleDuration, dwFlags, pSample, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostViewCallback_AllocateForPostView(self: *const T, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostViewCallback.VTable, self.vtable).AllocateForPostView(@ptrCast(*const IWMWriterPostViewCallback, self), wStreamNum, cbBuffer, ppBuffer, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterPostView_Value = Guid.initString("81e20ce4-75ef-491a-8004-fc53c45bdc3e"); pub const IID_IWMWriterPostView = &IID_IWMWriterPostView_Value; pub const IWMWriterPostView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetPostViewCallback: fn( self: *const IWMWriterPostView, pCallback: ?*IWMWriterPostViewCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReceivePostViewSamples: fn( self: *const IWMWriterPostView, wStreamNum: u16, fReceivePostViewSamples: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceivePostViewSamples: fn( self: *const IWMWriterPostView, wStreamNum: u16, pfReceivePostViewSamples: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPostViewProps: fn( self: *const IWMWriterPostView, wStreamNumber: u16, ppOutput: ?*?*IWMMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPostViewProps: fn( self: *const IWMWriterPostView, wStreamNumber: u16, pOutput: ?*IWMMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPostViewFormatCount: fn( self: *const IWMWriterPostView, wStreamNumber: u16, pcFormats: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPostViewFormat: fn( self: *const IWMWriterPostView, wStreamNumber: u16, dwFormatNumber: u32, ppProps: ?*?*IWMMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllocateForPostView: fn( self: *const IWMWriterPostView, wStreamNumber: u16, fAllocate: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllocateForPostView: fn( self: *const IWMWriterPostView, wStreamNumber: u16, pfAllocate: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_SetPostViewCallback(self: *const T, pCallback: ?*IWMWriterPostViewCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).SetPostViewCallback(@ptrCast(*const IWMWriterPostView, self), pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_SetReceivePostViewSamples(self: *const T, wStreamNum: u16, fReceivePostViewSamples: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).SetReceivePostViewSamples(@ptrCast(*const IWMWriterPostView, self), wStreamNum, fReceivePostViewSamples); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_GetReceivePostViewSamples(self: *const T, wStreamNum: u16, pfReceivePostViewSamples: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).GetReceivePostViewSamples(@ptrCast(*const IWMWriterPostView, self), wStreamNum, pfReceivePostViewSamples); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_GetPostViewProps(self: *const T, wStreamNumber: u16, ppOutput: ?*?*IWMMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).GetPostViewProps(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, ppOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_SetPostViewProps(self: *const T, wStreamNumber: u16, pOutput: ?*IWMMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).SetPostViewProps(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, pOutput); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_GetPostViewFormatCount(self: *const T, wStreamNumber: u16, pcFormats: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).GetPostViewFormatCount(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, pcFormats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_GetPostViewFormat(self: *const T, wStreamNumber: u16, dwFormatNumber: u32, ppProps: ?*?*IWMMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).GetPostViewFormat(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, dwFormatNumber, ppProps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_SetAllocateForPostView(self: *const T, wStreamNumber: u16, fAllocate: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).SetAllocateForPostView(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, fAllocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPostView_GetAllocateForPostView(self: *const T, wStreamNumber: u16, pfAllocate: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPostView.VTable, self.vtable).GetAllocateForPostView(@ptrCast(*const IWMWriterPostView, self), wStreamNumber, pfAllocate); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterSink_Value = Guid.initString("96406be4-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMWriterSink = &IID_IWMWriterSink_Value; pub const IWMWriterSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnHeader: fn( self: *const IWMWriterSink, pHeader: ?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsRealTime: fn( self: *const IWMWriterSink, pfRealTime: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateDataUnit: fn( self: *const IWMWriterSink, cbDataUnit: u32, ppDataUnit: ?*?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDataUnit: fn( self: *const IWMWriterSink, pDataUnit: ?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndWriting: fn( self: *const IWMWriterSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterSink_OnHeader(self: *const T, pHeader: ?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterSink.VTable, self.vtable).OnHeader(@ptrCast(*const IWMWriterSink, self), pHeader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterSink_IsRealTime(self: *const T, pfRealTime: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterSink.VTable, self.vtable).IsRealTime(@ptrCast(*const IWMWriterSink, self), pfRealTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterSink_AllocateDataUnit(self: *const T, cbDataUnit: u32, ppDataUnit: ?*?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterSink.VTable, self.vtable).AllocateDataUnit(@ptrCast(*const IWMWriterSink, self), cbDataUnit, ppDataUnit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterSink_OnDataUnit(self: *const T, pDataUnit: ?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterSink.VTable, self.vtable).OnDataUnit(@ptrCast(*const IWMWriterSink, self), pDataUnit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterSink_OnEndWriting(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterSink.VTable, self.vtable).OnEndWriting(@ptrCast(*const IWMWriterSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMRegisterCallback_Value = Guid.initString("cf4b1f99-4de2-4e49-a363-252740d99bc1"); pub const IID_IWMRegisterCallback = &IID_IWMRegisterCallback_Value; pub const IWMRegisterCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Advise: fn( self: *const IWMRegisterCallback, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IWMRegisterCallback, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisterCallback_Advise(self: *const T, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisterCallback.VTable, self.vtable).Advise(@ptrCast(*const IWMRegisterCallback, self), pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisterCallback_Unadvise(self: *const T, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisterCallback.VTable, self.vtable).Unadvise(@ptrCast(*const IWMRegisterCallback, self), pCallback, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterFileSink_Value = Guid.initString("96406be5-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMWriterFileSink = &IID_IWMWriterFileSink_Value; pub const IWMWriterFileSink = extern struct { pub const VTable = extern struct { base: IWMWriterSink.VTable, Open: fn( self: *const IWMWriterFileSink, pwszFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink_Open(self: *const T, pwszFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink.VTable, self.vtable).Open(@ptrCast(*const IWMWriterFileSink, self), pwszFilename); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterFileSink2_Value = Guid.initString("14282ba7-4aef-4205-8ce5-c229035a05bc"); pub const IID_IWMWriterFileSink2 = &IID_IWMWriterFileSink2_Value; pub const IWMWriterFileSink2 = extern struct { pub const VTable = extern struct { base: IWMWriterFileSink.VTable, Start: fn( self: *const IWMWriterFileSink2, cnsStartTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IWMWriterFileSink2, cnsStopTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsStopped: fn( self: *const IWMWriterFileSink2, pfStopped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFileDuration: fn( self: *const IWMWriterFileSink2, pcnsDuration: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFileSize: fn( self: *const IWMWriterFileSink2, pcbFile: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMWriterFileSink2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsClosed: fn( self: *const IWMWriterFileSink2, pfClosed: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterFileSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_Start(self: *const T, cnsStartTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).Start(@ptrCast(*const IWMWriterFileSink2, self), cnsStartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_Stop(self: *const T, cnsStopTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).Stop(@ptrCast(*const IWMWriterFileSink2, self), cnsStopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_IsStopped(self: *const T, pfStopped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).IsStopped(@ptrCast(*const IWMWriterFileSink2, self), pfStopped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_GetFileDuration(self: *const T, pcnsDuration: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).GetFileDuration(@ptrCast(*const IWMWriterFileSink2, self), pcnsDuration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_GetFileSize(self: *const T, pcbFile: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).GetFileSize(@ptrCast(*const IWMWriterFileSink2, self), pcbFile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).Close(@ptrCast(*const IWMWriterFileSink2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink2_IsClosed(self: *const T, pfClosed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink2.VTable, self.vtable).IsClosed(@ptrCast(*const IWMWriterFileSink2, self), pfClosed); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterFileSink3_Value = Guid.initString("3fea4feb-2945-47a7-a1dd-c53a8fc4c45c"); pub const IID_IWMWriterFileSink3 = &IID_IWMWriterFileSink3_Value; pub const IWMWriterFileSink3 = extern struct { pub const VTable = extern struct { base: IWMWriterFileSink2.VTable, SetAutoIndexing: fn( self: *const IWMWriterFileSink3, fDoAutoIndexing: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAutoIndexing: fn( self: *const IWMWriterFileSink3, pfAutoIndexing: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetControlStream: fn( self: *const IWMWriterFileSink3, wStreamNumber: u16, fShouldControlStartAndStop: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMode: fn( self: *const IWMWriterFileSink3, pdwFileSinkMode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDataUnitEx: fn( self: *const IWMWriterFileSink3, pFileSinkDataUnit: ?*WMT_FILESINK_DATA_UNIT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUnbufferedIO: fn( self: *const IWMWriterFileSink3, fUnbufferedIO: BOOL, fRestrictMemUsage: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUnbufferedIO: fn( self: *const IWMWriterFileSink3, pfUnbufferedIO: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompleteOperations: fn( self: *const IWMWriterFileSink3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterFileSink2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_SetAutoIndexing(self: *const T, fDoAutoIndexing: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).SetAutoIndexing(@ptrCast(*const IWMWriterFileSink3, self), fDoAutoIndexing); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_GetAutoIndexing(self: *const T, pfAutoIndexing: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).GetAutoIndexing(@ptrCast(*const IWMWriterFileSink3, self), pfAutoIndexing); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_SetControlStream(self: *const T, wStreamNumber: u16, fShouldControlStartAndStop: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).SetControlStream(@ptrCast(*const IWMWriterFileSink3, self), wStreamNumber, fShouldControlStartAndStop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_GetMode(self: *const T, pdwFileSinkMode: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).GetMode(@ptrCast(*const IWMWriterFileSink3, self), pdwFileSinkMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_OnDataUnitEx(self: *const T, pFileSinkDataUnit: ?*WMT_FILESINK_DATA_UNIT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).OnDataUnitEx(@ptrCast(*const IWMWriterFileSink3, self), pFileSinkDataUnit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_SetUnbufferedIO(self: *const T, fUnbufferedIO: BOOL, fRestrictMemUsage: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).SetUnbufferedIO(@ptrCast(*const IWMWriterFileSink3, self), fUnbufferedIO, fRestrictMemUsage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_GetUnbufferedIO(self: *const T, pfUnbufferedIO: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).GetUnbufferedIO(@ptrCast(*const IWMWriterFileSink3, self), pfUnbufferedIO); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterFileSink3_CompleteOperations(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterFileSink3.VTable, self.vtable).CompleteOperations(@ptrCast(*const IWMWriterFileSink3, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterNetworkSink_Value = Guid.initString("96406be7-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMWriterNetworkSink = &IID_IWMWriterNetworkSink_Value; pub const IWMWriterNetworkSink = extern struct { pub const VTable = extern struct { base: IWMWriterSink.VTable, SetMaximumClients: fn( self: *const IWMWriterNetworkSink, dwMaxClients: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaximumClients: fn( self: *const IWMWriterNetworkSink, pdwMaxClients: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNetworkProtocol: fn( self: *const IWMWriterNetworkSink, protocol: WMT_NET_PROTOCOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetworkProtocol: fn( self: *const IWMWriterNetworkSink, pProtocol: ?*WMT_NET_PROTOCOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHostURL: fn( self: *const IWMWriterNetworkSink, pwszURL: ?PWSTR, pcchURL: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Open: fn( self: *const IWMWriterNetworkSink, pdwPortNum: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const IWMWriterNetworkSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMWriterNetworkSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_SetMaximumClients(self: *const T, dwMaxClients: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).SetMaximumClients(@ptrCast(*const IWMWriterNetworkSink, self), dwMaxClients); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_GetMaximumClients(self: *const T, pdwMaxClients: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).GetMaximumClients(@ptrCast(*const IWMWriterNetworkSink, self), pdwMaxClients); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_SetNetworkProtocol(self: *const T, protocol: WMT_NET_PROTOCOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).SetNetworkProtocol(@ptrCast(*const IWMWriterNetworkSink, self), protocol); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_GetNetworkProtocol(self: *const T, pProtocol: ?*WMT_NET_PROTOCOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).GetNetworkProtocol(@ptrCast(*const IWMWriterNetworkSink, self), pProtocol); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_GetHostURL(self: *const T, pwszURL: ?PWSTR, pcchURL: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).GetHostURL(@ptrCast(*const IWMWriterNetworkSink, self), pwszURL, pcchURL); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_Open(self: *const T, pdwPortNum: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).Open(@ptrCast(*const IWMWriterNetworkSink, self), pdwPortNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).Disconnect(@ptrCast(*const IWMWriterNetworkSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterNetworkSink_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterNetworkSink.VTable, self.vtable).Close(@ptrCast(*const IWMWriterNetworkSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMClientConnections_Value = Guid.initString("73c66010-a299-41df-b1f0-ccf03b09c1c6"); pub const IID_IWMClientConnections = &IID_IWMClientConnections_Value; pub const IWMClientConnections = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetClientCount: fn( self: *const IWMClientConnections, pcClients: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClientProperties: fn( self: *const IWMClientConnections, dwClientNum: u32, pClientProperties: ?*WM_CLIENT_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMClientConnections_GetClientCount(self: *const T, pcClients: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMClientConnections.VTable, self.vtable).GetClientCount(@ptrCast(*const IWMClientConnections, self), pcClients); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMClientConnections_GetClientProperties(self: *const T, dwClientNum: u32, pClientProperties: ?*WM_CLIENT_PROPERTIES) callconv(.Inline) HRESULT { return @ptrCast(*const IWMClientConnections.VTable, self.vtable).GetClientProperties(@ptrCast(*const IWMClientConnections, self), dwClientNum, pClientProperties); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMClientConnections2_Value = Guid.initString("4091571e-4701-4593-bb3d-d5f5f0c74246"); pub const IID_IWMClientConnections2 = &IID_IWMClientConnections2_Value; pub const IWMClientConnections2 = extern struct { pub const VTable = extern struct { base: IWMClientConnections.VTable, GetClientInfo: fn( self: *const IWMClientConnections2, dwClientNum: u32, pwszNetworkAddress: [*:0]u16, pcchNetworkAddress: ?*u32, pwszPort: [*:0]u16, pcchPort: ?*u32, pwszDNSName: [*:0]u16, pcchDNSName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMClientConnections.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMClientConnections2_GetClientInfo(self: *const T, dwClientNum: u32, pwszNetworkAddress: [*:0]u16, pcchNetworkAddress: ?*u32, pwszPort: [*:0]u16, pcchPort: ?*u32, pwszDNSName: [*:0]u16, pcchDNSName: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMClientConnections2.VTable, self.vtable).GetClientInfo(@ptrCast(*const IWMClientConnections2, self), dwClientNum, pwszNetworkAddress, pcchNetworkAddress, pwszPort, pcchPort, pwszDNSName, pcchDNSName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced_Value = Guid.initString("96406bea-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReaderAdvanced = &IID_IWMReaderAdvanced_Value; pub const IWMReaderAdvanced = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetUserProvidedClock: fn( self: *const IWMReaderAdvanced, fUserClock: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUserProvidedClock: fn( self: *const IWMReaderAdvanced, pfUserClock: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeliverTime: fn( self: *const IWMReaderAdvanced, cnsTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetManualStreamSelection: fn( self: *const IWMReaderAdvanced, fSelection: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetManualStreamSelection: fn( self: *const IWMReaderAdvanced, pfSelection: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamsSelected: fn( self: *const IWMReaderAdvanced, cStreamCount: u16, pwStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamSelected: fn( self: *const IWMReaderAdvanced, wStreamNum: u16, pSelection: ?*WMT_STREAM_SELECTION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReceiveSelectionCallbacks: fn( self: *const IWMReaderAdvanced, fGetCallbacks: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveSelectionCallbacks: fn( self: *const IWMReaderAdvanced, pfGetCallbacks: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReceiveStreamSamples: fn( self: *const IWMReaderAdvanced, wStreamNum: u16, fReceiveStreamSamples: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveStreamSamples: fn( self: *const IWMReaderAdvanced, wStreamNum: u16, pfReceiveStreamSamples: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllocateForOutput: fn( self: *const IWMReaderAdvanced, dwOutputNum: u32, fAllocate: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllocateForOutput: fn( self: *const IWMReaderAdvanced, dwOutputNum: u32, pfAllocate: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllocateForStream: fn( self: *const IWMReaderAdvanced, wStreamNum: u16, fAllocate: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllocateForStream: fn( self: *const IWMReaderAdvanced, dwSreamNum: u16, pfAllocate: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatistics: fn( self: *const IWMReaderAdvanced, pStatistics: ?*WM_READER_STATISTICS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClientInfo: fn( self: *const IWMReaderAdvanced, pClientInfo: ?*WM_READER_CLIENTINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxOutputSampleSize: fn( self: *const IWMReaderAdvanced, dwOutput: u32, pcbMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxStreamSampleSize: fn( self: *const IWMReaderAdvanced, wStream: u16, pcbMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyLateDelivery: fn( self: *const IWMReaderAdvanced, cnsLateness: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetUserProvidedClock(self: *const T, fUserClock: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetUserProvidedClock(@ptrCast(*const IWMReaderAdvanced, self), fUserClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetUserProvidedClock(self: *const T, pfUserClock: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetUserProvidedClock(@ptrCast(*const IWMReaderAdvanced, self), pfUserClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_DeliverTime(self: *const T, cnsTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).DeliverTime(@ptrCast(*const IWMReaderAdvanced, self), cnsTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetManualStreamSelection(self: *const T, fSelection: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetManualStreamSelection(@ptrCast(*const IWMReaderAdvanced, self), fSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetManualStreamSelection(self: *const T, pfSelection: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetManualStreamSelection(@ptrCast(*const IWMReaderAdvanced, self), pfSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetStreamsSelected(self: *const T, cStreamCount: u16, pwStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetStreamsSelected(@ptrCast(*const IWMReaderAdvanced, self), cStreamCount, pwStreamNumbers, pSelections); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetStreamSelected(self: *const T, wStreamNum: u16, pSelection: ?*WMT_STREAM_SELECTION) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetStreamSelected(@ptrCast(*const IWMReaderAdvanced, self), wStreamNum, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetReceiveSelectionCallbacks(self: *const T, fGetCallbacks: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetReceiveSelectionCallbacks(@ptrCast(*const IWMReaderAdvanced, self), fGetCallbacks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetReceiveSelectionCallbacks(self: *const T, pfGetCallbacks: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetReceiveSelectionCallbacks(@ptrCast(*const IWMReaderAdvanced, self), pfGetCallbacks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetReceiveStreamSamples(self: *const T, wStreamNum: u16, fReceiveStreamSamples: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetReceiveStreamSamples(@ptrCast(*const IWMReaderAdvanced, self), wStreamNum, fReceiveStreamSamples); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetReceiveStreamSamples(self: *const T, wStreamNum: u16, pfReceiveStreamSamples: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetReceiveStreamSamples(@ptrCast(*const IWMReaderAdvanced, self), wStreamNum, pfReceiveStreamSamples); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetAllocateForOutput(self: *const T, dwOutputNum: u32, fAllocate: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetAllocateForOutput(@ptrCast(*const IWMReaderAdvanced, self), dwOutputNum, fAllocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetAllocateForOutput(self: *const T, dwOutputNum: u32, pfAllocate: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetAllocateForOutput(@ptrCast(*const IWMReaderAdvanced, self), dwOutputNum, pfAllocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetAllocateForStream(self: *const T, wStreamNum: u16, fAllocate: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetAllocateForStream(@ptrCast(*const IWMReaderAdvanced, self), wStreamNum, fAllocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetAllocateForStream(self: *const T, dwSreamNum: u16, pfAllocate: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetAllocateForStream(@ptrCast(*const IWMReaderAdvanced, self), dwSreamNum, pfAllocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetStatistics(self: *const T, pStatistics: ?*WM_READER_STATISTICS) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetStatistics(@ptrCast(*const IWMReaderAdvanced, self), pStatistics); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_SetClientInfo(self: *const T, pClientInfo: ?*WM_READER_CLIENTINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).SetClientInfo(@ptrCast(*const IWMReaderAdvanced, self), pClientInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetMaxOutputSampleSize(self: *const T, dwOutput: u32, pcbMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetMaxOutputSampleSize(@ptrCast(*const IWMReaderAdvanced, self), dwOutput, pcbMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_GetMaxStreamSampleSize(self: *const T, wStream: u16, pcbMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).GetMaxStreamSampleSize(@ptrCast(*const IWMReaderAdvanced, self), wStream, pcbMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced_NotifyLateDelivery(self: *const T, cnsLateness: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced.VTable, self.vtable).NotifyLateDelivery(@ptrCast(*const IWMReaderAdvanced, self), cnsLateness); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced2_Value = Guid.initString("ae14a945-b90c-4d0d-9127-80d665f7d73e"); pub const IID_IWMReaderAdvanced2 = &IID_IWMReaderAdvanced2_Value; pub const IWMReaderAdvanced2 = extern struct { pub const VTable = extern struct { base: IWMReaderAdvanced.VTable, SetPlayMode: fn( self: *const IWMReaderAdvanced2, Mode: WMT_PLAY_MODE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPlayMode: fn( self: *const IWMReaderAdvanced2, pMode: ?*WMT_PLAY_MODE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBufferProgress: fn( self: *const IWMReaderAdvanced2, pdwPercent: ?*u32, pcnsBuffering: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDownloadProgress: fn( self: *const IWMReaderAdvanced2, pdwPercent: ?*u32, pqwBytesDownloaded: ?*u64, pcnsDownload: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSaveAsProgress: fn( self: *const IWMReaderAdvanced2, pdwPercent: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveFileAs: fn( self: *const IWMReaderAdvanced2, pwszFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProtocolName: fn( self: *const IWMReaderAdvanced2, pwszProtocol: [*:0]u16, pcchProtocol: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartAtMarker: fn( self: *const IWMReaderAdvanced2, wMarkerIndex: u16, cnsDuration: u64, fRate: f32, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputSetting: fn( self: *const IWMReaderAdvanced2, dwOutputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputSetting: fn( self: *const IWMReaderAdvanced2, dwOutputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Preroll: fn( self: *const IWMReaderAdvanced2, cnsStart: u64, cnsDuration: u64, fRate: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLogClientID: fn( self: *const IWMReaderAdvanced2, fLogClientID: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLogClientID: fn( self: *const IWMReaderAdvanced2, pfLogClientID: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopBuffering: fn( self: *const IWMReaderAdvanced2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenStream: fn( self: *const IWMReaderAdvanced2, pStream: ?*IStream, pCallback: ?*IWMReaderCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderAdvanced.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_SetPlayMode(self: *const T, Mode: WMT_PLAY_MODE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).SetPlayMode(@ptrCast(*const IWMReaderAdvanced2, self), Mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetPlayMode(self: *const T, pMode: ?*WMT_PLAY_MODE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetPlayMode(@ptrCast(*const IWMReaderAdvanced2, self), pMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetBufferProgress(self: *const T, pdwPercent: ?*u32, pcnsBuffering: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetBufferProgress(@ptrCast(*const IWMReaderAdvanced2, self), pdwPercent, pcnsBuffering); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetDownloadProgress(self: *const T, pdwPercent: ?*u32, pqwBytesDownloaded: ?*u64, pcnsDownload: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetDownloadProgress(@ptrCast(*const IWMReaderAdvanced2, self), pdwPercent, pqwBytesDownloaded, pcnsDownload); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetSaveAsProgress(self: *const T, pdwPercent: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetSaveAsProgress(@ptrCast(*const IWMReaderAdvanced2, self), pdwPercent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_SaveFileAs(self: *const T, pwszFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).SaveFileAs(@ptrCast(*const IWMReaderAdvanced2, self), pwszFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetProtocolName(self: *const T, pwszProtocol: [*:0]u16, pcchProtocol: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetProtocolName(@ptrCast(*const IWMReaderAdvanced2, self), pwszProtocol, pcchProtocol); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_StartAtMarker(self: *const T, wMarkerIndex: u16, cnsDuration: u64, fRate: f32, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).StartAtMarker(@ptrCast(*const IWMReaderAdvanced2, self), wMarkerIndex, cnsDuration, fRate, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetOutputSetting(self: *const T, dwOutputNum: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetOutputSetting(@ptrCast(*const IWMReaderAdvanced2, self), dwOutputNum, pszName, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_SetOutputSetting(self: *const T, dwOutputNum: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).SetOutputSetting(@ptrCast(*const IWMReaderAdvanced2, self), dwOutputNum, pszName, Type, pValue, cbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_Preroll(self: *const T, cnsStart: u64, cnsDuration: u64, fRate: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).Preroll(@ptrCast(*const IWMReaderAdvanced2, self), cnsStart, cnsDuration, fRate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_SetLogClientID(self: *const T, fLogClientID: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).SetLogClientID(@ptrCast(*const IWMReaderAdvanced2, self), fLogClientID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_GetLogClientID(self: *const T, pfLogClientID: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).GetLogClientID(@ptrCast(*const IWMReaderAdvanced2, self), pfLogClientID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_StopBuffering(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).StopBuffering(@ptrCast(*const IWMReaderAdvanced2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced2_OpenStream(self: *const T, pStream: ?*IStream, pCallback: ?*IWMReaderCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced2.VTable, self.vtable).OpenStream(@ptrCast(*const IWMReaderAdvanced2, self), pStream, pCallback, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced3_Value = Guid.initString("5dc0674b-f04b-4a4e-9f2a-b1afde2c8100"); pub const IID_IWMReaderAdvanced3 = &IID_IWMReaderAdvanced3_Value; pub const IWMReaderAdvanced3 = extern struct { pub const VTable = extern struct { base: IWMReaderAdvanced2.VTable, StopNetStreaming: fn( self: *const IWMReaderAdvanced3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartAtPosition: fn( self: *const IWMReaderAdvanced3, wStreamNum: u16, pvOffsetStart: ?*anyopaque, pvDuration: ?*anyopaque, dwOffsetFormat: WMT_OFFSET_FORMAT, fRate: f32, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderAdvanced2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced3_StopNetStreaming(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced3.VTable, self.vtable).StopNetStreaming(@ptrCast(*const IWMReaderAdvanced3, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced3_StartAtPosition(self: *const T, wStreamNum: u16, pvOffsetStart: ?*anyopaque, pvDuration: ?*anyopaque, dwOffsetFormat: WMT_OFFSET_FORMAT, fRate: f32, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced3.VTable, self.vtable).StartAtPosition(@ptrCast(*const IWMReaderAdvanced3, self), wStreamNum, pvOffsetStart, pvDuration, dwOffsetFormat, fRate, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced4_Value = Guid.initString("945a76a2-12ae-4d48-bd3c-cd1d90399b85"); pub const IID_IWMReaderAdvanced4 = &IID_IWMReaderAdvanced4_Value; pub const IWMReaderAdvanced4 = extern struct { pub const VTable = extern struct { base: IWMReaderAdvanced3.VTable, GetLanguageCount: fn( self: *const IWMReaderAdvanced4, dwOutputNum: u32, pwLanguageCount: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguage: fn( self: *const IWMReaderAdvanced4, dwOutputNum: u32, wLanguage: u16, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxSpeedFactor: fn( self: *const IWMReaderAdvanced4, pdblFactor: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUsingFastCache: fn( self: *const IWMReaderAdvanced4, pfUsingFastCache: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddLogParam: fn( self: *const IWMReaderAdvanced4, wszNameSpace: ?[*:0]const u16, wszName: ?[*:0]const u16, wszValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendLogParams: fn( self: *const IWMReaderAdvanced4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CanSaveFileAs: fn( self: *const IWMReaderAdvanced4, pfCanSave: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelSaveFileAs: fn( self: *const IWMReaderAdvanced4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetURL: fn( self: *const IWMReaderAdvanced4, pwszURL: [*:0]u16, pcchURL: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderAdvanced3.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_GetLanguageCount(self: *const T, dwOutputNum: u32, pwLanguageCount: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).GetLanguageCount(@ptrCast(*const IWMReaderAdvanced4, self), dwOutputNum, pwLanguageCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_GetLanguage(self: *const T, dwOutputNum: u32, wLanguage: u16, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).GetLanguage(@ptrCast(*const IWMReaderAdvanced4, self), dwOutputNum, wLanguage, pwszLanguageString, pcchLanguageStringLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_GetMaxSpeedFactor(self: *const T, pdblFactor: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).GetMaxSpeedFactor(@ptrCast(*const IWMReaderAdvanced4, self), pdblFactor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_IsUsingFastCache(self: *const T, pfUsingFastCache: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).IsUsingFastCache(@ptrCast(*const IWMReaderAdvanced4, self), pfUsingFastCache); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_AddLogParam(self: *const T, wszNameSpace: ?[*:0]const u16, wszName: ?[*:0]const u16, wszValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).AddLogParam(@ptrCast(*const IWMReaderAdvanced4, self), wszNameSpace, wszName, wszValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_SendLogParams(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).SendLogParams(@ptrCast(*const IWMReaderAdvanced4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_CanSaveFileAs(self: *const T, pfCanSave: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).CanSaveFileAs(@ptrCast(*const IWMReaderAdvanced4, self), pfCanSave); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_CancelSaveFileAs(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).CancelSaveFileAs(@ptrCast(*const IWMReaderAdvanced4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced4_GetURL(self: *const T, pwszURL: [*:0]u16, pcchURL: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced4.VTable, self.vtable).GetURL(@ptrCast(*const IWMReaderAdvanced4, self), pwszURL, pcchURL); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced5_Value = Guid.initString("24c44db0-55d1-49ae-a5cc-f13815e36363"); pub const IID_IWMReaderAdvanced5 = &IID_IWMReaderAdvanced5_Value; pub const IWMReaderAdvanced5 = extern struct { pub const VTable = extern struct { base: IWMReaderAdvanced4.VTable, SetPlayerHook: fn( self: *const IWMReaderAdvanced5, dwOutputNum: u32, pHook: ?*IWMPlayerHook, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderAdvanced4.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced5_SetPlayerHook(self: *const T, dwOutputNum: u32, pHook: ?*IWMPlayerHook) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced5.VTable, self.vtable).SetPlayerHook(@ptrCast(*const IWMReaderAdvanced5, self), dwOutputNum, pHook); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAdvanced6_Value = Guid.initString("18a2e7f8-428f-4acd-8a00-e64639bc93de"); pub const IID_IWMReaderAdvanced6 = &IID_IWMReaderAdvanced6_Value; pub const IWMReaderAdvanced6 = extern struct { pub const VTable = extern struct { base: IWMReaderAdvanced5.VTable, SetProtectStreamSamples: fn( self: *const IWMReaderAdvanced6, pbCertificate: [*:0]u8, cbCertificate: u32, dwCertificateType: u32, dwFlags: u32, pbInitializationVector: [*:0]u8, pcbInitializationVector: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderAdvanced5.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAdvanced6_SetProtectStreamSamples(self: *const T, pbCertificate: [*:0]u8, cbCertificate: u32, dwCertificateType: u32, dwFlags: u32, pbInitializationVector: [*:0]u8, pcbInitializationVector: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAdvanced6.VTable, self.vtable).SetProtectStreamSamples(@ptrCast(*const IWMReaderAdvanced6, self), pbCertificate, cbCertificate, dwCertificateType, dwFlags, pbInitializationVector, pcbInitializationVector); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMPlayerHook_Value = Guid.initString("e5b7ca9a-0f1c-4f66-9002-74ec50d8b304"); pub const IID_IWMPlayerHook = &IID_IWMPlayerHook_Value; pub const IWMPlayerHook = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, PreDecode: fn( self: *const IWMPlayerHook, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPlayerHook_PreDecode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPlayerHook.VTable, self.vtable).PreDecode(@ptrCast(*const IWMPlayerHook, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAllocatorEx_Value = Guid.initString("9f762fa7-a22e-428d-93c9-ac82f3aafe5a"); pub const IID_IWMReaderAllocatorEx = &IID_IWMReaderAllocatorEx_Value; pub const IWMReaderAllocatorEx = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AllocateForStreamEx: fn( self: *const IWMReaderAllocatorEx, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, dwFlags: u32, cnsSampleTime: u64, cnsSampleDuration: u64, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateForOutputEx: fn( self: *const IWMReaderAllocatorEx, dwOutputNum: u32, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, dwFlags: u32, cnsSampleTime: u64, cnsSampleDuration: u64, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAllocatorEx_AllocateForStreamEx(self: *const T, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, dwFlags: u32, cnsSampleTime: u64, cnsSampleDuration: u64, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAllocatorEx.VTable, self.vtable).AllocateForStreamEx(@ptrCast(*const IWMReaderAllocatorEx, self), wStreamNum, cbBuffer, ppBuffer, dwFlags, cnsSampleTime, cnsSampleDuration, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAllocatorEx_AllocateForOutputEx(self: *const T, dwOutputNum: u32, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, dwFlags: u32, cnsSampleTime: u64, cnsSampleDuration: u64, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAllocatorEx.VTable, self.vtable).AllocateForOutputEx(@ptrCast(*const IWMReaderAllocatorEx, self), dwOutputNum, cbBuffer, ppBuffer, dwFlags, cnsSampleTime, cnsSampleDuration, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderTypeNegotiation_Value = Guid.initString("fdbe5592-81a1-41ea-93bd-735cad1adc05"); pub const IID_IWMReaderTypeNegotiation = &IID_IWMReaderTypeNegotiation_Value; pub const IWMReaderTypeNegotiation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, TryOutputProps: fn( self: *const IWMReaderTypeNegotiation, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderTypeNegotiation_TryOutputProps(self: *const T, dwOutputNum: u32, pOutput: ?*IWMOutputMediaProps) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderTypeNegotiation.VTable, self.vtable).TryOutputProps(@ptrCast(*const IWMReaderTypeNegotiation, self), dwOutputNum, pOutput); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderCallbackAdvanced_Value = Guid.initString("96406beb-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReaderCallbackAdvanced = &IID_IWMReaderCallbackAdvanced_Value; pub const IWMReaderCallbackAdvanced = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStreamSample: fn( self: *const IWMReaderCallbackAdvanced, wStreamNum: u16, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTime: fn( self: *const IWMReaderCallbackAdvanced, cnsCurrentTime: u64, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStreamSelection: fn( self: *const IWMReaderCallbackAdvanced, wStreamCount: u16, pStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnOutputPropsChanged: fn( self: *const IWMReaderCallbackAdvanced, dwOutputNum: u32, pMediaType: ?*WM_MEDIA_TYPE, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateForStream: fn( self: *const IWMReaderCallbackAdvanced, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateForOutput: fn( self: *const IWMReaderCallbackAdvanced, dwOutputNum: u32, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_OnStreamSample(self: *const T, wStreamNum: u16, cnsSampleTime: u64, cnsSampleDuration: u64, dwFlags: u32, pSample: ?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).OnStreamSample(@ptrCast(*const IWMReaderCallbackAdvanced, self), wStreamNum, cnsSampleTime, cnsSampleDuration, dwFlags, pSample, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_OnTime(self: *const T, cnsCurrentTime: u64, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).OnTime(@ptrCast(*const IWMReaderCallbackAdvanced, self), cnsCurrentTime, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_OnStreamSelection(self: *const T, wStreamCount: u16, pStreamNumbers: ?*u16, pSelections: ?*WMT_STREAM_SELECTION, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).OnStreamSelection(@ptrCast(*const IWMReaderCallbackAdvanced, self), wStreamCount, pStreamNumbers, pSelections, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_OnOutputPropsChanged(self: *const T, dwOutputNum: u32, pMediaType: ?*WM_MEDIA_TYPE, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).OnOutputPropsChanged(@ptrCast(*const IWMReaderCallbackAdvanced, self), dwOutputNum, pMediaType, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_AllocateForStream(self: *const T, wStreamNum: u16, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).AllocateForStream(@ptrCast(*const IWMReaderCallbackAdvanced, self), wStreamNum, cbBuffer, ppBuffer, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderCallbackAdvanced_AllocateForOutput(self: *const T, dwOutputNum: u32, cbBuffer: u32, ppBuffer: ?*?*INSSBuffer, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderCallbackAdvanced.VTable, self.vtable).AllocateForOutput(@ptrCast(*const IWMReaderCallbackAdvanced, self), dwOutputNum, cbBuffer, ppBuffer, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMDRMReader_Value = Guid.initString("d2827540-3ee7-432c-b14c-dc17f085d3b3"); pub const IID_IWMDRMReader = &IID_IWMDRMReader_Value; pub const IWMDRMReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AcquireLicense: fn( self: *const IWMDRMReader, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelLicenseAcquisition: fn( self: *const IWMDRMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Individualize: fn( self: *const IWMDRMReader, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelIndividualization: fn( self: *const IWMDRMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MonitorLicenseAcquisition: fn( self: *const IWMDRMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelMonitorLicenseAcquisition: fn( self: *const IWMDRMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDRMProperty: fn( self: *const IWMDRMReader, pwstrName: ?[*:0]const u16, dwType: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDRMProperty: fn( self: *const IWMDRMReader, pwstrName: ?[*:0]const u16, pdwType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_AcquireLicense(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).AcquireLicense(@ptrCast(*const IWMDRMReader, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_CancelLicenseAcquisition(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).CancelLicenseAcquisition(@ptrCast(*const IWMDRMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_Individualize(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).Individualize(@ptrCast(*const IWMDRMReader, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_CancelIndividualization(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).CancelIndividualization(@ptrCast(*const IWMDRMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_MonitorLicenseAcquisition(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).MonitorLicenseAcquisition(@ptrCast(*const IWMDRMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_CancelMonitorLicenseAcquisition(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).CancelMonitorLicenseAcquisition(@ptrCast(*const IWMDRMReader, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_SetDRMProperty(self: *const T, pwstrName: ?[*:0]const u16, dwType: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).SetDRMProperty(@ptrCast(*const IWMDRMReader, self), pwstrName, dwType, pValue, cbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader_GetDRMProperty(self: *const T, pwstrName: ?[*:0]const u16, pdwType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader.VTable, self.vtable).GetDRMProperty(@ptrCast(*const IWMDRMReader, self), pwstrName, pdwType, pValue, pcbLength); } };} pub usingnamespace MethodMixin(@This()); }; pub const DRM_MINIMUM_OUTPUT_PROTECTION_LEVELS = extern struct { wCompressedDigitalVideo: u16, wUncompressedDigitalVideo: u16, wAnalogVideo: u16, wCompressedDigitalAudio: u16, wUncompressedDigitalAudio: u16, }; pub const DRM_OPL_OUTPUT_IDS = extern struct { cIds: u16, rgIds: ?*Guid, }; pub const DRM_OUTPUT_PROTECTION = extern struct { guidId: Guid, bConfigData: u8, }; pub const DRM_VIDEO_OUTPUT_PROTECTION_IDS = extern struct { cEntries: u16, rgVop: ?*DRM_OUTPUT_PROTECTION, }; pub const DRM_PLAY_OPL = extern struct { minOPL: DRM_MINIMUM_OUTPUT_PROTECTION_LEVELS, oplIdReserved: DRM_OPL_OUTPUT_IDS, vopi: DRM_VIDEO_OUTPUT_PROTECTION_IDS, }; pub const DRM_COPY_OPL = extern struct { wMinimumCopyLevel: u16, oplIdIncludes: DRM_OPL_OUTPUT_IDS, oplIdExcludes: DRM_OPL_OUTPUT_IDS, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMReader2_Value = Guid.initString("befe7a75-9f1d-4075-b9d9-a3c37bda49a0"); pub const IID_IWMDRMReader2 = &IID_IWMDRMReader2_Value; pub const IWMDRMReader2 = extern struct { pub const VTable = extern struct { base: IWMDRMReader.VTable, SetEvaluateOutputLevelLicenses: fn( self: *const IWMDRMReader2, fEvaluate: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPlayOutputLevels: fn( self: *const IWMDRMReader2, pPlayOPL: [*]DRM_PLAY_OPL, pcbLength: ?*u32, pdwMinAppComplianceLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCopyOutputLevels: fn( self: *const IWMDRMReader2, pCopyOPL: [*]DRM_COPY_OPL, pcbLength: ?*u32, pdwMinAppComplianceLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TryNextLicense: fn( self: *const IWMDRMReader2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMDRMReader.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader2_SetEvaluateOutputLevelLicenses(self: *const T, fEvaluate: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader2.VTable, self.vtable).SetEvaluateOutputLevelLicenses(@ptrCast(*const IWMDRMReader2, self), fEvaluate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader2_GetPlayOutputLevels(self: *const T, pPlayOPL: [*]DRM_PLAY_OPL, pcbLength: ?*u32, pdwMinAppComplianceLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader2.VTable, self.vtable).GetPlayOutputLevels(@ptrCast(*const IWMDRMReader2, self), pPlayOPL, pcbLength, pdwMinAppComplianceLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader2_GetCopyOutputLevels(self: *const T, pCopyOPL: [*]DRM_COPY_OPL, pcbLength: ?*u32, pdwMinAppComplianceLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader2.VTable, self.vtable).GetCopyOutputLevels(@ptrCast(*const IWMDRMReader2, self), pCopyOPL, pcbLength, pdwMinAppComplianceLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader2_TryNextLicense(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader2.VTable, self.vtable).TryNextLicense(@ptrCast(*const IWMDRMReader2, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMReader3_Value = Guid.initString("e08672de-f1e7-4ff4-a0a3-fc4b08e4caf8"); pub const IID_IWMDRMReader3 = &IID_IWMDRMReader3_Value; pub const IWMDRMReader3 = extern struct { pub const VTable = extern struct { base: IWMDRMReader2.VTable, GetInclusionList: fn( self: *const IWMDRMReader3, ppGuids: ?*?*Guid, pcGuids: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMDRMReader2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMReader3_GetInclusionList(self: *const T, ppGuids: ?*?*Guid, pcGuids: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMReader3.VTable, self.vtable).GetInclusionList(@ptrCast(*const IWMDRMReader3, self), ppGuids, pcGuids); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderPlaylistBurn_Value = Guid.initString("f28c0300-9baa-4477-a846-1744d9cbf533"); pub const IID_IWMReaderPlaylistBurn = &IID_IWMReaderPlaylistBurn_Value; pub const IWMReaderPlaylistBurn = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitPlaylistBurn: fn( self: *const IWMReaderPlaylistBurn, cFiles: u32, ppwszFilenames: ?*?PWSTR, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInitResults: fn( self: *const IWMReaderPlaylistBurn, cFiles: u32, phrStati: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const IWMReaderPlaylistBurn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndPlaylistBurn: fn( self: *const IWMReaderPlaylistBurn, hrBurnResult: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderPlaylistBurn_InitPlaylistBurn(self: *const T, cFiles: u32, ppwszFilenames: ?*?PWSTR, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderPlaylistBurn.VTable, self.vtable).InitPlaylistBurn(@ptrCast(*const IWMReaderPlaylistBurn, self), cFiles, ppwszFilenames, pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderPlaylistBurn_GetInitResults(self: *const T, cFiles: u32, phrStati: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderPlaylistBurn.VTable, self.vtable).GetInitResults(@ptrCast(*const IWMReaderPlaylistBurn, self), cFiles, phrStati); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderPlaylistBurn_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderPlaylistBurn.VTable, self.vtable).Cancel(@ptrCast(*const IWMReaderPlaylistBurn, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderPlaylistBurn_EndPlaylistBurn(self: *const T, hrBurnResult: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderPlaylistBurn.VTable, self.vtable).EndPlaylistBurn(@ptrCast(*const IWMReaderPlaylistBurn, self), hrBurnResult); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderNetworkConfig_Value = Guid.initString("96406bec-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReaderNetworkConfig = &IID_IWMReaderNetworkConfig_Value; pub const IWMReaderNetworkConfig = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetBufferingTime: fn( self: *const IWMReaderNetworkConfig, pcnsBufferingTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBufferingTime: fn( self: *const IWMReaderNetworkConfig, cnsBufferingTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUDPPortRanges: fn( self: *const IWMReaderNetworkConfig, pRangeArray: [*]WM_PORT_NUMBER_RANGE, pcRanges: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUDPPortRanges: fn( self: *const IWMReaderNetworkConfig, pRangeArray: [*]WM_PORT_NUMBER_RANGE, cRanges: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProxySettings: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pProxySetting: ?*WMT_PROXY_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProxySettings: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, ProxySetting: WMT_PROXY_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProxyHostName: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pwszHostName: [*:0]u16, pcchHostName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProxyHostName: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pwszHostName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProxyPort: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pdwPort: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProxyPort: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, dwPort: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProxyExceptionList: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pwszExceptionList: [*:0]u16, pcchExceptionList: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProxyExceptionList: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pwszExceptionList: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProxyBypassForLocal: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, pfBypassForLocal: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProxyBypassForLocal: fn( self: *const IWMReaderNetworkConfig, pwszProtocol: ?[*:0]const u16, fBypassForLocal: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetForceRerunAutoProxyDetection: fn( self: *const IWMReaderNetworkConfig, pfForceRerunDetection: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetForceRerunAutoProxyDetection: fn( self: *const IWMReaderNetworkConfig, fForceRerunDetection: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableMulticast: fn( self: *const IWMReaderNetworkConfig, pfEnableMulticast: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableMulticast: fn( self: *const IWMReaderNetworkConfig, fEnableMulticast: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableHTTP: fn( self: *const IWMReaderNetworkConfig, pfEnableHTTP: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableHTTP: fn( self: *const IWMReaderNetworkConfig, fEnableHTTP: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableUDP: fn( self: *const IWMReaderNetworkConfig, pfEnableUDP: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableUDP: fn( self: *const IWMReaderNetworkConfig, fEnableUDP: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableTCP: fn( self: *const IWMReaderNetworkConfig, pfEnableTCP: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableTCP: fn( self: *const IWMReaderNetworkConfig, fEnableTCP: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResetProtocolRollover: fn( self: *const IWMReaderNetworkConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectionBandwidth: fn( self: *const IWMReaderNetworkConfig, pdwConnectionBandwidth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConnectionBandwidth: fn( self: *const IWMReaderNetworkConfig, dwConnectionBandwidth: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumProtocolsSupported: fn( self: *const IWMReaderNetworkConfig, pcProtocols: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSupportedProtocolName: fn( self: *const IWMReaderNetworkConfig, dwProtocolNum: u32, pwszProtocolName: [*:0]u16, pcchProtocolName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddLoggingUrl: fn( self: *const IWMReaderNetworkConfig, pwszUrl: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLoggingUrl: fn( self: *const IWMReaderNetworkConfig, dwIndex: u32, pwszUrl: [*:0]u16, pcchUrl: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLoggingUrlCount: fn( self: *const IWMReaderNetworkConfig, pdwUrlCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResetLoggingUrlList: fn( self: *const IWMReaderNetworkConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetBufferingTime(self: *const T, pcnsBufferingTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetBufferingTime(@ptrCast(*const IWMReaderNetworkConfig, self), pcnsBufferingTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetBufferingTime(self: *const T, cnsBufferingTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetBufferingTime(@ptrCast(*const IWMReaderNetworkConfig, self), cnsBufferingTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetUDPPortRanges(self: *const T, pRangeArray: [*]WM_PORT_NUMBER_RANGE, pcRanges: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetUDPPortRanges(@ptrCast(*const IWMReaderNetworkConfig, self), pRangeArray, pcRanges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetUDPPortRanges(self: *const T, pRangeArray: [*]WM_PORT_NUMBER_RANGE, cRanges: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetUDPPortRanges(@ptrCast(*const IWMReaderNetworkConfig, self), pRangeArray, cRanges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetProxySettings(self: *const T, pwszProtocol: ?[*:0]const u16, pProxySetting: ?*WMT_PROXY_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetProxySettings(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pProxySetting); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetProxySettings(self: *const T, pwszProtocol: ?[*:0]const u16, ProxySetting: WMT_PROXY_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetProxySettings(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, ProxySetting); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetProxyHostName(self: *const T, pwszProtocol: ?[*:0]const u16, pwszHostName: [*:0]u16, pcchHostName: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetProxyHostName(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pwszHostName, pcchHostName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetProxyHostName(self: *const T, pwszProtocol: ?[*:0]const u16, pwszHostName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetProxyHostName(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pwszHostName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetProxyPort(self: *const T, pwszProtocol: ?[*:0]const u16, pdwPort: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetProxyPort(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pdwPort); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetProxyPort(self: *const T, pwszProtocol: ?[*:0]const u16, dwPort: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetProxyPort(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, dwPort); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetProxyExceptionList(self: *const T, pwszProtocol: ?[*:0]const u16, pwszExceptionList: [*:0]u16, pcchExceptionList: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetProxyExceptionList(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pwszExceptionList, pcchExceptionList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetProxyExceptionList(self: *const T, pwszProtocol: ?[*:0]const u16, pwszExceptionList: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetProxyExceptionList(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pwszExceptionList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetProxyBypassForLocal(self: *const T, pwszProtocol: ?[*:0]const u16, pfBypassForLocal: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetProxyBypassForLocal(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, pfBypassForLocal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetProxyBypassForLocal(self: *const T, pwszProtocol: ?[*:0]const u16, fBypassForLocal: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetProxyBypassForLocal(@ptrCast(*const IWMReaderNetworkConfig, self), pwszProtocol, fBypassForLocal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetForceRerunAutoProxyDetection(self: *const T, pfForceRerunDetection: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetForceRerunAutoProxyDetection(@ptrCast(*const IWMReaderNetworkConfig, self), pfForceRerunDetection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetForceRerunAutoProxyDetection(self: *const T, fForceRerunDetection: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetForceRerunAutoProxyDetection(@ptrCast(*const IWMReaderNetworkConfig, self), fForceRerunDetection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetEnableMulticast(self: *const T, pfEnableMulticast: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetEnableMulticast(@ptrCast(*const IWMReaderNetworkConfig, self), pfEnableMulticast); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetEnableMulticast(self: *const T, fEnableMulticast: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetEnableMulticast(@ptrCast(*const IWMReaderNetworkConfig, self), fEnableMulticast); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetEnableHTTP(self: *const T, pfEnableHTTP: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetEnableHTTP(@ptrCast(*const IWMReaderNetworkConfig, self), pfEnableHTTP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetEnableHTTP(self: *const T, fEnableHTTP: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetEnableHTTP(@ptrCast(*const IWMReaderNetworkConfig, self), fEnableHTTP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetEnableUDP(self: *const T, pfEnableUDP: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetEnableUDP(@ptrCast(*const IWMReaderNetworkConfig, self), pfEnableUDP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetEnableUDP(self: *const T, fEnableUDP: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetEnableUDP(@ptrCast(*const IWMReaderNetworkConfig, self), fEnableUDP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetEnableTCP(self: *const T, pfEnableTCP: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetEnableTCP(@ptrCast(*const IWMReaderNetworkConfig, self), pfEnableTCP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetEnableTCP(self: *const T, fEnableTCP: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetEnableTCP(@ptrCast(*const IWMReaderNetworkConfig, self), fEnableTCP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_ResetProtocolRollover(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).ResetProtocolRollover(@ptrCast(*const IWMReaderNetworkConfig, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetConnectionBandwidth(self: *const T, pdwConnectionBandwidth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetConnectionBandwidth(@ptrCast(*const IWMReaderNetworkConfig, self), pdwConnectionBandwidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_SetConnectionBandwidth(self: *const T, dwConnectionBandwidth: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).SetConnectionBandwidth(@ptrCast(*const IWMReaderNetworkConfig, self), dwConnectionBandwidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetNumProtocolsSupported(self: *const T, pcProtocols: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetNumProtocolsSupported(@ptrCast(*const IWMReaderNetworkConfig, self), pcProtocols); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetSupportedProtocolName(self: *const T, dwProtocolNum: u32, pwszProtocolName: [*:0]u16, pcchProtocolName: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetSupportedProtocolName(@ptrCast(*const IWMReaderNetworkConfig, self), dwProtocolNum, pwszProtocolName, pcchProtocolName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_AddLoggingUrl(self: *const T, pwszUrl: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).AddLoggingUrl(@ptrCast(*const IWMReaderNetworkConfig, self), pwszUrl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetLoggingUrl(self: *const T, dwIndex: u32, pwszUrl: [*:0]u16, pcchUrl: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetLoggingUrl(@ptrCast(*const IWMReaderNetworkConfig, self), dwIndex, pwszUrl, pcchUrl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_GetLoggingUrlCount(self: *const T, pdwUrlCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).GetLoggingUrlCount(@ptrCast(*const IWMReaderNetworkConfig, self), pdwUrlCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig_ResetLoggingUrlList(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig.VTable, self.vtable).ResetLoggingUrlList(@ptrCast(*const IWMReaderNetworkConfig, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderNetworkConfig2_Value = Guid.initString("d979a853-042b-4050-8387-c939db22013f"); pub const IID_IWMReaderNetworkConfig2 = &IID_IWMReaderNetworkConfig2_Value; pub const IWMReaderNetworkConfig2 = extern struct { pub const VTable = extern struct { base: IWMReaderNetworkConfig.VTable, GetEnableContentCaching: fn( self: *const IWMReaderNetworkConfig2, pfEnableContentCaching: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableContentCaching: fn( self: *const IWMReaderNetworkConfig2, fEnableContentCaching: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableFastCache: fn( self: *const IWMReaderNetworkConfig2, pfEnableFastCache: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableFastCache: fn( self: *const IWMReaderNetworkConfig2, fEnableFastCache: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAcceleratedStreamingDuration: fn( self: *const IWMReaderNetworkConfig2, pcnsAccelDuration: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAcceleratedStreamingDuration: fn( self: *const IWMReaderNetworkConfig2, cnsAccelDuration: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAutoReconnectLimit: fn( self: *const IWMReaderNetworkConfig2, pdwAutoReconnectLimit: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAutoReconnectLimit: fn( self: *const IWMReaderNetworkConfig2, dwAutoReconnectLimit: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableResends: fn( self: *const IWMReaderNetworkConfig2, pfEnableResends: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableResends: fn( self: *const IWMReaderNetworkConfig2, fEnableResends: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnableThinning: fn( self: *const IWMReaderNetworkConfig2, pfEnableThinning: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnableThinning: fn( self: *const IWMReaderNetworkConfig2, fEnableThinning: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxNetPacketSize: fn( self: *const IWMReaderNetworkConfig2, pdwMaxNetPacketSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMReaderNetworkConfig.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetEnableContentCaching(self: *const T, pfEnableContentCaching: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetEnableContentCaching(@ptrCast(*const IWMReaderNetworkConfig2, self), pfEnableContentCaching); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetEnableContentCaching(self: *const T, fEnableContentCaching: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetEnableContentCaching(@ptrCast(*const IWMReaderNetworkConfig2, self), fEnableContentCaching); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetEnableFastCache(self: *const T, pfEnableFastCache: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetEnableFastCache(@ptrCast(*const IWMReaderNetworkConfig2, self), pfEnableFastCache); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetEnableFastCache(self: *const T, fEnableFastCache: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetEnableFastCache(@ptrCast(*const IWMReaderNetworkConfig2, self), fEnableFastCache); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetAcceleratedStreamingDuration(self: *const T, pcnsAccelDuration: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetAcceleratedStreamingDuration(@ptrCast(*const IWMReaderNetworkConfig2, self), pcnsAccelDuration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetAcceleratedStreamingDuration(self: *const T, cnsAccelDuration: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetAcceleratedStreamingDuration(@ptrCast(*const IWMReaderNetworkConfig2, self), cnsAccelDuration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetAutoReconnectLimit(self: *const T, pdwAutoReconnectLimit: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetAutoReconnectLimit(@ptrCast(*const IWMReaderNetworkConfig2, self), pdwAutoReconnectLimit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetAutoReconnectLimit(self: *const T, dwAutoReconnectLimit: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetAutoReconnectLimit(@ptrCast(*const IWMReaderNetworkConfig2, self), dwAutoReconnectLimit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetEnableResends(self: *const T, pfEnableResends: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetEnableResends(@ptrCast(*const IWMReaderNetworkConfig2, self), pfEnableResends); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetEnableResends(self: *const T, fEnableResends: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetEnableResends(@ptrCast(*const IWMReaderNetworkConfig2, self), fEnableResends); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetEnableThinning(self: *const T, pfEnableThinning: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetEnableThinning(@ptrCast(*const IWMReaderNetworkConfig2, self), pfEnableThinning); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_SetEnableThinning(self: *const T, fEnableThinning: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).SetEnableThinning(@ptrCast(*const IWMReaderNetworkConfig2, self), fEnableThinning); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderNetworkConfig2_GetMaxNetPacketSize(self: *const T, pdwMaxNetPacketSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderNetworkConfig2.VTable, self.vtable).GetMaxNetPacketSize(@ptrCast(*const IWMReaderNetworkConfig2, self), pdwMaxNetPacketSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderStreamClock_Value = Guid.initString("96406bed-2b2b-11d3-b36b-00c04f6108ff"); pub const IID_IWMReaderStreamClock = &IID_IWMReaderStreamClock_Value; pub const IWMReaderStreamClock = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetTime: fn( self: *const IWMReaderStreamClock, pcnsNow: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTimer: fn( self: *const IWMReaderStreamClock, cnsWhen: u64, pvParam: ?*anyopaque, pdwTimerId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, KillTimer: fn( self: *const IWMReaderStreamClock, dwTimerId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderStreamClock_GetTime(self: *const T, pcnsNow: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderStreamClock.VTable, self.vtable).GetTime(@ptrCast(*const IWMReaderStreamClock, self), pcnsNow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderStreamClock_SetTimer(self: *const T, cnsWhen: u64, pvParam: ?*anyopaque, pdwTimerId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderStreamClock.VTable, self.vtable).SetTimer(@ptrCast(*const IWMReaderStreamClock, self), cnsWhen, pvParam, pdwTimerId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderStreamClock_KillTimer(self: *const T, dwTimerId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderStreamClock.VTable, self.vtable).KillTimer(@ptrCast(*const IWMReaderStreamClock, self), dwTimerId); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMIndexer_Value = Guid.initString("6d7cdc71-9888-11d3-8edc-00c04f6109cf"); pub const IID_IWMIndexer = &IID_IWMIndexer_Value; pub const IWMIndexer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartIndexing: fn( self: *const IWMIndexer, pwszURL: ?[*:0]const u16, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const IWMIndexer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMIndexer_StartIndexing(self: *const T, pwszURL: ?[*:0]const u16, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMIndexer.VTable, self.vtable).StartIndexing(@ptrCast(*const IWMIndexer, self), pwszURL, pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMIndexer_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMIndexer.VTable, self.vtable).Cancel(@ptrCast(*const IWMIndexer, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMIndexer2_Value = Guid.initString("b70f1e42-6255-4df0-a6b9-02b212d9e2bb"); pub const IID_IWMIndexer2 = &IID_IWMIndexer2_Value; pub const IWMIndexer2 = extern struct { pub const VTable = extern struct { base: IWMIndexer.VTable, Configure: fn( self: *const IWMIndexer2, wStreamNum: u16, nIndexerType: WMT_INDEXER_TYPE, pvInterval: ?*anyopaque, pvIndexType: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMIndexer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMIndexer2_Configure(self: *const T, wStreamNum: u16, nIndexerType: WMT_INDEXER_TYPE, pvInterval: ?*anyopaque, pvIndexType: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMIndexer2.VTable, self.vtable).Configure(@ptrCast(*const IWMIndexer2, self), wStreamNum, nIndexerType, pvInterval, pvIndexType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMLicenseBackup_Value = Guid.initString("05e5ac9f-3fb6-4508-bb43-a4067ba1ebe8"); pub const IID_IWMLicenseBackup = &IID_IWMLicenseBackup_Value; pub const IWMLicenseBackup = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, BackupLicenses: fn( self: *const IWMLicenseBackup, dwFlags: u32, pCallback: ?*IWMStatusCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelLicenseBackup: fn( self: *const IWMLicenseBackup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseBackup_BackupLicenses(self: *const T, dwFlags: u32, pCallback: ?*IWMStatusCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseBackup.VTable, self.vtable).BackupLicenses(@ptrCast(*const IWMLicenseBackup, self), dwFlags, pCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseBackup_CancelLicenseBackup(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseBackup.VTable, self.vtable).CancelLicenseBackup(@ptrCast(*const IWMLicenseBackup, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMLicenseRestore_Value = Guid.initString("c70b6334-a22e-4efb-a245-15e65a004a13"); pub const IID_IWMLicenseRestore = &IID_IWMLicenseRestore_Value; pub const IWMLicenseRestore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RestoreLicenses: fn( self: *const IWMLicenseRestore, dwFlags: u32, pCallback: ?*IWMStatusCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelLicenseRestore: fn( self: *const IWMLicenseRestore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseRestore_RestoreLicenses(self: *const T, dwFlags: u32, pCallback: ?*IWMStatusCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseRestore.VTable, self.vtable).RestoreLicenses(@ptrCast(*const IWMLicenseRestore, self), dwFlags, pCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseRestore_CancelLicenseRestore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseRestore.VTable, self.vtable).CancelLicenseRestore(@ptrCast(*const IWMLicenseRestore, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMBackupRestoreProps_Value = Guid.initString("3c8e0da6-996f-4ff3-a1af-4838f9377e2e"); pub const IID_IWMBackupRestoreProps = &IID_IWMBackupRestoreProps_Value; pub const IWMBackupRestoreProps = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPropCount: fn( self: *const IWMBackupRestoreProps, pcProps: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropByIndex: fn( self: *const IWMBackupRestoreProps, wIndex: u16, pwszName: [*:0]u16, pcchNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropByName: fn( self: *const IWMBackupRestoreProps, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProp: fn( self: *const IWMBackupRestoreProps, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveProp: fn( self: *const IWMBackupRestoreProps, pcwszName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAllProps: fn( self: *const IWMBackupRestoreProps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_GetPropCount(self: *const T, pcProps: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).GetPropCount(@ptrCast(*const IWMBackupRestoreProps, self), pcProps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_GetPropByIndex(self: *const T, wIndex: u16, pwszName: [*:0]u16, pcchNameLen: ?*u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).GetPropByIndex(@ptrCast(*const IWMBackupRestoreProps, self), wIndex, pwszName, pcchNameLen, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_GetPropByName(self: *const T, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pcbLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).GetPropByName(@ptrCast(*const IWMBackupRestoreProps, self), pszName, pType, pValue, pcbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_SetProp(self: *const T, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, cbLength: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).SetProp(@ptrCast(*const IWMBackupRestoreProps, self), pszName, Type, pValue, cbLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_RemoveProp(self: *const T, pcwszName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).RemoveProp(@ptrCast(*const IWMBackupRestoreProps, self), pcwszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMBackupRestoreProps_RemoveAllProps(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMBackupRestoreProps.VTable, self.vtable).RemoveAllProps(@ptrCast(*const IWMBackupRestoreProps, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCodecInfo_Value = Guid.initString("a970f41e-34de-4a98-b3ba-e4b3ca7528f0"); pub const IID_IWMCodecInfo = &IID_IWMCodecInfo_Value; pub const IWMCodecInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCodecInfoCount: fn( self: *const IWMCodecInfo, guidType: ?*const Guid, pcCodecs: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecFormatCount: fn( self: *const IWMCodecInfo, guidType: ?*const Guid, dwCodecIndex: u32, pcFormat: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecFormat: fn( self: *const IWMCodecInfo, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, ppIStreamConfig: ?*?*IWMStreamConfig, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo_GetCodecInfoCount(self: *const T, guidType: ?*const Guid, pcCodecs: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo.VTable, self.vtable).GetCodecInfoCount(@ptrCast(*const IWMCodecInfo, self), guidType, pcCodecs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo_GetCodecFormatCount(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, pcFormat: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo.VTable, self.vtable).GetCodecFormatCount(@ptrCast(*const IWMCodecInfo, self), guidType, dwCodecIndex, pcFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo_GetCodecFormat(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, ppIStreamConfig: ?*?*IWMStreamConfig) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo.VTable, self.vtable).GetCodecFormat(@ptrCast(*const IWMCodecInfo, self), guidType, dwCodecIndex, dwFormatIndex, ppIStreamConfig); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCodecInfo2_Value = Guid.initString("aa65e273-b686-4056-91ec-dd768d4df710"); pub const IID_IWMCodecInfo2 = &IID_IWMCodecInfo2_Value; pub const IWMCodecInfo2 = extern struct { pub const VTable = extern struct { base: IWMCodecInfo.VTable, GetCodecName: fn( self: *const IWMCodecInfo2, guidType: ?*const Guid, dwCodecIndex: u32, wszName: [*:0]u16, pcchName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecFormatDesc: fn( self: *const IWMCodecInfo2, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, ppIStreamConfig: ?*?*IWMStreamConfig, wszDesc: [*:0]u16, pcchDesc: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMCodecInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo2_GetCodecName(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, wszName: [*:0]u16, pcchName: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo2.VTable, self.vtable).GetCodecName(@ptrCast(*const IWMCodecInfo2, self), guidType, dwCodecIndex, wszName, pcchName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo2_GetCodecFormatDesc(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, ppIStreamConfig: ?*?*IWMStreamConfig, wszDesc: [*:0]u16, pcchDesc: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo2.VTable, self.vtable).GetCodecFormatDesc(@ptrCast(*const IWMCodecInfo2, self), guidType, dwCodecIndex, dwFormatIndex, ppIStreamConfig, wszDesc, pcchDesc); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCodecInfo3_Value = Guid.initString("7e51f487-4d93-4f98-8ab4-27d0565adc51"); pub const IID_IWMCodecInfo3 = &IID_IWMCodecInfo3_Value; pub const IWMCodecInfo3 = extern struct { pub const VTable = extern struct { base: IWMCodecInfo2.VTable, GetCodecFormatProp: fn( self: *const IWMCodecInfo3, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecProp: fn( self: *const IWMCodecInfo3, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCodecEnumerationSetting: fn( self: *const IWMCodecInfo3, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, dwSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCodecEnumerationSetting: fn( self: *const IWMCodecInfo3, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMCodecInfo2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo3_GetCodecFormatProp(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, dwFormatIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo3.VTable, self.vtable).GetCodecFormatProp(@ptrCast(*const IWMCodecInfo3, self), guidType, dwCodecIndex, dwFormatIndex, pszName, pType, pValue, pdwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo3_GetCodecProp(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo3.VTable, self.vtable).GetCodecProp(@ptrCast(*const IWMCodecInfo3, self), guidType, dwCodecIndex, pszName, pType, pValue, pdwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo3_SetCodecEnumerationSetting(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, Type: WMT_ATTR_DATATYPE, pValue: [*:0]const u8, dwSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo3.VTable, self.vtable).SetCodecEnumerationSetting(@ptrCast(*const IWMCodecInfo3, self), guidType, dwCodecIndex, pszName, Type, pValue, dwSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecInfo3_GetCodecEnumerationSetting(self: *const T, guidType: ?*const Guid, dwCodecIndex: u32, pszName: ?[*:0]const u16, pType: ?*WMT_ATTR_DATATYPE, pValue: [*:0]u8, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecInfo3.VTable, self.vtable).GetCodecEnumerationSetting(@ptrCast(*const IWMCodecInfo3, self), guidType, dwCodecIndex, pszName, pType, pValue, pdwSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMLanguageList_Value = Guid.initString("df683f00-2d49-4d8e-92b7-fb19f6a0dc57"); pub const IID_IWMLanguageList = &IID_IWMLanguageList_Value; pub const IWMLanguageList = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLanguageCount: fn( self: *const IWMLanguageList, pwCount: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguageDetails: fn( self: *const IWMLanguageList, wIndex: u16, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddLanguageByRFC1766String: fn( self: *const IWMLanguageList, pwszLanguageString: ?PWSTR, pwIndex: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLanguageList_GetLanguageCount(self: *const T, pwCount: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLanguageList.VTable, self.vtable).GetLanguageCount(@ptrCast(*const IWMLanguageList, self), pwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLanguageList_GetLanguageDetails(self: *const T, wIndex: u16, pwszLanguageString: [*:0]u16, pcchLanguageStringLength: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLanguageList.VTable, self.vtable).GetLanguageDetails(@ptrCast(*const IWMLanguageList, self), wIndex, pwszLanguageString, pcchLanguageStringLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLanguageList_AddLanguageByRFC1766String(self: *const T, pwszLanguageString: ?PWSTR, pwIndex: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLanguageList.VTable, self.vtable).AddLanguageByRFC1766String(@ptrCast(*const IWMLanguageList, self), pwszLanguageString, pwIndex); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWriterPushSink_Value = Guid.initString("dc10e6a5-072c-467d-bf57-6330a9dde12a"); pub const IID_IWMWriterPushSink = &IID_IWMWriterPushSink_Value; pub const IWMWriterPushSink = extern struct { pub const VTable = extern struct { base: IWMWriterSink.VTable, Connect: fn( self: *const IWMWriterPushSink, pwszURL: ?[*:0]const u16, pwszTemplateURL: ?[*:0]const u16, fAutoDestroy: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const IWMWriterPushSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndSession: fn( self: *const IWMWriterPushSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMWriterSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPushSink_Connect(self: *const T, pwszURL: ?[*:0]const u16, pwszTemplateURL: ?[*:0]const u16, fAutoDestroy: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPushSink.VTable, self.vtable).Connect(@ptrCast(*const IWMWriterPushSink, self), pwszURL, pwszTemplateURL, fAutoDestroy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPushSink_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPushSink.VTable, self.vtable).Disconnect(@ptrCast(*const IWMWriterPushSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWriterPushSink_EndSession(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWriterPushSink.VTable, self.vtable).EndSession(@ptrCast(*const IWMWriterPushSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDeviceRegistration_Value = Guid.initString("f6211f03-8d21-4e94-93e6-8510805f2d99"); pub const IID_IWMDeviceRegistration = &IID_IWMDeviceRegistration_Value; pub const IWMDeviceRegistration = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterDevice: fn( self: *const IWMDeviceRegistration, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16, ppDevice: ?*?*IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterDevice: fn( self: *const IWMDeviceRegistration, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegistrationStats: fn( self: *const IWMDeviceRegistration, dwRegisterType: u32, pcRegisteredDevices: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFirstRegisteredDevice: fn( self: *const IWMDeviceRegistration, dwRegisterType: u32, ppDevice: ?*?*IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextRegisteredDevice: fn( self: *const IWMDeviceRegistration, ppDevice: ?*?*IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegisteredDeviceByID: fn( self: *const IWMDeviceRegistration, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16, ppDevice: ?*?*IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_RegisterDevice(self: *const T, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16, ppDevice: ?*?*IWMRegisteredDevice) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).RegisterDevice(@ptrCast(*const IWMDeviceRegistration, self), dwRegisterType, pbCertificate, cbCertificate, SerialNumber, ppDevice); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_UnregisterDevice(self: *const T, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).UnregisterDevice(@ptrCast(*const IWMDeviceRegistration, self), dwRegisterType, pbCertificate, cbCertificate, SerialNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_GetRegistrationStats(self: *const T, dwRegisterType: u32, pcRegisteredDevices: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).GetRegistrationStats(@ptrCast(*const IWMDeviceRegistration, self), dwRegisterType, pcRegisteredDevices); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_GetFirstRegisteredDevice(self: *const T, dwRegisterType: u32, ppDevice: ?*?*IWMRegisteredDevice) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).GetFirstRegisteredDevice(@ptrCast(*const IWMDeviceRegistration, self), dwRegisterType, ppDevice); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_GetNextRegisteredDevice(self: *const T, ppDevice: ?*?*IWMRegisteredDevice) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).GetNextRegisteredDevice(@ptrCast(*const IWMDeviceRegistration, self), ppDevice); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDeviceRegistration_GetRegisteredDeviceByID(self: *const T, dwRegisterType: u32, pbCertificate: [*:0]u8, cbCertificate: u32, SerialNumber: DRM_VAL16, ppDevice: ?*?*IWMRegisteredDevice) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDeviceRegistration.VTable, self.vtable).GetRegisteredDeviceByID(@ptrCast(*const IWMDeviceRegistration, self), dwRegisterType, pbCertificate, cbCertificate, SerialNumber, ppDevice); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMRegisteredDevice_Value = Guid.initString("a4503bec-5508-4148-97ac-bfa75760a70d"); pub const IID_IWMRegisteredDevice = &IID_IWMRegisteredDevice_Value; pub const IWMRegisteredDevice = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDeviceSerialNumber: fn( self: *const IWMRegisteredDevice, pSerialNumber: ?*DRM_VAL16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceCertificate: fn( self: *const IWMRegisteredDevice, ppCertificate: ?*?*INSSBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceType: fn( self: *const IWMRegisteredDevice, pdwType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeCount: fn( self: *const IWMRegisteredDevice, pcAttributes: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeByIndex: fn( self: *const IWMRegisteredDevice, dwIndex: u32, pbstrName: ?*?BSTR, pbstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeByName: fn( self: *const IWMRegisteredDevice, bstrName: ?BSTR, pbstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAttributeByName: fn( self: *const IWMRegisteredDevice, bstrName: ?BSTR, bstrValue: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Approve: fn( self: *const IWMRegisteredDevice, fApprove: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsValid: fn( self: *const IWMRegisteredDevice, pfValid: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsApproved: fn( self: *const IWMRegisteredDevice, pfApproved: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsWmdrmCompliant: fn( self: *const IWMRegisteredDevice, pfCompliant: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsOpened: fn( self: *const IWMRegisteredDevice, pfOpened: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Open: fn( self: *const IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMRegisteredDevice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetDeviceSerialNumber(self: *const T, pSerialNumber: ?*DRM_VAL16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetDeviceSerialNumber(@ptrCast(*const IWMRegisteredDevice, self), pSerialNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetDeviceCertificate(self: *const T, ppCertificate: ?*?*INSSBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetDeviceCertificate(@ptrCast(*const IWMRegisteredDevice, self), ppCertificate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetDeviceType(self: *const T, pdwType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetDeviceType(@ptrCast(*const IWMRegisteredDevice, self), pdwType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetAttributeCount(self: *const T, pcAttributes: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetAttributeCount(@ptrCast(*const IWMRegisteredDevice, self), pcAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetAttributeByIndex(self: *const T, dwIndex: u32, pbstrName: ?*?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetAttributeByIndex(@ptrCast(*const IWMRegisteredDevice, self), dwIndex, pbstrName, pbstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_GetAttributeByName(self: *const T, bstrName: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).GetAttributeByName(@ptrCast(*const IWMRegisteredDevice, self), bstrName, pbstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_SetAttributeByName(self: *const T, bstrName: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).SetAttributeByName(@ptrCast(*const IWMRegisteredDevice, self), bstrName, bstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_Approve(self: *const T, fApprove: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).Approve(@ptrCast(*const IWMRegisteredDevice, self), fApprove); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_IsValid(self: *const T, pfValid: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).IsValid(@ptrCast(*const IWMRegisteredDevice, self), pfValid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_IsApproved(self: *const T, pfApproved: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).IsApproved(@ptrCast(*const IWMRegisteredDevice, self), pfApproved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_IsWmdrmCompliant(self: *const T, pfCompliant: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).IsWmdrmCompliant(@ptrCast(*const IWMRegisteredDevice, self), pfCompliant); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_IsOpened(self: *const T, pfOpened: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).IsOpened(@ptrCast(*const IWMRegisteredDevice, self), pfOpened); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_Open(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).Open(@ptrCast(*const IWMRegisteredDevice, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMRegisteredDevice_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMRegisteredDevice.VTable, self.vtable).Close(@ptrCast(*const IWMRegisteredDevice, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMProximityDetection_Value = Guid.initString("6a9fd8ee-b651-4bf0-b849-7d4ece79a2b1"); pub const IID_IWMProximityDetection = &IID_IWMProximityDetection_Value; pub const IWMProximityDetection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartDetection: fn( self: *const IWMProximityDetection, pbRegistrationMsg: [*:0]u8, cbRegistrationMsg: u32, pbLocalAddress: [*:0]u8, cbLocalAddress: u32, dwExtraPortsAllowed: u32, ppRegistrationResponseMsg: ?*?*INSSBuffer, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMProximityDetection_StartDetection(self: *const T, pbRegistrationMsg: [*:0]u8, cbRegistrationMsg: u32, pbLocalAddress: [*:0]u8, cbLocalAddress: u32, dwExtraPortsAllowed: u32, ppRegistrationResponseMsg: ?*?*INSSBuffer, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMProximityDetection.VTable, self.vtable).StartDetection(@ptrCast(*const IWMProximityDetection, self), pbRegistrationMsg, cbRegistrationMsg, pbLocalAddress, cbLocalAddress, dwExtraPortsAllowed, ppRegistrationResponseMsg, pCallback, pvContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMMessageParser_Value = Guid.initString("a73a0072-25a0-4c99-b4a5-ede8101a6c39"); pub const IID_IWMDRMMessageParser = &IID_IWMDRMMessageParser_Value; pub const IWMDRMMessageParser = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ParseRegistrationReqMsg: fn( self: *const IWMDRMMessageParser, pbRegistrationReqMsg: [*:0]u8, cbRegistrationReqMsg: u32, ppDeviceCert: ?*?*INSSBuffer, pDeviceSerialNumber: ?*DRM_VAL16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ParseLicenseRequestMsg: fn( self: *const IWMDRMMessageParser, pbLicenseRequestMsg: [*:0]u8, cbLicenseRequestMsg: u32, ppDeviceCert: ?*?*INSSBuffer, pDeviceSerialNumber: ?*DRM_VAL16, pbstrAction: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMMessageParser_ParseRegistrationReqMsg(self: *const T, pbRegistrationReqMsg: [*:0]u8, cbRegistrationReqMsg: u32, ppDeviceCert: ?*?*INSSBuffer, pDeviceSerialNumber: ?*DRM_VAL16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMMessageParser.VTable, self.vtable).ParseRegistrationReqMsg(@ptrCast(*const IWMDRMMessageParser, self), pbRegistrationReqMsg, cbRegistrationReqMsg, ppDeviceCert, pDeviceSerialNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMMessageParser_ParseLicenseRequestMsg(self: *const T, pbLicenseRequestMsg: [*:0]u8, cbLicenseRequestMsg: u32, ppDeviceCert: ?*?*INSSBuffer, pDeviceSerialNumber: ?*DRM_VAL16, pbstrAction: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMMessageParser.VTable, self.vtable).ParseLicenseRequestMsg(@ptrCast(*const IWMDRMMessageParser, self), pbLicenseRequestMsg, cbLicenseRequestMsg, ppDeviceCert, pDeviceSerialNumber, pbstrAction); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWMDRMTranscryptor_Value = Guid.initString("69059850-6e6f-4bb2-806f-71863ddfc471"); pub const IID_IWMDRMTranscryptor = &IID_IWMDRMTranscryptor_Value; pub const IWMDRMTranscryptor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWMDRMTranscryptor, bstrFileName: ?BSTR, pbLicenseRequestMsg: ?*u8, cbLicenseRequestMsg: u32, ppLicenseResponseMsg: ?*?*INSSBuffer, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Seek: fn( self: *const IWMDRMTranscryptor, hnsTime: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Read: fn( self: *const IWMDRMTranscryptor, pbData: ?*u8, pcbData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWMDRMTranscryptor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor_Initialize(self: *const T, bstrFileName: ?BSTR, pbLicenseRequestMsg: ?*u8, cbLicenseRequestMsg: u32, ppLicenseResponseMsg: ?*?*INSSBuffer, pCallback: ?*IWMStatusCallback, pvContext: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor.VTable, self.vtable).Initialize(@ptrCast(*const IWMDRMTranscryptor, self), bstrFileName, pbLicenseRequestMsg, cbLicenseRequestMsg, ppLicenseResponseMsg, pCallback, pvContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor_Seek(self: *const T, hnsTime: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor.VTable, self.vtable).Seek(@ptrCast(*const IWMDRMTranscryptor, self), hnsTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor_Read(self: *const T, pbData: ?*u8, pcbData: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor.VTable, self.vtable).Read(@ptrCast(*const IWMDRMTranscryptor, self), pbData, pcbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor.VTable, self.vtable).Close(@ptrCast(*const IWMDRMTranscryptor, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMDRMTranscryptor2_Value = Guid.initString("e0da439f-d331-496a-bece-18e5bac5dd23"); pub const IID_IWMDRMTranscryptor2 = &IID_IWMDRMTranscryptor2_Value; pub const IWMDRMTranscryptor2 = extern struct { pub const VTable = extern struct { base: IWMDRMTranscryptor.VTable, SeekEx: fn( self: *const IWMDRMTranscryptor2, cnsStartTime: u64, cnsDuration: u64, flRate: f32, fIncludeFileHeader: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ZeroAdjustTimestamps: fn( self: *const IWMDRMTranscryptor2, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSeekStartTime: fn( self: *const IWMDRMTranscryptor2, pcnsTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDuration: fn( self: *const IWMDRMTranscryptor2, pcnsDuration: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMDRMTranscryptor.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor2_SeekEx(self: *const T, cnsStartTime: u64, cnsDuration: u64, flRate: f32, fIncludeFileHeader: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor2.VTable, self.vtable).SeekEx(@ptrCast(*const IWMDRMTranscryptor2, self), cnsStartTime, cnsDuration, flRate, fIncludeFileHeader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor2_ZeroAdjustTimestamps(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor2.VTable, self.vtable).ZeroAdjustTimestamps(@ptrCast(*const IWMDRMTranscryptor2, self), fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor2_GetSeekStartTime(self: *const T, pcnsTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor2.VTable, self.vtable).GetSeekStartTime(@ptrCast(*const IWMDRMTranscryptor2, self), pcnsTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptor2_GetDuration(self: *const T, pcnsDuration: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptor2.VTable, self.vtable).GetDuration(@ptrCast(*const IWMDRMTranscryptor2, self), pcnsDuration); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMDRMTranscryptionManager_Value = Guid.initString("b1a887b2-a4f0-407a-b02e-efbd23bbecdf"); pub const IID_IWMDRMTranscryptionManager = &IID_IWMDRMTranscryptionManager_Value; pub const IWMDRMTranscryptionManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateTranscryptor: fn( self: *const IWMDRMTranscryptionManager, ppTranscryptor: ?*?*IWMDRMTranscryptor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMDRMTranscryptionManager_CreateTranscryptor(self: *const T, ppTranscryptor: ?*?*IWMDRMTranscryptor) callconv(.Inline) HRESULT { return @ptrCast(*const IWMDRMTranscryptionManager.VTable, self.vtable).CreateTranscryptor(@ptrCast(*const IWMDRMTranscryptionManager, self), ppTranscryptor); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMWatermarkInfo_Value = Guid.initString("6f497062-f2e2-4624-8ea7-9dd40d81fc8d"); pub const IID_IWMWatermarkInfo = &IID_IWMWatermarkInfo_Value; pub const IWMWatermarkInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetWatermarkEntryCount: fn( self: *const IWMWatermarkInfo, wmetType: WMT_WATERMARK_ENTRY_TYPE, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWatermarkEntry: fn( self: *const IWMWatermarkInfo, wmetType: WMT_WATERMARK_ENTRY_TYPE, dwEntryNum: u32, pEntry: ?*WMT_WATERMARK_ENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWatermarkInfo_GetWatermarkEntryCount(self: *const T, wmetType: WMT_WATERMARK_ENTRY_TYPE, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWatermarkInfo.VTable, self.vtable).GetWatermarkEntryCount(@ptrCast(*const IWMWatermarkInfo, self), wmetType, pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMWatermarkInfo_GetWatermarkEntry(self: *const T, wmetType: WMT_WATERMARK_ENTRY_TYPE, dwEntryNum: u32, pEntry: ?*WMT_WATERMARK_ENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IWMWatermarkInfo.VTable, self.vtable).GetWatermarkEntry(@ptrCast(*const IWMWatermarkInfo, self), wmetType, dwEntryNum, pEntry); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderAccelerator_Value = Guid.initString("bddc4d08-944d-4d52-a612-46c3fda07dd4"); pub const IID_IWMReaderAccelerator = &IID_IWMReaderAccelerator_Value; pub const IWMReaderAccelerator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCodecInterface: fn( self: *const IWMReaderAccelerator, dwOutputNum: u32, riid: ?*const Guid, ppvCodecInterface: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Notify: fn( self: *const IWMReaderAccelerator, dwOutputNum: u32, pSubtype: ?*WM_MEDIA_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAccelerator_GetCodecInterface(self: *const T, dwOutputNum: u32, riid: ?*const Guid, ppvCodecInterface: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAccelerator.VTable, self.vtable).GetCodecInterface(@ptrCast(*const IWMReaderAccelerator, self), dwOutputNum, riid, ppvCodecInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderAccelerator_Notify(self: *const T, dwOutputNum: u32, pSubtype: ?*WM_MEDIA_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderAccelerator.VTable, self.vtable).Notify(@ptrCast(*const IWMReaderAccelerator, self), dwOutputNum, pSubtype); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMReaderTimecode_Value = Guid.initString("f369e2f0-e081-4fe6-8450-b810b2f410d1"); pub const IID_IWMReaderTimecode = &IID_IWMReaderTimecode_Value; pub const IWMReaderTimecode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetTimecodeRangeCount: fn( self: *const IWMReaderTimecode, wStreamNum: u16, pwRangeCount: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTimecodeRangeBounds: fn( self: *const IWMReaderTimecode, wStreamNum: u16, wRangeNum: u16, pStartTimecode: ?*u32, pEndTimecode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderTimecode_GetTimecodeRangeCount(self: *const T, wStreamNum: u16, pwRangeCount: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderTimecode.VTable, self.vtable).GetTimecodeRangeCount(@ptrCast(*const IWMReaderTimecode, self), wStreamNum, pwRangeCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMReaderTimecode_GetTimecodeRangeBounds(self: *const T, wStreamNum: u16, wRangeNum: u16, pStartTimecode: ?*u32, pEndTimecode: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMReaderTimecode.VTable, self.vtable).GetTimecodeRangeBounds(@ptrCast(*const IWMReaderTimecode, self), wStreamNum, wRangeNum, pStartTimecode, pEndTimecode); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMAddressAccess_Value = Guid.initString("bb3c6389-1633-4e92-af14-9f3173ba39d0"); pub const IID_IWMAddressAccess = &IID_IWMAddressAccess_Value; pub const IWMAddressAccess = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAccessEntryCount: fn( self: *const IWMAddressAccess, aeType: WM_AETYPE, pcEntries: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAccessEntry: fn( self: *const IWMAddressAccess, aeType: WM_AETYPE, dwEntryNum: u32, pAddrAccessEntry: ?*WM_ADDRESS_ACCESSENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAccessEntry: fn( self: *const IWMAddressAccess, aeType: WM_AETYPE, pAddrAccessEntry: ?*WM_ADDRESS_ACCESSENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAccessEntry: fn( self: *const IWMAddressAccess, aeType: WM_AETYPE, dwEntryNum: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess_GetAccessEntryCount(self: *const T, aeType: WM_AETYPE, pcEntries: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess.VTable, self.vtable).GetAccessEntryCount(@ptrCast(*const IWMAddressAccess, self), aeType, pcEntries); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess_GetAccessEntry(self: *const T, aeType: WM_AETYPE, dwEntryNum: u32, pAddrAccessEntry: ?*WM_ADDRESS_ACCESSENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess.VTable, self.vtable).GetAccessEntry(@ptrCast(*const IWMAddressAccess, self), aeType, dwEntryNum, pAddrAccessEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess_AddAccessEntry(self: *const T, aeType: WM_AETYPE, pAddrAccessEntry: ?*WM_ADDRESS_ACCESSENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess.VTable, self.vtable).AddAccessEntry(@ptrCast(*const IWMAddressAccess, self), aeType, pAddrAccessEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess_RemoveAccessEntry(self: *const T, aeType: WM_AETYPE, dwEntryNum: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess.VTable, self.vtable).RemoveAccessEntry(@ptrCast(*const IWMAddressAccess, self), aeType, dwEntryNum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMAddressAccess2_Value = Guid.initString("65a83fc2-3e98-4d4d-81b5-2a742886b33d"); pub const IID_IWMAddressAccess2 = &IID_IWMAddressAccess2_Value; pub const IWMAddressAccess2 = extern struct { pub const VTable = extern struct { base: IWMAddressAccess.VTable, GetAccessEntryEx: fn( self: *const IWMAddressAccess2, aeType: WM_AETYPE, dwEntryNum: u32, pbstrAddress: ?*?BSTR, pbstrMask: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAccessEntryEx: fn( self: *const IWMAddressAccess2, aeType: WM_AETYPE, bstrAddress: ?BSTR, bstrMask: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMAddressAccess.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess2_GetAccessEntryEx(self: *const T, aeType: WM_AETYPE, dwEntryNum: u32, pbstrAddress: ?*?BSTR, pbstrMask: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess2.VTable, self.vtable).GetAccessEntryEx(@ptrCast(*const IWMAddressAccess2, self), aeType, dwEntryNum, pbstrAddress, pbstrMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAddressAccess2_AddAccessEntryEx(self: *const T, aeType: WM_AETYPE, bstrAddress: ?BSTR, bstrMask: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAddressAccess2.VTable, self.vtable).AddAccessEntryEx(@ptrCast(*const IWMAddressAccess2, self), aeType, bstrAddress, bstrMask); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMImageInfo_Value = Guid.initString("9f0aa3b6-7267-4d89-88f2-ba915aa5c4c6"); pub const IID_IWMImageInfo = &IID_IWMImageInfo_Value; pub const IWMImageInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetImageCount: fn( self: *const IWMImageInfo, pcImages: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImage: fn( self: *const IWMImageInfo, wIndex: u32, pcchMIMEType: ?*u16, pwszMIMEType: [*:0]u16, pcchDescription: ?*u16, pwszDescription: [*:0]u16, pImageType: ?*u16, pcbImageData: ?*u32, pbImageData: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMImageInfo_GetImageCount(self: *const T, pcImages: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMImageInfo.VTable, self.vtable).GetImageCount(@ptrCast(*const IWMImageInfo, self), pcImages); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMImageInfo_GetImage(self: *const T, wIndex: u32, pcchMIMEType: ?*u16, pwszMIMEType: [*:0]u16, pcchDescription: ?*u16, pwszDescription: [*:0]u16, pImageType: ?*u16, pcbImageData: ?*u32, pbImageData: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMImageInfo.VTable, self.vtable).GetImage(@ptrCast(*const IWMImageInfo, self), wIndex, pcchMIMEType, pwszMIMEType, pcchDescription, pwszDescription, pImageType, pcbImageData, pbImageData); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMLicenseRevocationAgent_Value = Guid.initString("6967f2c9-4e26-4b57-8894-799880f7ac7b"); pub const IID_IWMLicenseRevocationAgent = &IID_IWMLicenseRevocationAgent_Value; pub const IWMLicenseRevocationAgent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLRBChallenge: fn( self: *const IWMLicenseRevocationAgent, pMachineID: ?*u8, dwMachineIDLength: u32, pChallenge: ?*u8, dwChallengeLength: u32, pChallengeOutput: ?*u8, pdwChallengeOutputLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessLRB: fn( self: *const IWMLicenseRevocationAgent, pSignedLRB: ?*u8, dwSignedLRBLength: u32, pSignedACK: ?*u8, pdwSignedACKLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseRevocationAgent_GetLRBChallenge(self: *const T, pMachineID: ?*u8, dwMachineIDLength: u32, pChallenge: ?*u8, dwChallengeLength: u32, pChallengeOutput: ?*u8, pdwChallengeOutputLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseRevocationAgent.VTable, self.vtable).GetLRBChallenge(@ptrCast(*const IWMLicenseRevocationAgent, self), pMachineID, dwMachineIDLength, pChallenge, dwChallengeLength, pChallengeOutput, pdwChallengeOutputLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMLicenseRevocationAgent_ProcessLRB(self: *const T, pSignedLRB: ?*u8, dwSignedLRBLength: u32, pSignedACK: ?*u8, pdwSignedACKLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMLicenseRevocationAgent.VTable, self.vtable).ProcessLRB(@ptrCast(*const IWMLicenseRevocationAgent, self), pSignedLRB, dwSignedLRBLength, pSignedACK, pdwSignedACKLength); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMAuthorizer_Value = Guid.initString("d9b67d36-a9ad-4eb4-baef-db284ef5504c"); pub const IID_IWMAuthorizer = &IID_IWMAuthorizer_Value; pub const IWMAuthorizer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCertCount: fn( self: *const IWMAuthorizer, pcCerts: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCert: fn( self: *const IWMAuthorizer, dwIndex: u32, ppbCertData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSharedData: fn( self: *const IWMAuthorizer, dwCertIndex: u32, pbSharedData: ?*const u8, pbCert: ?*u8, ppbSharedData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAuthorizer_GetCertCount(self: *const T, pcCerts: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAuthorizer.VTable, self.vtable).GetCertCount(@ptrCast(*const IWMAuthorizer, self), pcCerts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAuthorizer_GetCert(self: *const T, dwIndex: u32, ppbCertData: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAuthorizer.VTable, self.vtable).GetCert(@ptrCast(*const IWMAuthorizer, self), dwIndex, ppbCertData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMAuthorizer_GetSharedData(self: *const T, dwCertIndex: u32, pbSharedData: ?*const u8, pbCert: ?*u8, ppbSharedData: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMAuthorizer.VTable, self.vtable).GetSharedData(@ptrCast(*const IWMAuthorizer, self), dwCertIndex, pbSharedData, pbCert, ppbSharedData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMSecureChannel_Value = Guid.initString("2720598a-d0f2-4189-bd10-91c46ef0936f"); pub const IID_IWMSecureChannel = &IID_IWMSecureChannel_Value; pub const IWMSecureChannel = extern struct { pub const VTable = extern struct { base: IWMAuthorizer.VTable, WMSC_AddCertificate: fn( self: *const IWMSecureChannel, pCert: ?*IWMAuthorizer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_AddSignature: fn( self: *const IWMSecureChannel, pbCertSig: ?*u8, cbCertSig: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Connect: fn( self: *const IWMSecureChannel, pOtherSide: ?*IWMSecureChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_IsConnected: fn( self: *const IWMSecureChannel, pfIsConnected: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Disconnect: fn( self: *const IWMSecureChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_GetValidCertificate: fn( self: *const IWMSecureChannel, ppbCertificate: ?*?*u8, pdwSignature: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Encrypt: fn( self: *const IWMSecureChannel, pbData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Decrypt: fn( self: *const IWMSecureChannel, pbData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Lock: fn( self: *const IWMSecureChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_Unlock: fn( self: *const IWMSecureChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WMSC_SetSharedData: fn( self: *const IWMSecureChannel, dwCertIndex: u32, pbSharedData: ?*const u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMAuthorizer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_AddCertificate(self: *const T, pCert: ?*IWMAuthorizer) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_AddCertificate(@ptrCast(*const IWMSecureChannel, self), pCert); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_AddSignature(self: *const T, pbCertSig: ?*u8, cbCertSig: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_AddSignature(@ptrCast(*const IWMSecureChannel, self), pbCertSig, cbCertSig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Connect(self: *const T, pOtherSide: ?*IWMSecureChannel) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Connect(@ptrCast(*const IWMSecureChannel, self), pOtherSide); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_IsConnected(self: *const T, pfIsConnected: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_IsConnected(@ptrCast(*const IWMSecureChannel, self), pfIsConnected); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Disconnect(@ptrCast(*const IWMSecureChannel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_GetValidCertificate(self: *const T, ppbCertificate: ?*?*u8, pdwSignature: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_GetValidCertificate(@ptrCast(*const IWMSecureChannel, self), ppbCertificate, pdwSignature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Encrypt(self: *const T, pbData: ?*u8, cbData: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Encrypt(@ptrCast(*const IWMSecureChannel, self), pbData, cbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Decrypt(self: *const T, pbData: ?*u8, cbData: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Decrypt(@ptrCast(*const IWMSecureChannel, self), pbData, cbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Lock(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Lock(@ptrCast(*const IWMSecureChannel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_Unlock(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_Unlock(@ptrCast(*const IWMSecureChannel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSecureChannel_WMSC_SetSharedData(self: *const T, dwCertIndex: u32, pbSharedData: ?*const u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSecureChannel.VTable, self.vtable).WMSC_SetSharedData(@ptrCast(*const IWMSecureChannel, self), dwCertIndex, pbSharedData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IWMGetSecureChannel_Value = Guid.initString("94bc0598-c3d2-11d3-bedf-00c04f612986"); pub const IID_IWMGetSecureChannel = &IID_IWMGetSecureChannel_Value; pub const IWMGetSecureChannel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPeerSecureChannelInterface: fn( self: *const IWMGetSecureChannel, ppPeer: ?*?*IWMSecureChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMGetSecureChannel_GetPeerSecureChannelInterface(self: *const T, ppPeer: ?*?*IWMSecureChannel) callconv(.Inline) HRESULT { return @ptrCast(*const IWMGetSecureChannel.VTable, self.vtable).GetPeerSecureChannelInterface(@ptrCast(*const IWMGetSecureChannel, self), ppPeer); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INSNetSourceCreator_Value = Guid.initString("0c0e4080-9081-11d2-beec-0060082f2054"); pub const IID_INSNetSourceCreator = &IID_INSNetSourceCreator_Value; pub const INSNetSourceCreator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const INSNetSourceCreator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNetSource: fn( self: *const INSNetSourceCreator, pszStreamName: ?[*:0]const u16, pMonitor: ?*IUnknown, pData: ?*u8, pUserContext: ?*IUnknown, pCallback: ?*IUnknown, qwContext: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetSourceProperties: fn( self: *const INSNetSourceCreator, pszStreamName: ?[*:0]const u16, ppPropertiesNode: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetSourceSharedNamespace: fn( self: *const INSNetSourceCreator, ppSharedNamespace: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetSourceAdminInterface: fn( self: *const INSNetSourceCreator, pszStreamName: ?[*:0]const u16, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumProtocolsSupported: fn( self: *const INSNetSourceCreator, pcProtocols: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProtocolName: fn( self: *const INSNetSourceCreator, dwProtocolNum: u32, pwszProtocolName: ?PWSTR, pcchProtocolName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Shutdown: fn( self: *const INSNetSourceCreator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_Initialize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).Initialize(@ptrCast(*const INSNetSourceCreator, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_CreateNetSource(self: *const T, pszStreamName: ?[*:0]const u16, pMonitor: ?*IUnknown, pData: ?*u8, pUserContext: ?*IUnknown, pCallback: ?*IUnknown, qwContext: u64) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).CreateNetSource(@ptrCast(*const INSNetSourceCreator, self), pszStreamName, pMonitor, pData, pUserContext, pCallback, qwContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_GetNetSourceProperties(self: *const T, pszStreamName: ?[*:0]const u16, ppPropertiesNode: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).GetNetSourceProperties(@ptrCast(*const INSNetSourceCreator, self), pszStreamName, ppPropertiesNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_GetNetSourceSharedNamespace(self: *const T, ppSharedNamespace: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).GetNetSourceSharedNamespace(@ptrCast(*const INSNetSourceCreator, self), ppSharedNamespace); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_GetNetSourceAdminInterface(self: *const T, pszStreamName: ?[*:0]const u16, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).GetNetSourceAdminInterface(@ptrCast(*const INSNetSourceCreator, self), pszStreamName, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_GetNumProtocolsSupported(self: *const T, pcProtocols: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).GetNumProtocolsSupported(@ptrCast(*const INSNetSourceCreator, self), pcProtocols); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_GetProtocolName(self: *const T, dwProtocolNum: u32, pwszProtocolName: ?PWSTR, pcchProtocolName: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).GetProtocolName(@ptrCast(*const INSNetSourceCreator, self), dwProtocolNum, pwszProtocolName, pcchProtocolName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INSNetSourceCreator_Shutdown(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INSNetSourceCreator.VTable, self.vtable).Shutdown(@ptrCast(*const INSNetSourceCreator, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMPlayerTimestampHook_Value = Guid.initString("28580dda-d98e-48d0-b7ae-69e473a02825"); pub const IID_IWMPlayerTimestampHook = &IID_IWMPlayerTimestampHook_Value; pub const IWMPlayerTimestampHook = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, MapTimestamp: fn( self: *const IWMPlayerTimestampHook, rtIn: i64, prtOut: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMPlayerTimestampHook_MapTimestamp(self: *const T, rtIn: i64, prtOut: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMPlayerTimestampHook.VTable, self.vtable).MapTimestamp(@ptrCast(*const IWMPlayerTimestampHook, self), rtIn, prtOut); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCodecAMVideoAccelerator_Value = Guid.initString("d98ee251-34e0-4a2d-9312-9b4c788d9fa1"); pub const IID_IWMCodecAMVideoAccelerator = &IID_IWMCodecAMVideoAccelerator_Value; pub const IWMCodecAMVideoAccelerator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAcceleratorInterface: fn( self: *const IWMCodecAMVideoAccelerator, pIAMVA: ?*IAMVideoAccelerator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NegotiateConnection: fn( self: *const IWMCodecAMVideoAccelerator, pMediaType: ?*AM_MEDIA_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPlayerNotify: fn( self: *const IWMCodecAMVideoAccelerator, pHook: ?*IWMPlayerTimestampHook, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecAMVideoAccelerator_SetAcceleratorInterface(self: *const T, pIAMVA: ?*IAMVideoAccelerator) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecAMVideoAccelerator.VTable, self.vtable).SetAcceleratorInterface(@ptrCast(*const IWMCodecAMVideoAccelerator, self), pIAMVA); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecAMVideoAccelerator_NegotiateConnection(self: *const T, pMediaType: ?*AM_MEDIA_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecAMVideoAccelerator.VTable, self.vtable).NegotiateConnection(@ptrCast(*const IWMCodecAMVideoAccelerator, self), pMediaType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecAMVideoAccelerator_SetPlayerNotify(self: *const T, pHook: ?*IWMPlayerTimestampHook) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecAMVideoAccelerator.VTable, self.vtable).SetPlayerNotify(@ptrCast(*const IWMCodecAMVideoAccelerator, self), pHook); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMCodecVideoAccelerator_Value = Guid.initString("990641b0-739f-4e94-a808-9888da8f75af"); pub const IID_IWMCodecVideoAccelerator = &IID_IWMCodecVideoAccelerator_Value; pub const IWMCodecVideoAccelerator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NegotiateConnection: fn( self: *const IWMCodecVideoAccelerator, pIAMVA: ?*IAMVideoAccelerator, pMediaType: ?*AM_MEDIA_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPlayerNotify: fn( self: *const IWMCodecVideoAccelerator, pHook: ?*IWMPlayerTimestampHook, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecVideoAccelerator_NegotiateConnection(self: *const T, pIAMVA: ?*IAMVideoAccelerator, pMediaType: ?*AM_MEDIA_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecVideoAccelerator.VTable, self.vtable).NegotiateConnection(@ptrCast(*const IWMCodecVideoAccelerator, self), pIAMVA, pMediaType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMCodecVideoAccelerator_SetPlayerNotify(self: *const T, pHook: ?*IWMPlayerTimestampHook) callconv(.Inline) HRESULT { return @ptrCast(*const IWMCodecVideoAccelerator.VTable, self.vtable).SetPlayerNotify(@ptrCast(*const IWMCodecVideoAccelerator, self), pHook); } };} pub usingnamespace MethodMixin(@This()); }; pub const NETSOURCE_URLCREDPOLICY_SETTINGS = enum(i32) { SILENTLOGONOK = 0, MUSTPROMPTUSER = 1, ANONYMOUSONLY = 2, }; pub const NETSOURCE_URLCREDPOLICY_SETTING_SILENTLOGONOK = NETSOURCE_URLCREDPOLICY_SETTINGS.SILENTLOGONOK; pub const NETSOURCE_URLCREDPOLICY_SETTING_MUSTPROMPTUSER = NETSOURCE_URLCREDPOLICY_SETTINGS.MUSTPROMPTUSER; pub const NETSOURCE_URLCREDPOLICY_SETTING_ANONYMOUSONLY = NETSOURCE_URLCREDPOLICY_SETTINGS.ANONYMOUSONLY; const IID_IWMSInternalAdminNetSource_Value = Guid.initString("8bb23e5f-d127-4afb-8d02-ae5b66d54c78"); pub const IID_IWMSInternalAdminNetSource = &IID_IWMSInternalAdminNetSource_Value; pub const IWMSInternalAdminNetSource = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWMSInternalAdminNetSource, pSharedNamespace: ?*IUnknown, pNamespaceNode: ?*IUnknown, pNetSourceCreator: ?*INSNetSourceCreator, fEmbeddedInServer: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetSourceCreator: fn( self: *const IWMSInternalAdminNetSource, ppNetSourceCreator: ?*?*INSNetSourceCreator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCredentials: fn( self: *const IWMSInternalAdminNetSource, bstrRealm: ?BSTR, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCredentials: fn( self: *const IWMSInternalAdminNetSource, bstrRealm: ?BSTR, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteCredentials: fn( self: *const IWMSInternalAdminNetSource, bstrRealm: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCredentialFlags: fn( self: *const IWMSInternalAdminNetSource, lpdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCredentialFlags: fn( self: *const IWMSInternalAdminNetSource, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindProxyForURL: fn( self: *const IWMSInternalAdminNetSource, bstrProtocol: ?BSTR, bstrHost: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pdwProxyContext: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterProxyFailure: fn( self: *const IWMSInternalAdminNetSource, hrParam: HRESULT, dwProxyContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShutdownProxyContext: fn( self: *const IWMSInternalAdminNetSource, dwProxyContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUsingIE: fn( self: *const IWMSInternalAdminNetSource, dwProxyContext: u32, pfIsUsingIE: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_Initialize(self: *const T, pSharedNamespace: ?*IUnknown, pNamespaceNode: ?*IUnknown, pNetSourceCreator: ?*INSNetSourceCreator, fEmbeddedInServer: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).Initialize(@ptrCast(*const IWMSInternalAdminNetSource, self), pSharedNamespace, pNamespaceNode, pNetSourceCreator, fEmbeddedInServer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_GetNetSourceCreator(self: *const T, ppNetSourceCreator: ?*?*INSNetSourceCreator) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).GetNetSourceCreator(@ptrCast(*const IWMSInternalAdminNetSource, self), ppNetSourceCreator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_SetCredentials(self: *const T, bstrRealm: ?BSTR, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).SetCredentials(@ptrCast(*const IWMSInternalAdminNetSource, self), bstrRealm, bstrName, bstrPassword, fPersist, fConfirmedGood); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_GetCredentials(self: *const T, bstrRealm: ?BSTR, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).GetCredentials(@ptrCast(*const IWMSInternalAdminNetSource, self), bstrRealm, pbstrName, pbstrPassword, pfConfirmedGood); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_DeleteCredentials(self: *const T, bstrRealm: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).DeleteCredentials(@ptrCast(*const IWMSInternalAdminNetSource, self), bstrRealm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_GetCredentialFlags(self: *const T, lpdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).GetCredentialFlags(@ptrCast(*const IWMSInternalAdminNetSource, self), lpdwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_SetCredentialFlags(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).SetCredentialFlags(@ptrCast(*const IWMSInternalAdminNetSource, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_FindProxyForURL(self: *const T, bstrProtocol: ?BSTR, bstrHost: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pdwProxyContext: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).FindProxyForURL(@ptrCast(*const IWMSInternalAdminNetSource, self), bstrProtocol, bstrHost, pfProxyEnabled, pbstrProxyServer, pdwProxyPort, pdwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_RegisterProxyFailure(self: *const T, hrParam: HRESULT, dwProxyContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).RegisterProxyFailure(@ptrCast(*const IWMSInternalAdminNetSource, self), hrParam, dwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_ShutdownProxyContext(self: *const T, dwProxyContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).ShutdownProxyContext(@ptrCast(*const IWMSInternalAdminNetSource, self), dwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource_IsUsingIE(self: *const T, dwProxyContext: u32, pfIsUsingIE: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource.VTable, self.vtable).IsUsingIE(@ptrCast(*const IWMSInternalAdminNetSource, self), dwProxyContext, pfIsUsingIE); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMSInternalAdminNetSource2_Value = Guid.initString("e74d58c3-cf77-4b51-af17-744687c43eae"); pub const IID_IWMSInternalAdminNetSource2 = &IID_IWMSInternalAdminNetSource2_Value; pub const IWMSInternalAdminNetSource2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetCredentialsEx: fn( self: *const IWMSInternalAdminNetSource2, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCredentialsEx: fn( self: *const IWMSInternalAdminNetSource2, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, pdwUrlPolicy: ?*NETSOURCE_URLCREDPOLICY_SETTINGS, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteCredentialsEx: fn( self: *const IWMSInternalAdminNetSource2, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindProxyForURLEx: fn( self: *const IWMSInternalAdminNetSource2, bstrProtocol: ?BSTR, bstrHost: ?BSTR, bstrUrl: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pdwProxyContext: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource2_SetCredentialsEx(self: *const T, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource2.VTable, self.vtable).SetCredentialsEx(@ptrCast(*const IWMSInternalAdminNetSource2, self), bstrRealm, bstrUrl, fProxy, bstrName, bstrPassword, fPersist, fConfirmedGood); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource2_GetCredentialsEx(self: *const T, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, pdwUrlPolicy: ?*NETSOURCE_URLCREDPOLICY_SETTINGS, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource2.VTable, self.vtable).GetCredentialsEx(@ptrCast(*const IWMSInternalAdminNetSource2, self), bstrRealm, bstrUrl, fProxy, pdwUrlPolicy, pbstrName, pbstrPassword, pfConfirmedGood); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource2_DeleteCredentialsEx(self: *const T, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource2.VTable, self.vtable).DeleteCredentialsEx(@ptrCast(*const IWMSInternalAdminNetSource2, self), bstrRealm, bstrUrl, fProxy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource2_FindProxyForURLEx(self: *const T, bstrProtocol: ?BSTR, bstrHost: ?BSTR, bstrUrl: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pdwProxyContext: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource2.VTable, self.vtable).FindProxyForURLEx(@ptrCast(*const IWMSInternalAdminNetSource2, self), bstrProtocol, bstrHost, bstrUrl, pfProxyEnabled, pbstrProxyServer, pdwProxyPort, pdwProxyContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWMSInternalAdminNetSource3_Value = Guid.initString("6b63d08e-4590-44af-9eb3-57ff1e73bf80"); pub const IID_IWMSInternalAdminNetSource3 = &IID_IWMSInternalAdminNetSource3_Value; pub const IWMSInternalAdminNetSource3 = extern struct { pub const VTable = extern struct { base: IWMSInternalAdminNetSource2.VTable, GetNetSourceCreator2: fn( self: *const IWMSInternalAdminNetSource3, ppNetSourceCreator: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindProxyForURLEx2: fn( self: *const IWMSInternalAdminNetSource3, bstrProtocol: ?BSTR, bstrHost: ?BSTR, bstrUrl: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pqwProxyContext: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterProxyFailure2: fn( self: *const IWMSInternalAdminNetSource3, hrParam: HRESULT, qwProxyContext: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShutdownProxyContext2: fn( self: *const IWMSInternalAdminNetSource3, qwProxyContext: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUsingIE2: fn( self: *const IWMSInternalAdminNetSource3, qwProxyContext: u64, pfIsUsingIE: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCredentialsEx2: fn( self: *const IWMSInternalAdminNetSource3, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL, fClearTextAuthentication: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCredentialsEx2: fn( self: *const IWMSInternalAdminNetSource3, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, fClearTextAuthentication: BOOL, pdwUrlPolicy: ?*NETSOURCE_URLCREDPOLICY_SETTINGS, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWMSInternalAdminNetSource2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_GetNetSourceCreator2(self: *const T, ppNetSourceCreator: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).GetNetSourceCreator2(@ptrCast(*const IWMSInternalAdminNetSource3, self), ppNetSourceCreator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_FindProxyForURLEx2(self: *const T, bstrProtocol: ?BSTR, bstrHost: ?BSTR, bstrUrl: ?BSTR, pfProxyEnabled: ?*BOOL, pbstrProxyServer: ?*?BSTR, pdwProxyPort: ?*u32, pqwProxyContext: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).FindProxyForURLEx2(@ptrCast(*const IWMSInternalAdminNetSource3, self), bstrProtocol, bstrHost, bstrUrl, pfProxyEnabled, pbstrProxyServer, pdwProxyPort, pqwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_RegisterProxyFailure2(self: *const T, hrParam: HRESULT, qwProxyContext: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).RegisterProxyFailure2(@ptrCast(*const IWMSInternalAdminNetSource3, self), hrParam, qwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_ShutdownProxyContext2(self: *const T, qwProxyContext: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).ShutdownProxyContext2(@ptrCast(*const IWMSInternalAdminNetSource3, self), qwProxyContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_IsUsingIE2(self: *const T, qwProxyContext: u64, pfIsUsingIE: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).IsUsingIE2(@ptrCast(*const IWMSInternalAdminNetSource3, self), qwProxyContext, pfIsUsingIE); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_SetCredentialsEx2(self: *const T, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, bstrName: ?BSTR, bstrPassword: ?BSTR, fPersist: BOOL, fConfirmedGood: BOOL, fClearTextAuthentication: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).SetCredentialsEx2(@ptrCast(*const IWMSInternalAdminNetSource3, self), bstrRealm, bstrUrl, fProxy, bstrName, bstrPassword, fPersist, fConfirmedGood, fClearTextAuthentication); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWMSInternalAdminNetSource3_GetCredentialsEx2(self: *const T, bstrRealm: ?BSTR, bstrUrl: ?BSTR, fProxy: BOOL, fClearTextAuthentication: BOOL, pdwUrlPolicy: ?*NETSOURCE_URLCREDPOLICY_SETTINGS, pbstrName: ?*?BSTR, pbstrPassword: ?*?BSTR, pfConfirmedGood: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWMSInternalAdminNetSource3.VTable, self.vtable).GetCredentialsEx2(@ptrCast(*const IWMSInternalAdminNetSource3, self), bstrRealm, bstrUrl, fProxy, fClearTextAuthentication, pdwUrlPolicy, pbstrName, pbstrPassword, pfConfirmedGood); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (11) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMIsContentProtected( pwszFileName: ?[*:0]const u16, pfIsProtected: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateWriter( pUnkCert: ?*IUnknown, ppWriter: ?*?*IWMWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateReader( pUnkCert: ?*IUnknown, dwRights: u32, ppReader: ?*?*IWMReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateSyncReader( pUnkCert: ?*IUnknown, dwRights: u32, ppSyncReader: ?*?*IWMSyncReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateEditor( ppEditor: ?*?*IWMMetadataEditor, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateIndexer( ppIndexer: ?*?*IWMIndexer, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateBackupRestorer( pCallback: ?*IUnknown, ppBackup: ?*?*IWMLicenseBackup, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateProfileManager( ppProfileManager: ?*?*IWMProfileManager, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateWriterFileSink( ppSink: ?*?*IWMWriterFileSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateWriterNetworkSink( ppSink: ?*?*IWMWriterNetworkSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "WMVCore" fn WMCreateWriterPushSink( ppSink: ?*?*IWMWriterPushSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (14) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const AM_MEDIA_TYPE = @import("../media/direct_show.zig").AM_MEDIA_TYPE; const BITMAPINFOHEADER = @import("../graphics/gdi.zig").BITMAPINFOHEADER; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const HRESULT = @import("../foundation.zig").HRESULT; const IAMVideoAccelerator = @import("../media/direct_show.zig").IAMVideoAccelerator; const IPin = @import("../media/direct_show.zig").IPin; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const LPARAM = @import("../foundation.zig").LPARAM; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const VARIANT = @import("../system/com.zig").VARIANT; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/media/windows_media_format.zig
const std = @import("std"); const assert = std.debug.assert; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w = zwin32.base; const xaudio2 = zwin32.xaudio2; const mf = zwin32.mf; const wasapi = zwin32.wasapi; const xapo = zwin32.xapo; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const WAVEFORMATEX = wasapi.WAVEFORMATEX; const enable_dx_debug = @import("build_options").enable_dx_debug; const optimal_voice_format = WAVEFORMATEX{ .wFormatTag = wasapi.WAVE_FORMAT_PCM, .nChannels = 1, .nSamplesPerSec = 48_000, .nAvgBytesPerSec = 2 * 48_000, .nBlockAlign = 2, .wBitsPerSample = 16, .cbSize = @sizeOf(WAVEFORMATEX), }; const StopOnBufferEnd_VoiceCallback = struct { vtable: *const xaudio2.IVoiceCallbackVTable(Self) = &vtable_instance, const Self = @This(); fn OnBufferEnd(_: *Self, context: ?*anyopaque) callconv(w.WINAPI) void { const voice = @ptrCast(*xaudio2.ISourceVoice, @alignCast(8, context)); hrPanicOnFail(voice.Stop(0, xaudio2.COMMIT_NOW)); } const vtable_instance = xaudio2.IVoiceCallbackVTable(Self){ .vcb = .{ .OnVoiceProcessingPassStart = OnVoiceProcessingPassStart, .OnVoiceProcessingPassEnd = OnVoiceProcessingPassEnd, .OnStreamEnd = OnStreamEnd, .OnBufferStart = OnBufferStart, .OnBufferEnd = OnBufferEnd, .OnLoopEnd = OnLoopEnd, .OnVoiceError = OnVoiceError, }, }; fn OnVoiceProcessingPassStart(_: *Self, _: w.UINT32) callconv(w.WINAPI) void {} fn OnVoiceProcessingPassEnd(_: *Self) callconv(w.WINAPI) void {} fn OnStreamEnd(_: *Self) callconv(w.WINAPI) void {} fn OnBufferStart(_: *Self, _: ?*anyopaque) callconv(w.WINAPI) void {} fn OnLoopEnd(_: *Self, _: ?*anyopaque) callconv(w.WINAPI) void {} fn OnVoiceError(_: *Self, _: ?*anyopaque, _: w.HRESULT) callconv(w.WINAPI) void {} }; var stop_on_buffer_end_vcb: StopOnBufferEnd_VoiceCallback = .{}; pub const AudioContext = struct { device: *xaudio2.IXAudio2, master_voice: *xaudio2.IMasteringVoice, source_voices: std.ArrayList(*xaudio2.ISourceVoice), pub fn init(allocator: std.mem.Allocator) AudioContext { const device = blk: { var device: ?*xaudio2.IXAudio2 = null; hrPanicOnFail(xaudio2.create(&device, if (enable_dx_debug) xaudio2.DEBUG_ENGINE else 0, 0)); break :blk device.?; }; if (enable_dx_debug) { device.SetDebugConfiguration(&.{ .TraceMask = xaudio2.LOG_ERRORS | xaudio2.LOG_WARNINGS | xaudio2.LOG_INFO, .BreakMask = 0, .LogThreadID = w.TRUE, .LogFileline = w.FALSE, .LogFunctionName = w.FALSE, .LogTiming = w.FALSE, }, null); } const master_voice = blk: { var voice: ?*xaudio2.IMasteringVoice = null; hrPanicOnFail(device.CreateMasteringVoice( &voice, xaudio2.DEFAULT_CHANNELS, xaudio2.DEFAULT_SAMPLERATE, 0, null, null, .GameEffects, )); break :blk voice.?; }; var source_voices = std.ArrayList(*xaudio2.ISourceVoice).init(allocator); { var i: u32 = 0; while (i < 32) : (i += 1) { var voice: ?*xaudio2.ISourceVoice = null; hrPanicOnFail(device.CreateSourceVoice( &voice, &optimal_voice_format, 0, xaudio2.DEFAULT_FREQ_RATIO, @ptrCast(*xaudio2.IVoiceCallback, &stop_on_buffer_end_vcb), null, null, )); source_voices.append(voice.?) catch unreachable; } } hrPanicOnFail(mf.MFStartup(mf.VERSION, 0)); return .{ .device = device, .master_voice = master_voice, .source_voices = source_voices, }; } pub fn deinit(audio: *AudioContext) void { audio.device.StopEngine(); hrPanicOnFail(mf.MFShutdown()); for (audio.source_voices.items) |voice| { voice.DestroyVoice(); } audio.source_voices.deinit(); audio.master_voice.DestroyVoice(); _ = audio.device.Release(); audio.* = undefined; } pub fn getSourceVoice(audio: *AudioContext) *xaudio2.ISourceVoice { const idle_voice = blk: { for (audio.source_voices.items) |voice| { var state: xaudio2.VOICE_STATE = undefined; voice.GetState(&state, xaudio2.VOICE_NOSAMPLESPLAYED); if (state.BuffersQueued == 0) { break :blk voice; } } var voice: ?*xaudio2.ISourceVoice = null; hrPanicOnFail(audio.device.CreateSourceVoice( &voice, &optimal_voice_format, 0, xaudio2.DEFAULT_FREQ_RATIO, @ptrCast(*xaudio2.IVoiceCallback, &stop_on_buffer_end_vcb), null, null, )); audio.source_voices.append(voice.?) catch unreachable; break :blk voice.?; }; // Reset voice state hrPanicOnFail(idle_voice.SetEffectChain(null)); hrPanicOnFail(idle_voice.SetVolume(1.0)); hrPanicOnFail(idle_voice.SetSourceSampleRate(optimal_voice_format.nSamplesPerSec)); hrPanicOnFail(idle_voice.SetChannelVolumes(1, &[1]f32{1.0}, xaudio2.COMMIT_NOW)); hrPanicOnFail(idle_voice.SetFrequencyRatio(1.0, xaudio2.COMMIT_NOW)); return idle_voice; } pub fn playBuffer(audio: *AudioContext, buffer: Buffer) void { const voice = audio.getSourceVoice(); submitBuffer(voice, buffer); hrPanicOnFail(voice.Start(0, xaudio2.COMMIT_NOW)); } }; pub const Buffer = struct { data: []const u8, play_begin: u32 = 0, play_length: u32 = 0, loop_begin: u32 = 0, loop_length: u32 = 0, loop_count: u32 = 0, }; pub const Stream = struct { critical_section: w.CRITICAL_SECTION, allocator: std.mem.Allocator, voice: *xaudio2.ISourceVoice, voice_cb: *VoiceCallback, reader: *mf.ISourceReader, reader_cb: *SourceReaderCallback, pub fn create(allocator: std.mem.Allocator, device: *xaudio2.IXAudio2, file_path: [:0]const u16) *Stream { const voice_cb = blk: { var cb = allocator.create(VoiceCallback) catch unreachable; cb.* = VoiceCallback.init(); break :blk cb; }; var cs: w.CRITICAL_SECTION = undefined; w.kernel32.InitializeCriticalSection(&cs); const source_reader_cb = blk: { var cb = allocator.create(SourceReaderCallback) catch unreachable; cb.* = SourceReaderCallback.init(allocator); break :blk cb; }; var sample_rate: u32 = 0; const source_reader = blk: { var attribs: *mf.IAttributes = undefined; hrPanicOnFail(mf.MFCreateAttributes(&attribs, 1)); defer _ = attribs.Release(); hrPanicOnFail(attribs.SetUnknown( &mf.SOURCE_READER_ASYNC_CALLBACK, @ptrCast(*w.IUnknown, source_reader_cb), )); var source_reader: *mf.ISourceReader = undefined; hrPanicOnFail(mf.MFCreateSourceReaderFromURL(file_path, attribs, &source_reader)); var media_type: *mf.IMediaType = undefined; hrPanicOnFail(source_reader.GetNativeMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, &media_type)); defer _ = media_type.Release(); hrPanicOnFail(media_type.GetUINT32(&mf.MT_AUDIO_SAMPLES_PER_SECOND, &sample_rate)); hrPanicOnFail(media_type.SetGUID(&mf.MT_MAJOR_TYPE, &mf.MediaType_Audio)); hrPanicOnFail(media_type.SetGUID(&mf.MT_SUBTYPE, &mf.AudioFormat_PCM)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_NUM_CHANNELS, 2)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_SAMPLES_PER_SECOND, sample_rate)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_BITS_PER_SAMPLE, 16)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_BLOCK_ALIGNMENT, 4)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_AVG_BYTES_PER_SECOND, 4 * sample_rate)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_ALL_SAMPLES_INDEPENDENT, w.TRUE)); hrPanicOnFail(source_reader.SetCurrentMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, null, media_type)); break :blk source_reader; }; assert(sample_rate != 0); const voice = blk: { var voice: ?*xaudio2.ISourceVoice = null; hrPanicOnFail(device.CreateSourceVoice(&voice, &.{ .wFormatTag = wasapi.WAVE_FORMAT_PCM, .nChannels = 2, .nSamplesPerSec = sample_rate, .nAvgBytesPerSec = 4 * sample_rate, .nBlockAlign = 4, .wBitsPerSample = 16, .cbSize = @sizeOf(wasapi.WAVEFORMATEX), }, 0, xaudio2.DEFAULT_FREQ_RATIO, @ptrCast(*xaudio2.IVoiceCallback, voice_cb), null, null)); break :blk voice.?; }; var stream = allocator.create(Stream) catch unreachable; stream.* = .{ .critical_section = cs, .allocator = allocator, .voice = voice, .voice_cb = voice_cb, .reader = source_reader, .reader_cb = source_reader_cb, }; voice_cb.stream = stream; source_reader_cb.stream = stream; // Start async loading/decoding hrPanicOnFail(source_reader.ReadSample(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, null, null, null, null)); hrPanicOnFail(source_reader.ReadSample(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, null, null, null, null)); return stream; } pub fn destroy(stream: *Stream) void { { const refcount = stream.reader.Release(); assert(refcount == 0); } { const refcount = stream.reader_cb.Release(); assert(refcount == 0); } w.kernel32.DeleteCriticalSection(&stream.critical_section); stream.voice.DestroyVoice(); stream.allocator.destroy(stream.voice_cb); stream.allocator.destroy(stream); } pub fn setCurrentPosition(stream: *Stream, position: i64) void { w.kernel32.EnterCriticalSection(&stream.critical_section); defer w.kernel32.LeaveCriticalSection(&stream.critical_section); const pos = w.PROPVARIANT{ .vt = w.VT_I8, .u = .{ .hVal = position } }; hrPanicOnFail(stream.reader.SetCurrentPosition(&w.GUID_NULL, &pos)); hrPanicOnFail(stream.reader.ReadSample( mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, null, null, null, null, )); } fn onBufferEnd(stream: *Stream, buffer: *mf.IMediaBuffer) void { w.kernel32.EnterCriticalSection(&stream.critical_section); defer w.kernel32.LeaveCriticalSection(&stream.critical_section); hrPanicOnFail(buffer.Unlock()); const refcount = buffer.Release(); assert(refcount == 0); // Request new audio buffer hrPanicOnFail(stream.reader.ReadSample(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, null, null, null, null)); } fn onReadSample( stream: *Stream, status: w.HRESULT, _: w.DWORD, stream_flags: w.DWORD, _: w.LONGLONG, sample: ?*mf.ISample, ) void { w.kernel32.EnterCriticalSection(&stream.critical_section); defer w.kernel32.LeaveCriticalSection(&stream.critical_section); if ((stream_flags & mf.SOURCE_READERF_ENDOFSTREAM) != 0) { setCurrentPosition(stream, 0); return; } if (status != w.S_OK or sample == null) { return; } var buffer: *mf.IMediaBuffer = undefined; hrPanicOnFail(sample.?.ConvertToContiguousBuffer(&buffer)); var data_ptr: [*]u8 = undefined; var data_len: u32 = 0; hrPanicOnFail(buffer.Lock(&data_ptr, null, &data_len)); // Submit decoded buffer hrPanicOnFail(stream.voice.SubmitSourceBuffer(&.{ .Flags = 0, .AudioBytes = data_len, .pAudioData = data_ptr, .PlayBegin = 0, .PlayLength = 0, .LoopBegin = 0, .LoopLength = 0, .LoopCount = 0, .pContext = buffer, // Store pointer to the buffer so that we can release it in onBufferEnd() }, null)); } const VoiceCallback = struct { vtable: *const xaudio2.IVoiceCallbackVTable(VoiceCallback) = &vtable_voice_cb, stream: ?*Stream, fn init() VoiceCallback { return .{ .stream = null }; } fn OnBufferEnd(voice_cb: *VoiceCallback, context: ?*anyopaque) callconv(w.WINAPI) void { voice_cb.stream.?.onBufferEnd(@ptrCast(*mf.IMediaBuffer, @alignCast(8, context))); } const vtable_voice_cb = xaudio2.IVoiceCallbackVTable(VoiceCallback){ .vcb = .{ .OnVoiceProcessingPassStart = VoiceCallback.OnVoiceProcessingPassStart, .OnVoiceProcessingPassEnd = VoiceCallback.OnVoiceProcessingPassEnd, .OnStreamEnd = VoiceCallback.OnStreamEnd, .OnBufferStart = VoiceCallback.OnBufferStart, .OnBufferEnd = VoiceCallback.OnBufferEnd, .OnLoopEnd = VoiceCallback.OnLoopEnd, .OnVoiceError = VoiceCallback.OnVoiceError, }, }; fn OnVoiceProcessingPassStart(_: *VoiceCallback, _: w.UINT32) callconv(w.WINAPI) void {} fn OnVoiceProcessingPassEnd(_: *VoiceCallback) callconv(w.WINAPI) void {} fn OnStreamEnd(_: *VoiceCallback) callconv(w.WINAPI) void {} fn OnBufferStart(_: *VoiceCallback, _: ?*anyopaque) callconv(w.WINAPI) void {} fn OnLoopEnd(_: *VoiceCallback, _: ?*anyopaque) callconv(w.WINAPI) void {} fn OnVoiceError(_: *VoiceCallback, _: ?*anyopaque, _: w.HRESULT) callconv(w.WINAPI) void {} }; const SourceReaderCallback = struct { vtable: *const mf.ISourceReaderCallbackVTable(SourceReaderCallback) = &vtable_source_reader_cb, refcount: u32 = 1, allocator: std.mem.Allocator, stream: ?*Stream, fn init(allocator: std.mem.Allocator) SourceReaderCallback { return .{ .allocator = allocator, .stream = null, }; } const vtable_source_reader_cb = mf.ISourceReaderCallbackVTable(SourceReaderCallback){ .unknown = .{ .QueryInterface = SourceReaderCallback.QueryInterface, .AddRef = SourceReaderCallback.AddRef, .Release = SourceReaderCallback.Release, }, .cb = .{ .OnReadSample = SourceReaderCallback.OnReadSample, .OnFlush = SourceReaderCallback.OnFlush, .OnEvent = SourceReaderCallback.OnEvent, }, }; fn QueryInterface( source_reader_cb: *SourceReaderCallback, guid: *const w.GUID, outobj: ?*?*anyopaque, ) callconv(w.WINAPI) w.HRESULT { assert(outobj != null); if (std.mem.eql(u8, std.mem.asBytes(guid), std.mem.asBytes(&w.IID_IUnknown))) { outobj.?.* = source_reader_cb; _ = source_reader_cb.AddRef(); return w.S_OK; } else if (std.mem.eql(u8, std.mem.asBytes(guid), std.mem.asBytes(&mf.IID_ISourceReaderCallback))) { outobj.?.* = source_reader_cb; _ = source_reader_cb.AddRef(); return w.S_OK; } outobj.?.* = null; return w.E_NOINTERFACE; } fn AddRef(source_reader_cb: *SourceReaderCallback) callconv(w.WINAPI) w.ULONG { const prev_refcount = @atomicRmw(u32, &source_reader_cb.refcount, .Add, 1, .Monotonic); return prev_refcount + 1; } fn Release(source_reader_cb: *SourceReaderCallback) callconv(w.WINAPI) w.ULONG { const prev_refcount = @atomicRmw(u32, &source_reader_cb.refcount, .Sub, 1, .Monotonic); assert(prev_refcount > 0); if (prev_refcount == 1) { source_reader_cb.allocator.destroy(source_reader_cb); } return prev_refcount - 1; } fn OnReadSample( source_reader_cb: *SourceReaderCallback, status: w.HRESULT, stream_index: w.DWORD, stream_flags: w.DWORD, timestamp: w.LONGLONG, sample: ?*mf.ISample, ) callconv(w.WINAPI) w.HRESULT { source_reader_cb.stream.?.onReadSample(status, stream_index, stream_flags, timestamp, sample); return w.S_OK; } fn OnFlush(_: *SourceReaderCallback, _: w.DWORD) callconv(w.WINAPI) w.HRESULT { return w.S_OK; } fn OnEvent(_: *SourceReaderCallback, _: w.DWORD, _: *mf.IMediaEvent) callconv(w.WINAPI) w.HRESULT { return w.S_OK; } }; }; pub fn loadBufferData(allocator: std.mem.Allocator, audio_file_path: [:0]const u16) []const u8 { var source_reader: *mf.ISourceReader = undefined; hrPanicOnFail(mf.MFCreateSourceReaderFromURL(audio_file_path, null, &source_reader)); defer _ = source_reader.Release(); var media_type: *mf.IMediaType = undefined; hrPanicOnFail(source_reader.GetNativeMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, &media_type)); defer _ = media_type.Release(); hrPanicOnFail(media_type.SetGUID(&mf.MT_MAJOR_TYPE, &mf.MediaType_Audio)); hrPanicOnFail(media_type.SetGUID(&mf.MT_SUBTYPE, &mf.AudioFormat_PCM)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_NUM_CHANNELS, optimal_voice_format.nChannels)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_SAMPLES_PER_SECOND, optimal_voice_format.nSamplesPerSec)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_BITS_PER_SAMPLE, optimal_voice_format.wBitsPerSample)); hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_BLOCK_ALIGNMENT, optimal_voice_format.nBlockAlign)); hrPanicOnFail(media_type.SetUINT32( &mf.MT_AUDIO_AVG_BYTES_PER_SECOND, optimal_voice_format.nBlockAlign * optimal_voice_format.nSamplesPerSec, )); hrPanicOnFail(media_type.SetUINT32(&mf.MT_ALL_SAMPLES_INDEPENDENT, w.TRUE)); hrPanicOnFail(source_reader.SetCurrentMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, null, media_type)); var data = std.ArrayList(u8).init(allocator); while (true) { var flags: w.DWORD = 0; var sample: ?*mf.ISample = null; defer { if (sample) |s| _ = s.Release(); } hrPanicOnFail(source_reader.ReadSample(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, null, &flags, null, &sample)); if ((flags & mf.SOURCE_READERF_ENDOFSTREAM) != 0) { break; } var buffer: *mf.IMediaBuffer = undefined; hrPanicOnFail(sample.?.ConvertToContiguousBuffer(&buffer)); defer _ = buffer.Release(); var data_ptr: [*]u8 = undefined; var data_len: u32 = 0; hrPanicOnFail(buffer.Lock(&data_ptr, null, &data_len)); data.appendSlice(data_ptr[0..data_len]) catch unreachable; hrPanicOnFail(buffer.Unlock()); } return data.toOwnedSlice(); } pub fn submitBuffer(voice: *xaudio2.ISourceVoice, buffer: Buffer) void { hrPanicOnFail(voice.SubmitSourceBuffer(&.{ .Flags = xaudio2.END_OF_STREAM, .AudioBytes = @intCast(u32, buffer.data.len), .pAudioData = buffer.data.ptr, .PlayBegin = buffer.play_begin, .PlayLength = buffer.play_length, .LoopBegin = buffer.loop_begin, .LoopLength = buffer.loop_length, .LoopCount = buffer.loop_count, .pContext = voice, }, null)); } const SimpleAudioProcessor = extern struct { v: *const xapo.IXAPOVTable(SimpleAudioProcessor) = &vtable, refcount: u32 = 1, is_locked: bool = false, num_channels: u16 = 0, process: *const fn ([]f32, u32, ?*anyopaque) void, context: ?*anyopaque, const Self = @This(); const vtable = xapo.IXAPOVTable(SimpleAudioProcessor){ .unknown = .{ .QueryInterface = QueryInterface, .AddRef = AddRef, .Release = Release, }, .xapo = .{ .GetRegistrationProperties = GetRegistrationProperties, .IsInputFormatSupported = IsInputFormatSupported, .IsOutputFormatSupported = IsOutputFormatSupported, .Initialize = Initialize, .Reset = Reset, .LockForProcess = LockForProcess, .UnlockForProcess = UnlockForProcess, .Process = Process, .CalcInputFrames = CalcInputFrames, .CalcOutputFrames = CalcOutputFrames, }, }; const info = xapo.REGISTRATION_PROPERTIES{ .clsid = w.GUID_NULL, .FriendlyName = [_]w.WCHAR{0} ** xapo.REGISTRATION_STRING_LENGTH, .CopyrightInfo = [_]w.WCHAR{0} ** xapo.REGISTRATION_STRING_LENGTH, .MajorVersion = 1, .MinorVersion = 0, .Flags = xapo.FLAG_CHANNELS_MUST_MATCH | xapo.FLAG_FRAMERATE_MUST_MATCH | xapo.FLAG_BITSPERSAMPLE_MUST_MATCH | xapo.FLAG_BUFFERCOUNT_MUST_MATCH | xapo.FLAG_INPLACE_SUPPORTED | xapo.FLAG_INPLACE_REQUIRED, .MinInputBufferCount = 1, .MaxInputBufferCount = 1, .MinOutputBufferCount = 1, .MaxOutputBufferCount = 1, }; fn QueryInterface( self: *Self, guid: *const w.GUID, outobj: ?*?*anyopaque, ) callconv(w.WINAPI) w.HRESULT { assert(outobj != null); if (std.mem.eql(u8, std.mem.asBytes(guid), std.mem.asBytes(&w.IID_IUnknown))) { outobj.?.* = self; _ = self.AddRef(); return w.S_OK; } else if (std.mem.eql(u8, std.mem.asBytes(guid), std.mem.asBytes(&xapo.IID_IXAPO))) { outobj.?.* = self; _ = self.AddRef(); return w.S_OK; } outobj.?.* = null; return w.E_NOINTERFACE; } fn AddRef(self: *Self) callconv(w.WINAPI) w.ULONG { return @atomicRmw(u32, &self.refcount, .Add, 1, .Monotonic) + 1; } fn Release(self: *Self) callconv(w.WINAPI) w.ULONG { const prev_refcount = @atomicRmw(u32, &self.refcount, .Sub, 1, .Monotonic); if (prev_refcount == 1) { w.ole32.CoTaskMemFree(self); } return prev_refcount - 1; } fn GetRegistrationProperties( _: *Self, props: **xapo.REGISTRATION_PROPERTIES, ) callconv(w.WINAPI) w.HRESULT { const ptr = w.CoTaskMemAlloc(@sizeOf(xapo.REGISTRATION_PROPERTIES)); if (ptr != null) { props.* = @ptrCast(*xapo.REGISTRATION_PROPERTIES, @alignCast(8, ptr.?)); props.*.* = info; return w.S_OK; } return w.E_FAIL; } fn IsInputFormatSupported( _: *Self, _: *const WAVEFORMATEX, requested_input_format: *const WAVEFORMATEX, supported_input_format: ?**WAVEFORMATEX, ) callconv(w.WINAPI) w.HRESULT { if (requested_input_format.wFormatTag != wasapi.WAVE_FORMAT_IEEE_FLOAT or requested_input_format.nChannels < xapo.MIN_CHANNELS or requested_input_format.nChannels > xapo.MAX_CHANNELS or requested_input_format.nSamplesPerSec < xapo.MIN_FRAMERATE or requested_input_format.nSamplesPerSec > xapo.MAX_FRAMERATE or requested_input_format.wBitsPerSample != 32) { if (supported_input_format != null) { supported_input_format.?.*.wFormatTag = wasapi.WAVE_FORMAT_IEEE_FLOAT; supported_input_format.?.*.wBitsPerSample = 32; supported_input_format.?.*.nChannels = std.math.clamp( requested_input_format.nChannels, @intCast(u16, xapo.MIN_CHANNELS), @intCast(u16, xapo.MAX_CHANNELS), ); supported_input_format.?.*.nSamplesPerSec = std.math.clamp( requested_input_format.nSamplesPerSec, xapo.MIN_FRAMERATE, xapo.MAX_FRAMERATE, ); } return xapo.E_FORMAT_UNSUPPORTED; } return w.S_OK; } fn IsOutputFormatSupported( _: *Self, _: *const WAVEFORMATEX, requested_output_format: *const WAVEFORMATEX, supported_output_format: ?**WAVEFORMATEX, ) callconv(w.WINAPI) w.HRESULT { if (requested_output_format.wFormatTag != wasapi.WAVE_FORMAT_IEEE_FLOAT or requested_output_format.nChannels < xapo.MIN_CHANNELS or requested_output_format.nChannels > xapo.MAX_CHANNELS or requested_output_format.nSamplesPerSec < xapo.MIN_FRAMERATE or requested_output_format.nSamplesPerSec > xapo.MAX_FRAMERATE or requested_output_format.wBitsPerSample != 32) { if (supported_output_format != null) { supported_output_format.?.*.wFormatTag = wasapi.WAVE_FORMAT_IEEE_FLOAT; supported_output_format.?.*.wBitsPerSample = 32; supported_output_format.?.*.nChannels = std.math.clamp( requested_output_format.nChannels, @intCast(u16, xapo.MIN_CHANNELS), @intCast(u16, xapo.MAX_CHANNELS), ); supported_output_format.?.*.nSamplesPerSec = std.math.clamp( requested_output_format.nSamplesPerSec, xapo.MIN_FRAMERATE, xapo.MAX_FRAMERATE, ); } return xapo.E_FORMAT_UNSUPPORTED; } return w.S_OK; } fn Initialize(_: *Self, data: ?*const anyopaque, data_size: w.UINT32) callconv(w.WINAPI) w.HRESULT { _ = data; _ = data_size; return w.S_OK; } fn Reset(_: *Self) callconv(w.WINAPI) void {} fn LockForProcess( self: *Self, num_input_params: w.UINT32, input_params: ?[*]const xapo.LOCKFORPROCESS_BUFFER_PARAMETERS, num_output_params: w.UINT32, output_params: ?[*]const xapo.LOCKFORPROCESS_BUFFER_PARAMETERS, ) callconv(w.WINAPI) w.HRESULT { assert(self.is_locked == false); assert(num_input_params == 1 and num_output_params == 1); assert(input_params != null and output_params != null); assert(input_params.?[0].pFormat.wFormatTag == output_params.?[0].pFormat.wFormatTag); assert(input_params.?[0].pFormat.nChannels == output_params.?[0].pFormat.nChannels); assert(input_params.?[0].pFormat.nSamplesPerSec == output_params.?[0].pFormat.nSamplesPerSec); assert(input_params.?[0].pFormat.wBitsPerSample == output_params.?[0].pFormat.wBitsPerSample); assert(input_params.?[0].pFormat.wBitsPerSample == 32); self.num_channels = input_params.?[0].pFormat.nChannels; self.is_locked = true; return w.S_OK; } fn UnlockForProcess(self: *Self) callconv(w.WINAPI) void { assert(self.is_locked == true); self.num_channels = 0; self.is_locked = false; } fn Process( self: *Self, num_input_params: w.UINT32, input_params: ?[*]const xapo.PROCESS_BUFFER_PARAMETERS, num_output_params: w.UINT32, output_params: ?[*]xapo.PROCESS_BUFFER_PARAMETERS, is_enabled: w.BOOL, ) callconv(w.WINAPI) void { assert(self.is_locked and self.num_channels > 0); assert(num_input_params == 1 and num_output_params == 1); assert(input_params != null and output_params != null); assert(input_params.?[0].pBuffer == output_params.?[0].pBuffer); if (is_enabled == w.TRUE) { var samples = @ptrCast([*]f32, @alignCast(16, input_params.?[0].pBuffer)); // XAudio2 aligns data to 16. const num_samples = input_params.?[0].ValidFrameCount * self.num_channels; self.process.*( samples[0..num_samples], if (input_params.?[0].BufferFlags == .VALID) self.num_channels else 0, self.context, ); } output_params.?[0].ValidFrameCount = input_params.?[0].ValidFrameCount; output_params.?[0].BufferFlags = input_params.?[0].BufferFlags; } fn CalcInputFrames(_: *Self, num_output_frames: w.UINT32) callconv(w.WINAPI) w.UINT32 { return num_output_frames; } fn CalcOutputFrames(_: *Self, num_input_frames: w.UINT32) callconv(w.WINAPI) w.UINT32 { return num_input_frames; } }; pub fn createSimpleProcessor( process: *const fn ([]f32, u32, ?*anyopaque) void, context: ?*anyopaque, ) *w.IUnknown { const ptr = w.CoTaskMemAlloc(@sizeOf(SimpleAudioProcessor)).?; const comptr = @ptrCast(*SimpleAudioProcessor, @alignCast(8, ptr)); comptr.* = .{ .process = process, .context = context, }; return @ptrCast(*w.IUnknown, comptr); }
libs/zxaudio2/src/zxaudio2.zig
const std = @import("std"); const Builder = std.build.Builder; const Pkg = std.build.Pkg; const Day = struct { dir: []const u8, packages: ?[]const Pkg, }; // my packages const pkg_numtheory = Pkg{ .name = "numtheory", .path = .{ .path = "share/zig/numtheory.zig" } }; const pkg_combination = Pkg{ .name = "combination", .path = .{ .path = "share/zig/combination.zig" } }; const pkg_intcode = Pkg{ .name = "intcode", .path = .{ .path = "share/zig/intcode.zig" } }; // would be nice if this could be inlined const arr_numtheory = [_]Pkg{pkg_numtheory}; const arr_intcode = [_]Pkg{pkg_intcode}; const arr_intcode_combination = [_]Pkg{ pkg_intcode, pkg_combination }; const days = [_]Day{ .{ .dir = "day22", .packages = arr_numtheory[0..], }, .{ .dir = "day23", .packages = arr_intcode[0..], }, .{ .dir = "day24", .packages = null, }, .{ .dir = "day25", .packages = arr_intcode_combination[0..], }, }; pub fn build(b: *Builder) !void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const allocator = b.allocator; const test_step = b.step("test", "Run library tests"); // add intcode var intcode_tests = b.addTest("share/zig/intcode.zig"); intcode_tests.setBuildMode(mode); test_step.dependOn(&intcode_tests.step); for (days) |d| { const main_zig = try std.fmt.allocPrint(allocator, "{s}/src/main.zig", .{d.dir}); const exe = b.addExecutable(d.dir, main_zig); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step(d.dir, d.dir); run_step.dependOn(&run_cmd.step); var tests = b.addTest(main_zig); tests.setBuildMode(mode); test_step.dependOn(&tests.step); if (d.packages) |packages| { for (packages) |p| { exe.addPackage(p); tests.addPackage(p); } } } }
build.zig
const std = @import("std"); const print = std.debug.print; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const Pair = struct { first: usize, second: usize }; const DataList = std.ArrayList(Pair); pub fn main() !void { defer _ = gpa.deinit(); const inputData = try std.fs.cwd().readFileAlloc(alloc, "input", std.math.maxInt(u64)); defer alloc.free(inputData); const p1 = part1(inputData); const p2 = part2(inputData); std.debug.print("{}\n", .{p1}); std.debug.print("{}\n", .{p2}); } fn sort_times(ctx: void, lhs: Pair, rhs: Pair) bool { return lhs.second < rhs.second; } fn part1(inputData: []const u8) !usize { var times_list = DataList.init(alloc); defer times_list.deinit(); var lines = std.mem.split(inputData, "\n"); const cur_time = try std.fmt.parseInt(usize, lines.next().?, 10); var busses = std.mem.split(lines.next().?, ","); while (busses.next()) |bus_str| { if (std.mem.eql(u8, bus_str, "x")) { continue; } const bus = try std.fmt.parseInt(usize, bus_str, 10); const time_left = bus - @mod(cur_time, bus); try times_list.append(.{ .first = bus, .second = time_left }); } std.sort.sort(Pair, times_list.items, {}, sort_times); return times_list.items[0].first * times_list.items[0].second; } // here "second" is the relative position fn part2(inputData: []const u8) !usize { var times_list = DataList.init(alloc); defer times_list.deinit(); var lines = std.mem.split(inputData, "\n"); const cur_time = try std.fmt.parseInt(usize, lines.next().?, 10); // unused for p2 var busses = std.mem.split(lines.next().?, ","); var rel_pos: usize = 0; while (busses.next()) |bus_str| : (rel_pos += 1) { if (std.mem.eql(u8, bus_str, "x")) { continue; } const bus = try std.fmt.parseInt(usize, bus_str, 10); try times_list.append(.{ .first = bus, .second = rel_pos }); } std.sort.sort(Pair, times_list.items, {}, sort_desc_by_period); const max = times_list.items[0].first; const max_offset = times_list.items[0].second; var timestamp = 2 * max - max_offset; // start from some value > 0 that satisfies n0 var prev_ts: usize = timestamp; var step: usize = max; for (times_list.items[1..]) |item| { while ((timestamp + item.second) % item.first != 0) { timestamp += step; } step *= item.first; } return timestamp; } fn sort_desc_by_period(ctx: void, lhs: Pair, rhs: Pair) bool { return lhs.first > rhs.first; }
Day13/day13.zig
const subo = @import("subo.zig"); const std = @import("std"); const testing = std.testing; const math = std.math; fn test__suboti4(a: i128, b: i128) !void { var result_ov: c_int = undefined; var expected_ov: c_int = undefined; var result = subo.__suboti4(a, b, &result_ov); var expected: i128 = simple_suboti4(a, b, &expected_ov); try testing.expectEqual(expected, result); try testing.expectEqual(expected_ov, result_ov); } // 2 cases on evaluating `a-b`: // 1. `a-b` may underflow, iff b>0 && a<0 and a-b < min <=> a<min+b // 2. `a-b` may overflow, iff b<0 && a>0 and a-b > max <=> a>max+b // `-b` evaluation may overflow, iff b==min, but this is handled by the hardware pub fn simple_suboti4(a: i128, b: i128, overflow: *c_int) i128 { overflow.* = 0; const min: i128 = math.minInt(i128); const max: i128 = math.maxInt(i128); if (((b > 0) and (a < min + b)) or ((b < 0) and (a > max + b))) overflow.* = 1; return a -% b; } test "suboti3" { const min: i128 = math.minInt(i128); const max: i128 = math.maxInt(i128); var i: i128 = 1; while (i < max) : (i *|= 2) { try test__suboti4(i, i); try test__suboti4(-i, -i); try test__suboti4(i, -i); try test__suboti4(-i, i); } // edge cases // 0 - 0 = 0 // MIN - MIN = 0 // MAX - MAX = 0 // 0 - MIN overflow // 0 - MAX = MIN+1 // MIN - 0 = MIN // MAX - 0 = MAX // MIN - MAX overflow // MAX - MIN overflow try test__suboti4(0, 0); try test__suboti4(min, min); try test__suboti4(max, max); try test__suboti4(0, min); try test__suboti4(0, max); try test__suboti4(min, 0); try test__suboti4(max, 0); try test__suboti4(min, max); try test__suboti4(max, min); // derived edge cases // MIN+1 - MIN = 1 // MAX-1 - MAX = -1 // 1 - MIN overflow // -1 - MIN = MAX // -1 - MAX = MIN // +1 - MAX = MIN+2 // MIN - 1 overflow // MIN - -1 = MIN+1 // MAX - 1 = MAX-1 // MAX - -1 overflow try test__suboti4(min + 1, min); try test__suboti4(max - 1, max); try test__suboti4(1, min); try test__suboti4(-1, min); try test__suboti4(-1, max); try test__suboti4(1, max); try test__suboti4(min, 1); try test__suboti4(min, -1); try test__suboti4(max, -1); try test__suboti4(max, 1); }
lib/std/special/compiler_rt/suboti4_test.zig
const std = @import("std"); const pcx = @import("pcx.zig"); const argsParser = @import("args"); pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, output: ?[]const u8 = null, pub const shorthands = .{ .h = "help", .o = "output", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); if (cli_args.options.help or cli_args.positionals.len != 1) { try std.io.getStdOut().writer().writeAll( \\bit-converter --help [--output file] pcx-file \\Converts a PCX file into a bit-bang sequence for the \\ \\-h, --help Displays this help text. \\-o, --output Defines the name of the output file. If not given, \\ the bit-converter will write the bit sequence to stdout. \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var file = try std.fs.cwd().openFile(cli_args.positionals[0], .{ .read = true, .write = false }); defer file.close(); var img = try pcx.load(std.heap.page_allocator, &file); defer img.deinit(); if (img != .bpp8) { try std.io.getStdErr().writer().print("The provided file is not a file with 8 bit per pixel, but uses the format {}!\n", .{ @as(pcx.Format, img), }); return 1; } var out = if (cli_args.options.output) |outfile| try std.fs.cwd().createFile(outfile, .{ .truncate = true }) else std.io.getStdOut(); defer if (cli_args.options.output) |_| out.close(); var ostream = out.writer(); var y: usize = 0; while (y < 128) : (y += 1) { var x: usize = 0; while (x < 256) : (x += 1) { try ostream.writeIntLittle(u8, 'B'); try ostream.writeIntLittle(u24, 0x810000 | @intCast(u24, y << 8) | @intCast(u24, x)); try ostream.writeIntLittle(u8, img.bpp8.pixels[y * img.bpp8.width + x]); } } return 0; }
tools/bit-loader/main.zig
const x86_64 = @import("../../index.zig"); const bitjuggle = @import("bitjuggle"); const std = @import("std"); const PageTableIndex = x86_64.structures.paging.PageTableIndex; const SIZE_4KiB_STR: []const u8 = "4KiB"; const SIZE_2MiB_STR: []const u8 = "2MiB"; const SIZE_1GiB_STR: []const u8 = "1GiB"; pub const PageSize = enum { Size4KiB, Size2MiB, Size1GiB, pub fn bytes(self: PageSize) u64 { return switch (self) { .Size4KiB => 4096, .Size2MiB => 4096 * 512, .Size1GiB => 4096 * 512 * 512, }; } pub fn sizeString(self: PageSize) []const u8 { return switch (self) { .Size4KiB => SIZE_4KiB_STR, .Size2MiB => SIZE_2MiB_STR, .Size1GiB => SIZE_1GiB_STR, }; } pub fn isGiantPage(self: PageSize) bool { return self == .Size1GiB; } }; /// A virtual memory page. Page size 4 KiB pub const Page = extern struct { const page_size = PageSize.Size4KiB; const bytes: u64 = page_size.bytes(); start_address: x86_64.VirtAddr, /// Returns the page that starts at the given virtual address. /// /// Returns an error if the address is not correctly aligned (i.e. is not a valid page start). pub fn fromStartAddress(address: x86_64.VirtAddr) PageError!Page { if (!address.isAligned(page_size.bytes())) { return PageError.AddressNotAligned; } return containingAddress(address); } /// Returns the page that starts at the given virtual address. pub fn fromStartAddressUnchecked(address: x86_64.VirtAddr) Page { return .{ .start_address = address }; } /// Returns the page that contains the given virtual address. pub fn containingAddress(address: x86_64.VirtAddr) Page { return .{ .start_address = address.alignDown(page_size.bytes()) }; } /// Returns the level 4 page table index of this page. pub fn p4Index(self: Page) PageTableIndex { return self.start_address.p4Index(); } /// Returns the level 3 page table index of this page. pub fn p3Index(self: Page) PageTableIndex { return self.start_address.p3Index(); } /// Returns the level 2 page table index of this page. pub fn p2Index(self: Page) PageTableIndex { return self.start_address.p2Index(); } /// Returns the level 1 page table index of this page. pub fn p1Index(self: Page) PageTableIndex { return self.start_address.p1Index(); } pub fn format(value: Page, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; try writer.print("Page[" ++ page_size.sizeString() ++ "](0x{x})", .{value.start_address.value}); } comptime { std.testing.refAllDecls(@This()); } }; /// A virtual memory page. Page size 2 MiB pub const Page2MiB = extern struct { const page_size = PageSize.Size2MiB; const bytes: u64 = page_size.bytes(); start_address: x86_64.VirtAddr, /// Returns the page that starts at the given virtual address. /// /// Returns an error if the address is not correctly aligned (i.e. is not a valid page start). pub fn fromStartAddress(address: x86_64.VirtAddr) PageError!Page2MiB { if (!address.isAligned(page_size.bytes())) { return PageError.AddressNotAligned; } return containingAddress(address); } /// Returns the page that starts at the given virtual address. pub fn fromStartAddressUnchecked(address: x86_64.VirtAddr) Page2MiB { return .{ .start_address = address }; } /// Returns the page that contains the given virtual address. pub fn containingAddress(address: x86_64.VirtAddr) Page2MiB { return .{ .start_address = address.alignDown(page_size.bytes()) }; } /// Returns the level 4 page table index of this page. pub fn p4Index(self: Page2MiB) PageTableIndex { return self.start_address.p4Index(); } /// Returns the level 3 page table index of this page. pub fn p3Index(self: Page2MiB) PageTableIndex { return self.start_address.p3Index(); } /// Returns the level 2 page table index of this page. pub fn p2Index(self: Page2MiB) PageTableIndex { return self.start_address.p2Index(); } pub fn format(value: Page2MiB, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; try writer.print("Page[" ++ page_size.sizeString() ++ "](0x{x})", .{value.start_address.value}); } comptime { std.testing.refAllDecls(@This()); } }; /// A virtual memory page. Page size 1 GiB pub const Page1GiB = extern struct { const page_size = PageSize.Size1GiB; const bytes: u64 = page_size.bytes(); start_address: x86_64.VirtAddr, /// Returns the page that starts at the given virtual address. /// /// Returns an error if the address is not correctly aligned (i.e. is not a valid page start). pub fn fromStartAddress(address: x86_64.VirtAddr) PageError!Page1GiB { if (!address.isAligned(page_size.bytes())) { return PageError.AddressNotAligned; } return containingAddress(address); } /// Returns the page that starts at the given virtual address. pub fn fromStartAddressUnchecked(address: x86_64.VirtAddr) Page1GiB { return .{ .start_address = address }; } /// Returns the page that contains the given virtual address. pub fn containingAddress(address: x86_64.VirtAddr) Page1GiB { return .{ .start_address = address.alignDown(page_size.bytes()) }; } /// Returns the level 4 page table index of this page. pub fn p4Index(self: Page1GiB) PageTableIndex { return self.start_address.p4Index(); } /// Returns the level 3 page table index of this page. pub fn p3Index(self: Page1GiB) PageTableIndex { return self.start_address.p3Index(); } pub fn format(value: Page1GiB, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; try writer.print("Page[" ++ page_size.sizeString() ++ "](0x{x})", .{value.start_address.value}); } comptime { std.testing.refAllDecls(@This()); } }; pub const PageError = error{AddressNotAligned}; /// Returns the 1GiB memory page with the specified page table indices. pub fn pageFromTableIndices1GiB(p4_index: PageTableIndex, p3_index: PageTableIndex) Page1GiB { var addr: u64 = 0; bitjuggle.setBits(&addr, 39, 9, p4_index.value); bitjuggle.setBits(&addr, 30, 9, p3_index.value); return Page1GiB.containingAddress(x86_64.VirtAddr.initPanic(addr)); } /// Returns the 2MiB memory page with the specified page table indices. pub fn pageFromTableIndices2MiB(p4_index: PageTableIndex, p3_index: PageTableIndex, p2_index: PageTableIndex) Page2MiB { var addr: u64 = 0; bitjuggle.setBits(&addr, 39, 9, p4_index.value); bitjuggle.setBits(&addr, 30, 9, p3_index.value); bitjuggle.setBits(&addr, 21, 9, p2_index.value); return Page2MiB.containingAddress(x86_64.VirtAddr.initPanic(addr)); } /// Returns the 4KiB memory page p4_index the specified page table indices. pub fn pageFromTableIndices(p4_index: PageTableIndex, p3_index: PageTableIndex, p2_index: PageTableIndex, p1_index: PageTableIndex) Page { var addr: u64 = 0; bitjuggle.setBits(&addr, 39, 9, p4_index.value); bitjuggle.setBits(&addr, 30, 9, p3_index.value); bitjuggle.setBits(&addr, 21, 9, p2_index.value); bitjuggle.setBits(&addr, 12, 9, p1_index.value); return Page.containingAddress(x86_64.VirtAddr.initPanic(addr)); } /// A range of pages, exclusive the upper bound. Page size 4 KiB pub const PageRange = struct { /// The start of the range, inclusive. start: Page, /// The end of the range, exclusive. end: Page, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRange) bool { return self.start.start_address.value >= self.end.start_address.value; } pub fn next(self: *PageRange) ?Page { if (self.start.start_address.value < self.end.start_address.value) { const page = self.start; self.start = Page.containingAddress(.{ .value = self.start.start_address.value + Page.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// A range of pages, exclusive the upper bound. Page size 2 MiB pub const PageRange2MiB = struct { /// The start of the range, inclusive. start: Page2MiB, /// The end of the range, exclusive. end: Page2MiB, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRange2MiB) bool { return self.start.start_address.value >= self.end.start_address.value; } pub fn next(self: *PageRange2MiB) ?Page2MiB { if (self.start.start_address.value < self.end.start_address.value) { const page = self.start; self.start = Page2MiB.containingAddress(.{ .value = self.start.start_address.value + Page2MiB.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// A range of pages, exclusive the upper bound. Page size 1 GiB pub const PageRange1GiB = struct { /// The start of the range, inclusive. start: Page1GiB, /// The end of the range, exclusive. end: Page1GiB, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRange1GiB) bool { return self.start.start_address.value >= self.end.start_address.value; } pub fn next(self: *PageRange1GiB) ?Page1GiB { if (self.start.start_address.value < self.end.start_address.value) { const page = self.start; self.start = Page1GiB.containingAddress(.{ .value = self.start.start_address.value + Page1GiB.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// A range of pages, inclusive the upper bound. Page size 4 KiB pub const PageRangeInclusive = struct { /// The start of the range, inclusive. start: Page, /// The end of the range, exclusive. end: Page, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRangeInclusive) bool { return self.start.start_address.value > self.end.start_address.value; } pub fn next(self: *PageRangeInclusive) ?Page { if (self.start.start_address.value <= self.end.start_address.value) { const page = self.start; self.start = Page.containingAddress(x86_64.VirtAddr{ .value = self.start.start_address.value + Page.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// A range of pages, inclusive the upper bound. Page size 2 MiB pub const PageRange2MiBInclusive = struct { /// The start of the range, inclusive. start: Page2MiB, /// The end of the range, exclusive. end: Page2MiB, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRange2MiBInclusive) bool { return self.start.start_address.value > self.end.start_address.value; } pub fn next(self: *PageRange2MiBInclusive) ?Page2MiB { if (self.start.start_address.value <= self.end.start_address.value) { const page = self.start; self.start = Page2MiB.containingAddress(x86_64.VirtAddr{ .value = self.start.start_address.value + Page2MiB.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// A range of pages, inclusive the upper bound. Page size 1 GiB pub const PageRange1GiBInclusive = struct { /// The start of the range, inclusive. start: Page1GiB, /// The end of the range, exclusive. end: Page1GiB, /// Returns whether the range contains no frames. pub fn isEmpty(self: PageRange1GiBInclusive) bool { return self.start.start_address.value > self.end.start_address.value; } pub fn next(self: *PageRange1GiBInclusive) ?Page1GiB { if (self.start.start_address.value <= self.end.start_address.value) { const page = self.start; self.start = Page1GiB.containingAddress(x86_64.VirtAddr{ .value = self.start.start_address.value + Page1GiB.bytes }); return page; } return null; } comptime { std.testing.refAllDecls(@This()); } }; /// Generates iterators for ranges of physical memory frame. Page size 4 KiB pub const PageIterator = struct { /// Returns a range of pages, exclusive `end`. pub fn range(start: Page, end: Page) PageRange { return .{ .start = start, .end = end }; } /// Returns a range of pages, inclusive `end`. pub fn rangeInclusive(start: Page, end: Page) PageRangeInclusive { return .{ .start = start, .end = end }; } comptime { std.testing.refAllDecls(@This()); } }; /// Generates iterators for ranges of physical memory frame. Page size 2 MiB pub const PageIterator2MiB = struct { /// Returns a range of pages, exclusive `end`. pub fn range(start: Page2MiB, end: Page2MiB) PageRange2MiB { return .{ .start = start, .end = end }; } /// Returns a range of pages, inclusive `end`. pub fn rangeInclusive(start: Page2MiB, end: Page2MiB) PageRange2MiBInclusive { return .{ .start = start, .end = end }; } comptime { std.testing.refAllDecls(@This()); } }; /// Generates iterators for ranges of physical memory frame. Page size 1 GiB pub const PageIterator1GiB = struct { /// Returns a range of pages, exclusive `end`. pub fn range(start: Page1GiB, end: Page1GiB) PageRange1GiB { return .{ .start = start, .end = end }; } /// Returns a range of pages, inclusive `end`. pub fn rangeInclusive(start: Page1GiB, end: Page1GiB) PageRange1GiBInclusive { return .{ .start = start, .end = end }; } comptime { std.testing.refAllDecls(@This()); } }; test "PageIterator" { var virtAddrA = x86_64.VirtAddr.initPanic(0x00000FFFFFFF0000); virtAddrA = virtAddrA.alignDown(x86_64.structures.paging.PageSize.Size4KiB.bytes()); var virtAddrB = x86_64.VirtAddr.initPanic(0x00000FFFFFFFFFFF); virtAddrB = virtAddrB.alignDown(x86_64.structures.paging.PageSize.Size4KiB.bytes()); const a = try Page.fromStartAddress(virtAddrA); const b = try Page.fromStartAddress(virtAddrB); var iterator = PageIterator.range(a, b); var inclusive_iterator = PageIterator.rangeInclusive(a, b); try std.testing.expect(!iterator.isEmpty()); try std.testing.expect(!inclusive_iterator.isEmpty()); var count: usize = 0; while (iterator.next()) |_| { count += 1; } try std.testing.expectEqual(@as(usize, 15), count); count = 0; while (inclusive_iterator.next()) |_| { count += 1; } try std.testing.expectEqual(@as(usize, 16), count); try std.testing.expect(iterator.isEmpty()); try std.testing.expect(inclusive_iterator.isEmpty()); } comptime { std.testing.refAllDecls(@This()); }
src/structures/paging/page.zig
const std = @import("std"); const assert = std.debug.assert; const glfw = @import("glfw"); const c = @cImport({ @cInclude("dawn/dawn_proc.h"); @cInclude("dawn_native_mach.h"); }); const objc = @cImport({ @cInclude("objc/message.h"); }); pub const cimgui = @cImport({ @cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", ""); @cDefine("CIMGUI_NO_EXPORT", ""); @cInclude("imgui/cimgui.h"); }); pub const gpu = @import("mach-gpu/main.zig"); const wgsl = @import("common_wgsl.zig"); pub const SwapChainState = enum { normal, swap_chain_resized, }; pub const GraphicsContext = struct { native_instance: gpu.NativeInstance, adapter_type: gpu.Adapter.Type, backend_type: gpu.Adapter.BackendType, device: gpu.Device, queue: gpu.Queue, window: glfw.Window, window_width: u32, window_height: u32, window_surface: gpu.Surface, swapchain: gpu.SwapChain, swapchain_descriptor: gpu.SwapChain.Descriptor, buffer_pool: BufferPool, texture_pool: TexturePool, texture_view_pool: TextureViewPool, sampler_pool: SamplerPool, render_pipeline_pool: RenderPipelinePool, compute_pipeline_pool: ComputePipelinePool, bind_group_pool: BindGroupPool, bind_group_layout_pool: BindGroupLayoutPool, mipgen: struct { pipeline: ComputePipelineHandle = .{}, scratch_texture: TextureHandle = .{}, scratch_texture_views: [4]TextureViewHandle = [_]TextureViewHandle{.{}} ** 4, bind_group_layout: BindGroupLayoutHandle = .{}, } = .{}, stats: FrameStats = .{}, pub const swapchain_format = gpu.Texture.Format.bgra8_unorm; // TODO: Adjust pool sizes. const buffer_pool_size = 256; const texture_pool_size = 256; const texture_view_pool_size = 256; const sampler_pool_size = 16; const render_pipeline_pool_size = 128; const compute_pipeline_pool_size = 128; const bind_group_pool_size = 32; const bind_group_layout_pool_size = 32; pub fn init(allocator: std.mem.Allocator, window: glfw.Window) !GraphicsContext { c.dawnProcSetProcs(c.machDawnNativeGetProcs()); const instance = c.machDawnNativeInstance_init(); c.machDawnNativeInstance_discoverDefaultAdapters(instance); var native_instance = gpu.NativeInstance.wrap(c.machDawnNativeInstance_get(instance).?); const gpu_interface = native_instance.interface(); const backend_adapter = switch (gpu_interface.waitForAdapter(&.{ .power_preference = .high_performance, })) { .adapter => |v| v, .err => |err| { std.debug.print("[zgpu] Failed to get adapter: error={} {s}.\n", .{ err.code, err.message }); return error.NoGraphicsAdapter; }, }; const props = backend_adapter.properties; std.debug.print("[zgpu] High-performance device has been selected:\n", .{}); std.debug.print("[zgpu] Name: {s}\n", .{props.name}); std.debug.print("[zgpu] Driver: {s}\n", .{props.driver_description}); std.debug.print("[zgpu] Adapter type: {s}\n", .{gpu.Adapter.typeName(props.adapter_type)}); std.debug.print("[zgpu] Backend type: {s}\n", .{gpu.Adapter.backendTypeName(props.backend_type)}); const device = switch (backend_adapter.waitForDevice(&.{})) { .device => |v| v, .err => |err| { std.debug.print("[zgpu] Failed to get device: error={} {s}\n", .{ err.code, err.message }); return error.NoGraphicsDevice; }, }; device.setUncapturedErrorCallback(&printUnhandledErrorCallback); const window_surface = createSurfaceForWindow( &native_instance, window, comptime detectGLFWOptions(), ); const window_size = window.getSize() catch unreachable; const framebuffer_size = window.getFramebufferSize() catch unreachable; const swapchain_descriptor = gpu.SwapChain.Descriptor{ .label = "main window swap chain", .usage = .{ .render_attachment = true }, .format = swapchain_format, .width = framebuffer_size.width, .height = framebuffer_size.height, .present_mode = .fifo, .implementation = 0, }; const swapchain = device.nativeCreateSwapChain( window_surface, &swapchain_descriptor, ); return GraphicsContext{ .native_instance = native_instance, .adapter_type = props.adapter_type, .backend_type = props.backend_type, .device = device, .queue = device.getQueue(), .window = window, .window_width = window_size.width, .window_height = window_size.height, .window_surface = window_surface, .swapchain = swapchain, .swapchain_descriptor = swapchain_descriptor, .buffer_pool = BufferPool.init(allocator, buffer_pool_size), .texture_pool = TexturePool.init(allocator, texture_pool_size), .texture_view_pool = TextureViewPool.init(allocator, texture_view_pool_size), .sampler_pool = SamplerPool.init(allocator, sampler_pool_size), .render_pipeline_pool = RenderPipelinePool.init(allocator, render_pipeline_pool_size), .compute_pipeline_pool = ComputePipelinePool.init(allocator, compute_pipeline_pool_size), .bind_group_pool = BindGroupPool.init(allocator, bind_group_pool_size), .bind_group_layout_pool = BindGroupLayoutPool.init(allocator, bind_group_layout_pool_size), }; } pub fn deinit(gctx: *GraphicsContext, allocator: std.mem.Allocator) void { // TODO: How to release `native_instance`? gctx.bind_group_pool.deinit(allocator); gctx.bind_group_layout_pool.deinit(allocator); gctx.buffer_pool.deinit(allocator); gctx.texture_view_pool.deinit(allocator); gctx.texture_pool.deinit(allocator); gctx.sampler_pool.deinit(allocator); gctx.render_pipeline_pool.deinit(allocator); gctx.compute_pipeline_pool.deinit(allocator); gctx.window_surface.release(); gctx.swapchain.release(); gctx.queue.release(); gctx.device.release(); gctx.* = undefined; } pub fn present(gctx: *GraphicsContext) SwapChainState { gctx.swapchain.present(); gctx.stats.update(); const win_size = gctx.window.getSize() catch unreachable; const fb_size = gctx.window.getFramebufferSize() catch unreachable; if (gctx.swapchain_descriptor.width != fb_size.width or gctx.swapchain_descriptor.height != fb_size.height) { gctx.swapchain_descriptor.width = fb_size.width; gctx.swapchain_descriptor.height = fb_size.height; gctx.swapchain.release(); gctx.swapchain = gctx.device.nativeCreateSwapChain( gctx.window_surface, &gctx.swapchain_descriptor, ); gctx.window_width = win_size.width; gctx.window_height = win_size.height; std.debug.print( "[zgpu] Window has been resized to: {d}x{d} pixels ({d}x{d} units).\n", .{ gctx.swapchain_descriptor.width, gctx.swapchain_descriptor.height, gctx.window_width, gctx.window_height, }, ); return .swap_chain_resized; } return .normal; } pub fn createBuffer(gctx: *GraphicsContext, descriptor: gpu.Buffer.Descriptor) BufferHandle { return gctx.buffer_pool.addResource(gctx.*, .{ .gpuobj = gctx.device.createBuffer(&descriptor), .size = descriptor.size, .usage = descriptor.usage, }); } pub fn createTexture(gctx: *GraphicsContext, descriptor: gpu.Texture.Descriptor) TextureHandle { return gctx.texture_pool.addResource(gctx.*, .{ .gpuobj = gctx.device.createTexture(&descriptor), .usage = descriptor.usage, .dimension = descriptor.dimension, .size = descriptor.size, .format = descriptor.format, .mip_level_count = descriptor.mip_level_count, .sample_count = descriptor.sample_count, }); } pub fn createTextureView( gctx: *GraphicsContext, texture_handle: TextureHandle, descriptor: gpu.TextureView.Descriptor, ) TextureViewHandle { const texture = gctx.lookupResource(texture_handle).?; return gctx.texture_view_pool.addResource(gctx.*, .{ .gpuobj = texture.createView(&descriptor), .format = descriptor.format, .dimension = descriptor.dimension, .base_mip_level = descriptor.base_mip_level, .base_array_layer = descriptor.base_array_layer, .array_layer_count = descriptor.array_layer_count, .aspect = descriptor.aspect, .parent_texture_handle = texture_handle, }); } pub fn createSampler(gctx: *GraphicsContext, descriptor: gpu.Sampler.Descriptor) SamplerHandle { return gctx.sampler_pool.addResource(gctx.*, .{ .gpuobj = gctx.device.createSampler(&descriptor), .address_mode_u = descriptor.address_mode_u, .address_mode_v = descriptor.address_mode_v, .address_mode_w = descriptor.address_mode_w, .mag_filter = descriptor.mag_filter, .min_filter = descriptor.min_filter, .mipmap_filter = descriptor.mipmap_filter, .lod_min_clamp = descriptor.lod_min_clamp, .lod_max_clamp = descriptor.lod_max_clamp, .compare = descriptor.compare, .max_anisotropy = descriptor.max_anisotropy, }); } pub fn createRenderPipeline( gctx: *GraphicsContext, descriptor: gpu.RenderPipeline.Descriptor, ) RenderPipelineHandle { return gctx.render_pipeline_pool.addResource(gctx.*, .{ .gpuobj = gctx.device.createRenderPipeline(&descriptor), }); } pub fn createComputePipeline( gctx: *GraphicsContext, descriptor: gpu.ComputePipeline.Descriptor, ) ComputePipelineHandle { return gctx.compute_pipeline_pool.addResource(gctx.*, .{ .gpuobj = gctx.device.createComputePipeline(&descriptor), }); } pub fn createBindGroup( gctx: *GraphicsContext, layout: BindGroupLayoutHandle, entries: []const BindGroupEntryInfo, ) BindGroupHandle { assert(entries.len > 0 and entries.len < max_num_bindings_per_group); var bind_group_info = BindGroupInfo{ .num_active_entries = @intCast(u32, entries.len) }; var gpu_bind_group_entries: [max_num_bindings_per_group]gpu.BindGroup.Entry = undefined; for (entries) |entry, i| { bind_group_info.entries[i] = entry; if (entries[i].buffer_handle) |handle| { gpu_bind_group_entries[i] = .{ .binding = entries[i].binding, .buffer = gctx.lookupResource(handle).?, .offset = entries[i].offset, .size = entries[i].size, .sampler = null, .texture_view = null, }; } else if (entries[i].sampler_handle) |handle| { gpu_bind_group_entries[i] = .{ .binding = entries[i].binding, .buffer = null, .offset = 0, .size = 0, .sampler = gctx.lookupResource(handle).?, .texture_view = null, }; } else if (entries[i].texture_view_handle) |handle| { gpu_bind_group_entries[i] = .{ .binding = entries[i].binding, .buffer = null, .offset = 0, .size = 0, .sampler = null, .texture_view = gctx.lookupResource(handle).?, }; } else unreachable; } bind_group_info.gpuobj = gctx.device.createBindGroup(&.{ .layout = gctx.lookupResource(layout).?, .entries = gpu_bind_group_entries[0..entries.len], }); return gctx.bind_group_pool.addResource(gctx.*, bind_group_info); } pub fn createBindGroupLayout( gctx: *GraphicsContext, descriptor: gpu.BindGroupLayout.Descriptor, ) BindGroupLayoutHandle { assert(descriptor.entries.len > 0 and descriptor.entries.len < max_num_bindings_per_group); var bind_group_layout_info = BindGroupLayoutInfo{ .gpuobj = gctx.device.createBindGroupLayout(&descriptor), .num_active_entries = @intCast(u32, descriptor.entries.len), }; for (descriptor.entries) |entry, i| { bind_group_layout_info.entries[i] = entry; bind_group_layout_info.entries[i].reserved = null; bind_group_layout_info.entries[i].buffer.reserved = null; bind_group_layout_info.entries[i].sampler.reserved = null; bind_group_layout_info.entries[i].texture.reserved = null; bind_group_layout_info.entries[i].storage_texture.reserved = null; } return gctx.bind_group_layout_pool.addResource(gctx.*, bind_group_layout_info); } pub fn createBindGroupLayoutAuto( gctx: *GraphicsContext, pipeline: anytype, group_index: u32, ) BindGroupLayoutHandle { const bgl = gctx.lookupResource(pipeline).?.getBindGroupLayout(group_index); return gctx.bind_group_layout_pool.addResource(gctx.*, BindGroupLayoutInfo{ .gpuobj = bgl }); } pub fn lookupResource(gctx: GraphicsContext, handle: anytype) ?handleToGpuResourceType(@TypeOf(handle)) { if (gctx.isResourceValid(handle)) { const T = @TypeOf(handle); return switch (T) { BufferHandle => gctx.buffer_pool.resources[handle.index].gpuobj.?, TextureHandle => gctx.texture_pool.resources[handle.index].gpuobj.?, TextureViewHandle => gctx.texture_view_pool.resources[handle.index].gpuobj.?, SamplerHandle => gctx.sampler_pool.resources[handle.index].gpuobj.?, RenderPipelineHandle => gctx.render_pipeline_pool.resources[handle.index].gpuobj.?, ComputePipelineHandle => gctx.compute_pipeline_pool.resources[handle.index].gpuobj.?, BindGroupHandle => gctx.bind_group_pool.resources[handle.index].gpuobj.?, BindGroupLayoutHandle => gctx.bind_group_layout_pool.resources[handle.index].gpuobj.?, else => @compileError( "[zgpu] GraphicsContext.lookupResource() not implemented for " ++ @typeName(T), ), }; } return null; } pub fn lookupResourceInfo(gctx: GraphicsContext, handle: anytype) ?handleToResourceInfoType(@TypeOf(handle)) { if (gctx.isResourceValid(handle)) { const T = @TypeOf(handle); return switch (T) { BufferHandle => gctx.buffer_pool.resources[handle.index], TextureHandle => gctx.texture_pool.resources[handle.index], TextureViewHandle => gctx.texture_view_pool.resources[handle.index], SamplerHandle => gctx.sampler_pool.resources[handle.index], RenderPipelineHandle => gctx.render_pipeline_pool.resources[handle.index], ComputePipelineHandle => gctx.compute_pipeline_pool.resources[handle.index], BindGroupHandle => gctx.bind_group_pool.resources[handle.index], BindGroupLayoutHandle => gctx.bind_group_layout_pool.resources[handle.index], else => @compileError( "[zgpu] GraphicsContext.lookupResourceInfo() not implemented for " ++ @typeName(T), ), }; } return null; } pub fn destroyResource(gctx: GraphicsContext, handle: anytype) void { const T = @TypeOf(handle); switch (T) { BufferHandle => gctx.buffer_pool.destroyResource(handle), TextureHandle => gctx.texture_pool.destroyResource(handle), TextureViewHandle => gctx.texture_view_pool.destroyResource(handle), SamplerHandle => gctx.sampler_pool.destroyResource(handle), RenderPipelineHandle => gctx.render_pipeline_pool.destroyResource(handle), ComputePipelineHandle => gctx.compute_pipeline_pool.destroyResource(handle), BindGroupHandle => gctx.bind_group_pool.destroyResource(handle), BindGroupLayoutHandle => gctx.bind_group_layout_pool.destroyResource(handle), else => @compileError("[zgpu] GraphicsContext.destroyResource() not implemented for " ++ @typeName(T)), } } pub fn isResourceValid(gctx: GraphicsContext, handle: anytype) bool { const T = @TypeOf(handle); switch (T) { BufferHandle => return gctx.buffer_pool.isHandleValid(handle), TextureHandle => return gctx.texture_pool.isHandleValid(handle), TextureViewHandle => { if (gctx.texture_view_pool.isHandleValid(handle)) { const texture = gctx.texture_view_pool.resources[handle.index].parent_texture_handle; return gctx.isResourceValid(texture); } return false; }, SamplerHandle => return gctx.sampler_pool.isHandleValid(handle), RenderPipelineHandle => return gctx.render_pipeline_pool.isHandleValid(handle), ComputePipelineHandle => return gctx.compute_pipeline_pool.isHandleValid(handle), BindGroupHandle => { if (gctx.bind_group_pool.isHandleValid(handle)) { const num_entries = gctx.bind_group_pool.resources[handle.index].num_active_entries; const entries = &gctx.bind_group_pool.resources[handle.index].entries; var i: u32 = 0; while (i < num_entries) : (i += 1) { if (entries[i].buffer_handle) |buffer| { if (!gctx.isResourceValid(buffer)) return false; } else if (entries[i].sampler_handle) |sampler| { if (!gctx.isResourceValid(sampler)) return false; } else if (entries[i].texture_view_handle) |texture_view| { if (!gctx.isResourceValid(texture_view)) return false; } else unreachable; } return true; } return false; }, BindGroupLayoutHandle => return gctx.bind_group_layout_pool.isHandleValid(handle), else => @compileError("[zgpu] GraphicsContext.isResourceValid() not implemented for " ++ @typeName(T)), } } pub fn generateMipmaps(gctx: *GraphicsContext, texture: TextureHandle) void { const texture_info = gctx.lookupResourceInfo(texture) orelse return; if (texture_info.dimension != .dimension_2d) { // TODO: Print message. return; } if (!gctx.isResourceValid(gctx.mipgen.pipeline)) { const cs_module = gctx.device.createShaderModule(&.{ .label = "zgpu_cs_generate_mipmaps", .code = .{ .wgsl = wgsl.cs_generate_mipmaps }, }); defer cs_module.release(); gctx.mipgen.pipeline = gctx.createComputePipeline(.{ .compute = .{ .label = "zgpu_cs_generate_mipmaps", .module = cs_module, .entry_point = "main", }, }); gctx.mipgen.bind_group_layout = gctx.createBindGroupLayoutAuto(gctx.mipgen.pipeline, 0); gctx.mipgen.scratch_texture = gctx.createTexture(.{ .usage = .{ .copy_src = true, .storage_binding = true }, .dimension = .dimension_2d, .size = .{ .width = 1024, .height = 1024, .depth_or_array_layers = 1 }, .format = .rgba32_float, .mip_level_count = 4, .sample_count = 1, }); for (gctx.mipgen.scratch_texture_views) |*view, i| { view.* = gctx.createTextureView(gctx.mipgen.scratch_texture, .{ .format = .rgba32_float, .dimension = .dimension_2d, .base_mip_level = @intCast(u32, i), .mip_level_count = 1, .base_array_layer = 0, .array_layer_count = 1, }); } } const uniform_buffer = gctx.createBuffer(.{ .usage = .{ .copy_dst = true, .uniform = true }, .size = 8, }); defer gctx.destroyResource(uniform_buffer); const texture_view = gctx.createTextureView(texture, .{ .format = texture_info.format, .dimension = .dimension_2d, .base_mip_level = 0, .mip_level_count = texture_info.mip_level_count, .base_array_layer = 0, .array_layer_count = texture_info.size.depth_or_array_layers, }); defer gctx.destroyResource(texture_view); const draw_bind_group = gctx.createBindGroup(gctx.mipgen.bind_group_layout, &[_]BindGroupEntryInfo{ .{ .binding = 0, .buffer_handle = uniform_buffer, .offset = 0, .size = 8 }, .{ .binding = 1, .texture_view_handle = texture_view }, .{ .binding = 2, .texture_view_handle = gctx.mipgen.scratch_texture_views[0] }, .{ .binding = 3, .texture_view_handle = gctx.mipgen.scratch_texture_views[1] }, .{ .binding = 4, .texture_view_handle = gctx.mipgen.scratch_texture_views[2] }, .{ .binding = 5, .texture_view_handle = gctx.mipgen.scratch_texture_views[3] }, }); defer gctx.destroyResource(draw_bind_group); } }; pub const BufferHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const TextureHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const TextureViewHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const SamplerHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const RenderPipelineHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const ComputePipelineHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const BindGroupHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const BindGroupLayoutHandle = struct { index: u16 align(4) = 0, generation: u16 = 0 }; pub const BufferInfo = struct { gpuobj: ?gpu.Buffer = null, size: usize = 0, usage: gpu.BufferUsage = .{}, }; pub const TextureInfo = struct { gpuobj: ?gpu.Texture = null, usage: gpu.Texture.Usage = .{}, dimension: gpu.Texture.Dimension = .dimension_1d, size: gpu.Extent3D = .{ .width = 0 }, format: gpu.Texture.Format = .none, mip_level_count: u32 = 0, sample_count: u32 = 0, }; pub const TextureViewInfo = struct { gpuobj: ?gpu.TextureView = null, format: gpu.Texture.Format = .none, dimension: gpu.TextureView.Dimension = .dimension_none, base_mip_level: u32 = 0, base_array_layer: u32 = 0, array_layer_count: u32 = 0, aspect: gpu.Texture.Aspect = .all, parent_texture_handle: TextureHandle = .{}, }; pub const SamplerInfo = struct { gpuobj: ?gpu.Sampler = null, address_mode_u: gpu.AddressMode = .repeat, address_mode_v: gpu.AddressMode = .repeat, address_mode_w: gpu.AddressMode = .repeat, mag_filter: gpu.FilterMode = .nearest, min_filter: gpu.FilterMode = .nearest, mipmap_filter: gpu.FilterMode = .nearest, lod_min_clamp: f32 = 0.0, lod_max_clamp: f32 = 0.0, compare: gpu.CompareFunction = .none, max_anisotropy: u16 = 0, }; const RenderPipelineInfo = struct { gpuobj: ?gpu.RenderPipeline = null, }; const ComputePipelineInfo = struct { gpuobj: ?gpu.ComputePipeline = null, }; pub const BindGroupEntryInfo = struct { binding: u32 = 0, buffer_handle: ?BufferHandle = null, offset: u64 = 0, size: u64 = 0, sampler_handle: ?SamplerHandle = null, texture_view_handle: ?TextureViewHandle = null, }; pub const max_num_bindings_per_group = 8; pub const BindGroupInfo = struct { gpuobj: ?gpu.BindGroup = null, num_active_entries: u32 = 0, entries: [max_num_bindings_per_group]BindGroupEntryInfo = [_]BindGroupEntryInfo{.{}} ** max_num_bindings_per_group, }; pub const BindGroupLayoutInfo = struct { gpuobj: ?gpu.BindGroupLayout = null, num_active_entries: u32 = 0, entries: [max_num_bindings_per_group]gpu.BindGroupLayout.Entry = [_]gpu.BindGroupLayout.Entry{.{ .binding = 0, .visibility = .{} }} ** max_num_bindings_per_group, }; const BufferPool = ResourcePool(BufferInfo, BufferHandle); const TexturePool = ResourcePool(TextureInfo, TextureHandle); const TextureViewPool = ResourcePool(TextureViewInfo, TextureViewHandle); const SamplerPool = ResourcePool(SamplerInfo, SamplerHandle); const RenderPipelinePool = ResourcePool(RenderPipelineInfo, RenderPipelineHandle); const ComputePipelinePool = ResourcePool(ComputePipelineInfo, ComputePipelineHandle); const BindGroupPool = ResourcePool(BindGroupInfo, BindGroupHandle); const BindGroupLayoutPool = ResourcePool(BindGroupLayoutInfo, BindGroupLayoutHandle); fn ResourcePool(comptime ResourceInfo: type, comptime ResourceHandle: type) type { return struct { const Self = @This(); resources: []ResourceInfo, generations: []u16, start_slot_index: u32 = 0, fn init(allocator: std.mem.Allocator, capacity: u32) Self { var resources = allocator.alloc(ResourceInfo, capacity + 1) catch unreachable; for (resources) |*resource| resource.* = .{}; var generations = allocator.alloc(u16, capacity + 1) catch unreachable; for (generations) |*gen| gen.* = 0; return .{ .resources = resources, .generations = generations, }; } fn deinit(pool: *Self, allocator: std.mem.Allocator) void { for (pool.resources) |resource| { if (resource.gpuobj) |gpuobj| { if (@hasDecl(@TypeOf(gpuobj), "destroy")) { gpuobj.destroy(); } gpuobj.release(); } } allocator.free(pool.resources); allocator.free(pool.generations); pool.* = undefined; } fn addResource(pool: *Self, gctx: GraphicsContext, resource: ResourceInfo) ResourceHandle { assert(resource.gpuobj != null); var index: u32 = 0; var found_slot_index: u32 = 0; while (index < pool.resources.len) : (index += 1) { const slot_index = (pool.start_slot_index + index) % @intCast(u32, pool.resources.len); if (slot_index == 0) // Skip index 0 because it is reserved for `invalid handle`. continue; if (pool.resources[slot_index].gpuobj == null) { // If `gpuobj` is null slot is free. found_slot_index = slot_index; break; } else { // If `gpuobj` is not null slot can still be free because dependent resources could // have become invalid. For example, texture view becomes invalid when parent texture // is destroyed. const handle = ResourceHandle{ // Construct a *valid* handle for the slot that we want to check. .index = @intCast(u16, slot_index), .generation = pool.generations[slot_index], }; // Check the handle (will always be valid) and its potential dependencies (may be invalid). if (!gctx.isResourceValid(handle)) { // Destroy old resource (it is invalid because some of its dependencies are invalid). pool.destroyResource(handle); found_slot_index = slot_index; break; } } } // TODO: For now we just assert if pool is full - make it more roboust. assert(found_slot_index > 0 and found_slot_index < pool.resources.len); pool.start_slot_index = found_slot_index + 1; pool.resources[found_slot_index] = resource; return .{ .index = @intCast(u16, found_slot_index), .generation = generation: { pool.generations[found_slot_index] += 1; break :generation pool.generations[found_slot_index]; }, }; } fn destroyResource(pool: Self, handle: ResourceHandle) void { if (!pool.isHandleValid(handle)) return; var resource_info = &pool.resources[handle.index]; const gpuobj = resource_info.gpuobj.?; if (@hasDecl(@TypeOf(gpuobj), "destroy")) { gpuobj.destroy(); } gpuobj.release(); resource_info.* = .{}; } fn isHandleValid(pool: Self, handle: ResourceHandle) bool { return handle.index > 0 and handle.index < pool.resources.len and handle.generation > 0 and handle.generation == pool.generations[handle.index] and pool.resources[handle.index].gpuobj != null; } }; } pub fn checkContent(comptime content_dir: []const u8) !void { const local = struct { fn impl() !void { // Change directory to where an executable is located. { var exe_path_buffer: [1024]u8 = undefined; const exe_path = std.fs.selfExeDirPath(exe_path_buffer[0..]) catch "./"; std.os.chdir(exe_path) catch {}; } // Make sure font file is a valid data file and not just a Git LFS pointer. { const file = try std.fs.cwd().openFile(content_dir ++ "Roboto-Medium.ttf", .{}); defer file.close(); const size = @intCast(usize, try file.getEndPos()); if (size <= 1024) { return error.InvalidDataFiles; } } } }; local.impl() catch |err| { std.debug.print( \\ \\DATA ERROR \\ \\Invalid data files or missing content folder. \\Please install Git LFS (Large File Support) and run (in the repo): \\ \\git lfs install \\git pull \\ \\For more info please see: https://git-lfs.github.com/ \\ \\ , .{}, ); return err; }; } const FrameStats = struct { time: f64 = 0.0, delta_time: f32 = 0.0, fps: f32 = 0.0, fps_counter: u32 = 0, average_cpu_time: f32 = 0.0, previous_time: f64 = 0.0, fps_refresh_time: f64 = 0.0, frame_number: u64 = 0, fn update(stats: *FrameStats) void { stats.time = glfw.getTime(); stats.delta_time = @floatCast(f32, stats.time - stats.previous_time); stats.previous_time = stats.time; if ((stats.time - stats.fps_refresh_time) >= 1.0) { const t = stats.time - stats.fps_refresh_time; const fps = @intToFloat(f64, stats.fps_counter) / t; const ms = (1.0 / fps) * 1000.0; stats.fps = @floatCast(f32, fps); stats.average_cpu_time = @floatCast(f32, ms); stats.fps_refresh_time = stats.time; stats.fps_counter = 0; } stats.fps_counter += 1; stats.frame_number += 1; } }; pub const gui = struct { pub fn init(window: glfw.Window, device: gpu.Device, font: [*:0]const u8, font_size: f32) void { assert(cimgui.igGetCurrentContext() == null); _ = cimgui.igCreateContext(null); if (!ImGui_ImplGlfw_InitForOther(window.handle, true)) { unreachable; } const io = cimgui.igGetIO().?; if (cimgui.ImFontAtlas_AddFontFromFileTTF(io.*.Fonts, font, font_size, null, null) == null) { unreachable; } if (!ImGui_ImplWGPU_Init( device.ptr, 1, // Number of `frames in flight`. One is enough because Dawn creates staging buffers internally. @enumToInt(GraphicsContext.swapchain_format), )) { unreachable; } } pub fn deinit() void { assert(cimgui.igGetCurrentContext() != null); ImGui_ImplWGPU_Shutdown(); ImGui_ImplGlfw_Shutdown(); cimgui.igDestroyContext(null); } pub fn newFrame(win_width: u32, win_height: u32, fb_width: u32, fb_height: u32) void { ImGui_ImplGlfw_NewFrame(win_width, win_height, fb_width, fb_height); ImGui_ImplWGPU_NewFrame(); cimgui.igNewFrame(); } pub fn draw(pass: gpu.RenderPassEncoder) void { cimgui.igRender(); ImGui_ImplWGPU_RenderDrawData(cimgui.igGetDrawData(), pass.ptr); } extern fn ImGui_ImplGlfw_InitForOther(window: *anyopaque, install_callbacks: bool) bool; extern fn ImGui_ImplGlfw_NewFrame(window_w: u32, window_h: u32, framebuffer_w: u32, framebuffer_h: u32) void; extern fn ImGui_ImplGlfw_Shutdown() void; extern fn ImGui_ImplWGPU_Init(device: *anyopaque, num_frames_in_flight: u32, rt_format: u32) bool; extern fn ImGui_ImplWGPU_NewFrame() void; extern fn ImGui_ImplWGPU_RenderDrawData(draw_data: *anyopaque, pass_encoder: *anyopaque) void; extern fn ImGui_ImplWGPU_Shutdown() void; }; fn detectGLFWOptions() glfw.BackendOptions { const target = @import("builtin").target; if (target.isDarwin()) return .{ .cocoa = true }; return switch (target.os.tag) { .windows => .{ .win32 = true }, .linux => .{ .x11 = true }, else => .{}, }; } fn createSurfaceForWindow( native_instance: *const gpu.NativeInstance, window: glfw.Window, comptime glfw_options: glfw.BackendOptions, ) gpu.Surface { const glfw_native = glfw.Native(glfw_options); const descriptor = if (glfw_options.win32) gpu.Surface.Descriptor{ .windows_hwnd = .{ .label = "basic surface", .hinstance = std.os.windows.kernel32.GetModuleHandleW(null).?, .hwnd = glfw_native.getWin32Window(window), }, } else if (glfw_options.x11) gpu.Surface.Descriptor{ .xlib = .{ .label = "basic surface", .display = glfw_native.getX11Display(), .window = glfw_native.getX11Window(window), }, } else if (glfw_options.cocoa) blk: { const ns_window = glfw_native.getCocoaWindow(window); const ns_view = msgSend(ns_window, "contentView", .{}, *anyopaque); // [nsWindow contentView] // Create a CAMetalLayer that covers the whole window that will be passed to CreateSurface. msgSend(ns_view, "setWantsLayer:", .{true}, void); // [view setWantsLayer:YES] const layer = msgSend(objc.objc_getClass("CAMetalLayer"), "layer", .{}, ?*anyopaque); // [CAMetalLayer layer] if (layer == null) @panic("failed to create Metal layer"); msgSend(ns_view, "setLayer:", .{layer.?}, void); // [view setLayer:layer] // Use retina if the window was created with retina support. const scale_factor = msgSend(ns_window, "backingScaleFactor", .{}, f64); // [ns_window backingScaleFactor] msgSend(layer.?, "setContentsScale:", .{scale_factor}, void); // [layer setContentsScale:scale_factor] break :blk gpu.Surface.Descriptor{ .metal_layer = .{ .label = "basic surface", .layer = layer.?, }, }; } else if (glfw_options.wayland) { // bugs.chromium.org/p/dawn/issues/detail?id=1246&q=surface&can=2 @panic("Dawn does not yet have Wayland support"); } else unreachable; return native_instance.createSurface(&descriptor); } // Borrowed from https://github.com/hazeycode/zig-objcrt fn msgSend(obj: anytype, sel_name: [:0]const u8, args: anytype, comptime ReturnType: type) ReturnType { const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; const FnType = switch (args_meta.len) { 0 => fn (@TypeOf(obj), objc.SEL) callconv(.C) ReturnType, 1 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type) callconv(.C) ReturnType, 2 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type) callconv(.C) ReturnType, 3 => fn ( @TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type, ) callconv(.C) ReturnType, 4 => fn ( @TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type, args_meta[3].field_type, ) callconv(.C) ReturnType, else => @compileError("[zgpu] Unsupported number of args"), }; // NOTE: `func` is a var because making it const causes a compile error which I believe is a compiler bug. var func = @ptrCast(FnType, objc.objc_msgSend); const sel = objc.sel_getUid(sel_name); return @call(.{}, func, .{ obj, sel } ++ args); } fn printUnhandledError(_: void, typ: gpu.ErrorType, message: [*:0]const u8) void { switch (typ) { .validation => std.debug.print("[zgpu] Validation error: {s}\n", .{message}), .out_of_memory => std.debug.print("[zgpu] Out of memory: {s}\n", .{message}), .device_lost => std.debug.print("[zgpu] Device lost: {s}\n", .{message}), .unknown => std.debug.print("[zgpu] Unknown error: {s}\n", .{message}), else => unreachable, } // TODO: Do something better. std.process.exit(1); } var printUnhandledErrorCallback = gpu.ErrorCallback.init(void, {}, printUnhandledError); fn handleToGpuResourceType(comptime T: type) type { return switch (T) { BufferHandle => gpu.Buffer, TextureHandle => gpu.Texture, TextureViewHandle => gpu.TextureView, SamplerHandle => gpu.Sampler, RenderPipelineHandle => gpu.RenderPipeline, ComputePipelineHandle => gpu.ComputePipeline, BindGroupHandle => gpu.BindGroup, BindGroupLayoutHandle => gpu.BindGroupLayout, else => @compileError("[zgpu] handleToGpuResourceType() not implemented for " ++ @typeName(T)), }; } fn handleToResourceInfoType(comptime T: type) type { return switch (T) { BufferHandle => BufferInfo, TextureHandle => TextureInfo, TextureViewHandle => TextureViewInfo, SamplerHandle => SamplerInfo, RenderPipelineHandle => RenderPipelineInfo, ComputePipelineHandle => ComputePipelineInfo, BindGroupHandle => BindGroupInfo, BindGroupLayoutHandle => BindGroupLayoutInfo, else => @compileError("[zgpu] handleToResourceInfoType() not implemented for " ++ @typeName(T)), }; }
libs/zgpu/src/zgpu.zig
const std = @import("std"); pub const maxWindows = 8; pub const WindowManager = struct { activeScreenIndex: usize = 0, amountScreens: usize = 0, displayWidth: i32 = 0, displayHeight: i32 = 0, screens: [maxWindows]Screen = undefined, running: bool = false, fn getActiveScreen(self: *WindowManager) *Screen { var res = &self.screens[self.activeScreenIndex]; return res; } fn getScreenIndexOfWindow(self: *WindowManager, window: u64) i32 { var res: i32 = -1; for (self.screens[0..self.amountScreens]) |*screen, screenIndex| { var workspace = screen.getActiveWorkspace(); var windowIndex = workspace.getWindowIndex(window); if (windowIndex >= 0) { res = @intCast(i32, screenIndex); break; } } return res; } }; pub const Screen = struct { info: ScreenInfo, workspaces: [8]Workspace, activeWorkspace: u32 = 0, previousWorkspace: u32 = 0, fn getActiveWorkspace(self: *Screen) *Workspace { return &self.workspaces[self.activeWorkspace]; } fn workspaceFocus(self: *Screen, index: u32) void { self.previousWorkspace = self.activeWorkspace; self.activeWorkspace = index; } }; pub const ScreenInfo = struct { x: i32, y: i32, width: u32, height: u32, }; pub const Workspace = struct { windows: [8]u64 = undefined, amountOfWindows: u32 = 0, focusedWindow: u32 = 0, const Self = *Workspace; fn hasWindow(self: Self, window: u64) bool { // TODO: array contains?? var res = false; for (self.windows) |win| { if (win == window) { res = true; break; } } return res; } fn getWindowIndex(self: Self, window: u64) i32 { var res: i32 = -1; for (self.windows) |win, i| { if (win == window) { res = @intCast(i32, i); break; } } return res; } fn getFocusedWindow(self: Self) u64 { return self.windows[self.focusedWindow]; } fn removeWindow(self: Self, window: u64) void { var removeIndex: usize = 0; var found = false; for (self.windows) |win, i| { if (win == window) { removeIndex = i; found = true; break; } } if (found) { for (self.windows[removeIndex..self.amountOfWindows]) |win, i| { var index = removeIndex + i; self.windows[index] = self.windows[index + 1]; } self.amountOfWindows -= 1; } } fn addWindow(self: Self, window: u64) bool { if (self.amountOfWindows == maxWindows) { return false; } self.windows[self.amountOfWindows] = window; self.amountOfWindows += 1; return true; } fn getNextWindow(self: Self) u64 { var index = std.math.min(self.focusedWindow + 1, self.amountOfWindows - 1); return self.windows[index]; } fn getPreviousWindow(self: Self) u64 { var index = self.focusedWindow; if (index > 0) { index -= 1; } return self.windows[index]; } };
src/wm.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const clap = @import("clap"); const Parser = @import("parser.zig").Parser; const Options = @import("options.zig").Options; const nodes = @import("nodes.zig"); const html = @import("html.zig"); pub fn main() !void { // In debug, use the GeneralPurposeAllocator as the Parser internal allocator // to shake out memory issues. There should be no leaks in normal operation. // In release, use an arena and reset it at the end. var gpa: std.heap.GeneralPurposeAllocator(.{}) = undefined; var arena: std.heap.ArenaAllocator = undefined; var allocator: std.mem.Allocator = undefined; if (builtin.mode == .Debug) { gpa = std.heap.GeneralPurposeAllocator(.{}){}; allocator = gpa.allocator(); } else { arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocator = arena.allocator(); } defer { if (builtin.mode == .Debug) { _ = gpa.deinit(); } else { arena.deinit(); } } var options: Options = undefined; var args = try parseArgs(&options); var parser = try Parser.init(allocator, options); if (args.positionals().len > 0) { for (args.positionals()) |pos| { var markdown = try std.fs.cwd().readFileAlloc(allocator, pos, 1024 * 1024 * 1024); defer allocator.free(markdown); try parser.feed(markdown); } } else { var markdown = try std.io.getStdIn().reader().readAllAlloc(allocator, 1024 * 1024 * 1024); defer allocator.free(markdown); try parser.feed(markdown); } var doc = try parser.finish(); var output = blk: { var arr = std.ArrayList(u8).init(allocator); errdefer arr.deinit(); try html.print(arr.writer(), allocator, options, doc); break :blk arr.toOwnedSlice(); }; defer allocator.free(output); if (builtin.mode == .Debug) { args.deinit(); parser.deinit(); doc.deinit(); } try std.io.getStdOut().writer().writeAll(output); } const params = params: { @setEvalBranchQuota(2000); break :params [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit") catch unreachable, clap.parseParam("-u, --unsafe Render raw HTML and dangerous URLs") catch unreachable, clap.parseParam("-e, --extension <EXTENSION>... Enable an extension (" ++ extensionsFriendly ++ ")") catch unreachable, clap.parseParam(" --header-anchors Generate anchors for headers") catch unreachable, clap.parseParam(" --smart Use smart punctuation") catch unreachable, clap.Param(clap.Help){ .takes_value = .one, }, }; }; const Args = clap.Args(clap.Help, &params); fn parseArgs(options: *Options) !Args { var stderr = std.io.getStdErr().writer(); var args = try clap.parse(clap.Help, &params, .{}); if (args.flag("--help")) { try stderr.writeAll("Usage: koino "); try clap.usage(stderr, &params); try stderr.writeAll("\n\nOptions:\n"); try clap.help(stderr, &params); std.os.exit(0); } options.* = .{}; if (args.flag("--unsafe")) options.render.unsafe = true; if (args.flag("--smart")) options.parse.smart = true; if (args.flag("--header-anchors")) options.render.header_anchors = true; for (args.options("--extension")) |extension| try enableExtension(extension, options); return args; } const extensions = blk: { var exts: []const []const u8 = &[_][]const u8{}; for (@typeInfo(Options.Extensions).Struct.fields) |field| { exts = exts ++ [_][]const u8{field.name}; } break :blk exts; }; const extensionsFriendly = blk: { var extsFriendly: []const u8 = &[_]u8{}; var first = true; for (extensions) |extension| { if (first) { first = false; } else { extsFriendly = extsFriendly ++ ","; } extsFriendly = extsFriendly ++ extension; } break :blk extsFriendly; }; fn enableExtension(extension: []const u8, options: *Options) !void { inline for (extensions) |valid_extension| { if (std.mem.eql(u8, valid_extension, extension)) { @field(options.extensions, valid_extension) = true; return; } } try std.fmt.format(std.io.getStdErr().writer(), "unknown extension: {s}\n", .{extension}); std.os.exit(1); } /// Performs work using internalAllocator, and writes the result to a Writer. fn markdownToHtmlInternal(writer: anytype, internalAllocator: std.mem.Allocator, options: Options, markdown: []const u8) !void { var doc = try parse(internalAllocator, options, markdown); defer doc.deinit(); try html.print(writer, internalAllocator, options, doc); } /// Parses Markdown into an AST. Use `deinit()' on the returned document to free memory. pub fn parse(internalAllocator: std.mem.Allocator, options: Options, markdown: []const u8) !*nodes.AstNode { var p = try Parser.init(internalAllocator, options); defer p.deinit(); try p.feed(markdown); return try p.finish(); } /// Performs work with an ArenaAllocator backed by the page allocator, and allocates the result HTML with resultAllocator. pub fn markdownToHtml(resultAllocator: std.mem.Allocator, options: Options, markdown: []const u8) ![]u8 { var result = std.ArrayList(u8).init(resultAllocator); errdefer result.deinit(); try markdownToHtmlWriter(result.writer(), options, markdown); return result.toOwnedSlice(); } /// Performs work with an ArenaAllocator backed by the page allocator, and writes the result to a Writer. pub fn markdownToHtmlWriter(writer: anytype, options: Options, markdown: []const u8) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); try markdownToHtmlInternal(writer, arena.allocator(), options, markdown); } /// Uses a GeneralPurposeAllocator for scratch work instead of an ArenaAllocator to aid in locating memory leaks. /// Result HTML is allocated by std.testing.allocator. pub fn testMarkdownToHtml(options: Options, markdown: []const u8) ![]u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var doc = try parse(gpa.allocator(), options, markdown); defer doc.deinit(); var result = std.ArrayList(u8).init(std.testing.allocator); errdefer result.deinit(); try html.print(result.writer(), gpa.allocator(), options, doc); return result.toOwnedSlice(); } test "" { std.testing.refAllDecls(@This()); }
src/main.zig
const std = @import("std"); const mem = std.mem; // Credit to prime31's various zig projects, very useful allocator const ScratchAllocator = struct { allocator: mem.Allocator, backup_allocator: *mem.Allocator, end_index: usize, buffer: []u8, pub fn init(a: *mem.Allocator) ScratchAllocator { const scratch_buffer = a.alloc(u8, 8 * 1024 * 1024) catch unreachable; return ScratchAllocator{ .allocator = mem.Allocator{ .allocFn = alloc, .resizeFn = mem.Allocator.noResize, }, .backup_allocator = a, .buffer = scratch_buffer, .end_index = 0, }; } fn alloc(a: *mem.Allocator, n: usize, ptr_align: u29, len_align: u29, ret_addr: usize) ![]u8 { const self = @fieldParentPtr(ScratchAllocator, "allocator", a); const addr = @ptrToInt(self.buffer.ptr) + self.end_index; const adjusted_addr = mem.alignForward(addr, ptr_align); const adjusted_index = self.end_index + (adjusted_addr - addr); const new_end_index = adjusted_index + n; if (new_end_index > self.buffer.len) { // if more memory is requested then we have in our buffer leak like a sieve! if (n > self.buffer.len) { std.debug.warn("\n---------\nwarning: tmp allocated more than is in our temp allocator. This memory WILL leak!\n--------\n", .{}); return self.allocator.allocFn(a, n, ptr_align, len_align, ret_addr); } const result = self.buffer[0..n]; self.end_index = n; return result; } const result = self.buffer[adjusted_index..new_end_index]; self.end_index = new_end_index; return result; } }; var ringBuffer: *mem.Allocator = undefined; var _allocInstance: ScratchAllocator = undefined; var initialized: bool = false; fn init(allocator: *std.mem.Allocator) void { _allocInstance = ScratchAllocator.init(allocator); ringBuffer = &_allocInstance.allocator; } /// Returns a ring buffer that uses a page allocator in a loop of memory. /// Do not use this for permanent memory, but instead for throw away memory, no need /// to free anything that you use this to allocate. pub fn ring() *mem.Allocator { if (!initialized) { init(std.heap.page_allocator); initialized = true; } return ringBuffer; }
src/zt/allocators.zig
const std = @import("std"); const uefi = std.os.uefi; const io = std.io; const Guid = uefi.Guid; const Time = uefi.Time; const Status = uefi.Status; pub const FileProtocol = extern struct { revision: u64, _open: fn (*const FileProtocol, **const FileProtocol, [*:0]const u16, u64, u64) callconv(.C) Status, _close: fn (*const FileProtocol) callconv(.C) Status, _delete: fn (*const FileProtocol) callconv(.C) Status, _read: fn (*const FileProtocol, *usize, [*]u8) callconv(.C) Status, _write: fn (*const FileProtocol, *usize, [*]const u8) callconv(.C) Status, _get_position: fn (*const FileProtocol, *u64) callconv(.C) Status, _set_position: fn (*const FileProtocol, u64) callconv(.C) Status, _get_info: fn (*const FileProtocol, *align(8) const Guid, *const usize, [*]u8) callconv(.C) Status, _set_info: fn (*const FileProtocol, *align(8) const Guid, usize, [*]const u8) callconv(.C) Status, _flush: fn (*const FileProtocol) callconv(.C) Status, pub const SeekError = error{SeekError}; pub const GetSeekPosError = error{GetSeekPosError}; pub const ReadError = error{ReadError}; pub const WriteError = error{WriteError}; pub const SeekableStream = io.SeekableStream(*const FileProtocol, SeekError, GetSeekPosError, seekTo, seekBy, getPos, getEndPos); pub const Reader = io.Reader(*const FileProtocol, ReadError, readFn); pub const Writer = io.Writer(*const FileProtocol, WriteError, writeFn); pub fn seekableStream(self: *FileProtocol) SeekableStream { return .{ .context = self }; } pub fn reader(self: *FileProtocol) Reader { return .{ .context = self }; } pub fn writer(self: *FileProtocol) Writer { return .{ .context = self }; } pub fn open(self: *const FileProtocol, new_handle: **const FileProtocol, file_name: [*:0]const u16, open_mode: u64, attributes: u64) Status { return self._open(self, new_handle, file_name, open_mode, attributes); } pub fn close(self: *const FileProtocol) Status { return self._close(self); } pub fn delete(self: *const FileProtocol) Status { return self._delete(self); } pub fn read(self: *const FileProtocol, buffer_size: *usize, buffer: [*]u8) Status { return self._read(self, buffer_size, buffer); } fn readFn(self: *const FileProtocol, buffer: []u8) ReadError!usize { var size: usize = buffer.len; if (.Success != self.read(&size, buffer.ptr)) return ReadError.ReadError; return size; } pub fn write(self: *const FileProtocol, buffer_size: *usize, buffer: [*]const u8) Status { return self._write(self, buffer_size, buffer); } fn writeFn(self: *const FileProtocol, bytes: []const u8) WriteError!usize { var size: usize = bytes.len; if (.Success != self.write(&size, bytes.ptr)) return WriteError.WriteError; return size; } pub fn getPosition(self: *const FileProtocol, position: *u64) Status { return self._get_position(self, position); } fn getPos(self: *const FileProtocol) GetSeekPosError!u64 { var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return GetSeekPosError.GetSeekPosError; return pos; } fn getEndPos(self: *const FileProtocol) GetSeekPosError!u64 { // preserve the old file position var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return GetSeekPosError.GetSeekPosError; // seek to end of file to get position = file size if (.Success != self.setPosition(efi_file_position_end_of_file)) return GetSeekPosError.GetSeekPosError; // restore the old position if (.Success != self.setPosition(pos)) return GetSeekPosError.GetSeekPosError; // return the file size = position return pos; } pub fn setPosition(self: *const FileProtocol, position: u64) Status { return self._set_position(self, position); } fn seekTo(self: *const FileProtocol, pos: u64) SeekError!void { if (.Success != self.setPosition(pos)) return SeekError.SeekError; } fn seekBy(self: *const FileProtocol, offset: i64) SeekError!void { // save the old position and calculate the delta var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return SeekError.SeekError; const seek_back = offset < 0; const amt = std.math.absCast(offset); if (seek_back) { pos += amt; } else { pos -= amt; } if (.Success != self.setPosition(pos)) return SeekError.SeekError; } pub fn getInfo(self: *const FileProtocol, information_type: *align(8) const Guid, buffer_size: *usize, buffer: [*]u8) Status { return self._get_info(self, information_type, buffer_size, buffer); } pub fn setInfo(self: *const FileProtocol, information_type: *align(8) const Guid, buffer_size: usize, buffer: [*]const u8) Status { return self._set_info(self, information_type, buffer_size, buffer); } pub fn flush(self: *const FileProtocol) Status { return self._flush(self); } pub const guid align(8) = Guid{ .time_low = 0x09576e92, .time_mid = 0x6d3f, .time_high_and_version = 0x11d2, .clock_seq_high_and_reserved = 0x8e, .clock_seq_low = 0x39, .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b }, }; pub const efi_file_mode_read: u64 = 0x0000000000000001; pub const efi_file_mode_write: u64 = 0x0000000000000002; pub const efi_file_mode_create: u64 = 0x8000000000000000; pub const efi_file_read_only: u64 = 0x0000000000000001; pub const efi_file_hidden: u64 = 0x0000000000000002; pub const efi_file_system: u64 = 0x0000000000000004; pub const efi_file_reserved: u64 = 0x0000000000000008; pub const efi_file_directory: u64 = 0x0000000000000010; pub const efi_file_archive: u64 = 0x0000000000000020; pub const efi_file_valid_attr: u64 = 0x0000000000000037; pub const efi_file_position_end_of_file: u64 = 0xffffffffffffffff; }; pub const FileInfo = extern struct { size: u64, file_size: u64, physical_size: u64, create_time: Time, last_access_time: Time, modification_time: Time, attribute: u64, pub fn getFileName(self: *const FileInfo) [*:0]const u16 { return @ptrCast([*:0]const u16, @ptrCast([*]const u8, self) + @sizeOf(FileInfo)); } pub const efi_file_read_only: u64 = 0x0000000000000001; pub const efi_file_hidden: u64 = 0x0000000000000002; pub const efi_file_system: u64 = 0x0000000000000004; pub const efi_file_reserved: u64 = 0x0000000000000008; pub const efi_file_directory: u64 = 0x0000000000000010; pub const efi_file_archive: u64 = 0x0000000000000020; pub const efi_file_valid_attr: u64 = 0x0000000000000037; };
lib/std/os/uefi/protocols/file_protocol.zig
pub const GLFWglproc = ?fn () callconv(.C) void; pub const struct_GLFWmonitor = opaque {}; pub const GLFWmonitor = struct_GLFWmonitor; pub const struct_GLFWwindow = opaque {}; pub const GLFWwindow = struct_GLFWwindow; pub const struct_GLFWcursor = opaque {}; pub const GLFWcursor = struct_GLFWcursor; pub const GLFWerrorfun = ?fn (c_int, [*c]const u8) callconv(.C) void; pub const GLFWwindowposfun = ?fn (?*GLFWwindow, c_int, c_int) callconv(.C) void; pub const GLFWwindowsizefun = ?fn (?*GLFWwindow, c_int, c_int) callconv(.C) void; pub const GLFWwindowclosefun = ?fn (?*GLFWwindow) callconv(.C) void; pub const GLFWwindowrefreshfun = ?fn (?*GLFWwindow) callconv(.C) void; pub const GLFWwindowfocusfun = ?fn (?*GLFWwindow, c_int) callconv(.C) void; pub const GLFWwindowiconifyfun = ?fn (?*GLFWwindow, c_int) callconv(.C) void; pub const GLFWwindowmaximizefun = ?fn (?*GLFWwindow, c_int) callconv(.C) void; pub const GLFWframebuffersizefun = ?fn (?*GLFWwindow, c_int, c_int) callconv(.C) void; pub const GLFWwindowcontentscalefun = ?fn (?*GLFWwindow, f32, f32) callconv(.C) void; pub const GLFWmousebuttonfun = ?fn (?*GLFWwindow, c_int, c_int, c_int) callconv(.C) void; pub const GLFWcursorposfun = ?fn (?*GLFWwindow, f64, f64) callconv(.C) void; pub const GLFWcursorenterfun = ?fn (?*GLFWwindow, c_int) callconv(.C) void; pub const GLFWscrollfun = ?fn (?*GLFWwindow, f64, f64) callconv(.C) void; pub const GLFWkeyfun = ?fn (?*GLFWwindow, c_int, c_int, c_int, c_int) callconv(.C) void; pub const GLFWcharfun = ?fn (?*GLFWwindow, c_uint) callconv(.C) void; pub const GLFWcharmodsfun = ?fn (?*GLFWwindow, c_uint, c_int) callconv(.C) void; pub const GLFWdropfun = ?fn (?*GLFWwindow, c_int, [*c][*c]const u8) callconv(.C) void; pub const GLFWmonitorfun = ?fn (?*GLFWmonitor, c_int) callconv(.C) void; pub const GLFWjoystickfun = ?fn (c_int, c_int) callconv(.C) void; pub const struct_GLFWvidmode = extern struct { width: c_int, height: c_int, redBits: c_int, greenBits: c_int, blueBits: c_int, refreshRate: c_int, }; pub const GLFWvidmode = struct_GLFWvidmode; pub const struct_GLFWgammaramp = extern struct { red: [*c]c_ushort, green: [*c]c_ushort, blue: [*c]c_ushort, size: c_uint, }; pub const GLFWgammaramp = struct_GLFWgammaramp; pub const struct_GLFWimage = extern struct { width: c_int, height: c_int, pixels: [*c]u8, }; pub const GLFWimage = struct_GLFWimage; pub const struct_GLFWgamepadstate = extern struct { buttons: [15]u8, axes: [6]f32, }; pub const GLFWgamepadstate = struct_GLFWgamepadstate; pub extern fn glfwInit() c_int; pub extern fn glfwTerminate() void; pub extern fn glfwInitHint(hint: c_int, value: c_int) void; pub extern fn glfwGetVersion(major: [*c]c_int, minor: [*c]c_int, rev: [*c]c_int) void; pub extern fn glfwGetVersionString() [*c]const u8; pub extern fn glfwGetError(description: [*c][*c]const u8) c_int; pub extern fn glfwSetErrorCallback(callback: GLFWerrorfun) GLFWerrorfun; pub extern fn glfwGetMonitors(count: [*c]c_int) [*c]?*GLFWmonitor; pub extern fn glfwGetPrimaryMonitor() ?*GLFWmonitor; pub extern fn glfwGetMonitorPos(monitor: ?*GLFWmonitor, xpos: [*c]c_int, ypos: [*c]c_int) void; pub extern fn glfwGetMonitorWorkarea(monitor: ?*GLFWmonitor, xpos: [*c]c_int, ypos: [*c]c_int, width: [*c]c_int, height: [*c]c_int) void; pub extern fn glfwGetMonitorPhysicalSize(monitor: ?*GLFWmonitor, widthMM: [*c]c_int, heightMM: [*c]c_int) void; pub extern fn glfwGetMonitorContentScale(monitor: ?*GLFWmonitor, xscale: [*c]f32, yscale: [*c]f32) void; pub extern fn glfwGetMonitorName(monitor: ?*GLFWmonitor) [*c]const u8; pub extern fn glfwSetMonitorUserPointer(monitor: ?*GLFWmonitor, pointer: ?*anyopaque) void; pub extern fn glfwGetMonitorUserPointer(monitor: ?*GLFWmonitor) ?*anyopaque; pub extern fn glfwSetMonitorCallback(callback: GLFWmonitorfun) GLFWmonitorfun; pub extern fn glfwGetVideoModes(monitor: ?*GLFWmonitor, count: [*c]c_int) [*c]const GLFWvidmode; pub extern fn glfwGetVideoMode(monitor: ?*GLFWmonitor) [*c]const GLFWvidmode; pub extern fn glfwSetGamma(monitor: ?*GLFWmonitor, gamma: f32) void; pub extern fn glfwGetGammaRamp(monitor: ?*GLFWmonitor) [*c]const GLFWgammaramp; pub extern fn glfwSetGammaRamp(monitor: ?*GLFWmonitor, ramp: [*c]const GLFWgammaramp) void; pub extern fn glfwDefaultWindowHints() void; pub extern fn glfwWindowHint(hint: c_int, value: c_int) void; pub extern fn glfwWindowHintString(hint: c_int, value: [*c]const u8) void; pub extern fn glfwCreateWindow(width: c_int, height: c_int, title: [*c]const u8, monitor: ?*GLFWmonitor, share: ?*GLFWwindow) ?*GLFWwindow; pub extern fn glfwDestroyWindow(window: ?*GLFWwindow) void; pub extern fn glfwWindowShouldClose(window: ?*GLFWwindow) c_int; pub extern fn glfwSetWindowShouldClose(window: ?*GLFWwindow, value: c_int) void; pub extern fn glfwSetWindowTitle(window: ?*GLFWwindow, title: [*c]const u8) void; pub extern fn glfwSetWindowIcon(window: ?*GLFWwindow, count: c_int, images: [*c]const GLFWimage) void; pub extern fn glfwGetWindowPos(window: ?*GLFWwindow, xpos: [*c]c_int, ypos: [*c]c_int) void; pub extern fn glfwSetWindowPos(window: ?*GLFWwindow, xpos: c_int, ypos: c_int) void; pub extern fn glfwGetWindowSize(window: ?*GLFWwindow, width: [*c]c_int, height: [*c]c_int) void; pub extern fn glfwSetWindowSizeLimits(window: ?*GLFWwindow, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int) void; pub extern fn glfwSetWindowAspectRatio(window: ?*GLFWwindow, numer: c_int, denom: c_int) void; pub extern fn glfwSetWindowSize(window: ?*GLFWwindow, width: c_int, height: c_int) void; pub extern fn glfwGetFramebufferSize(window: ?*GLFWwindow, width: [*c]c_int, height: [*c]c_int) void; pub extern fn glfwGetWindowFrameSize(window: ?*GLFWwindow, left: [*c]c_int, top: [*c]c_int, right: [*c]c_int, bottom: [*c]c_int) void; pub extern fn glfwGetWindowContentScale(window: ?*GLFWwindow, xscale: [*c]f32, yscale: [*c]f32) void; pub extern fn glfwGetWindowOpacity(window: ?*GLFWwindow) f32; pub extern fn glfwSetWindowOpacity(window: ?*GLFWwindow, opacity: f32) void; pub extern fn glfwIconifyWindow(window: ?*GLFWwindow) void; pub extern fn glfwRestoreWindow(window: ?*GLFWwindow) void; pub extern fn glfwMaximizeWindow(window: ?*GLFWwindow) void; pub extern fn glfwShowWindow(window: ?*GLFWwindow) void; pub extern fn glfwHideWindow(window: ?*GLFWwindow) void; pub extern fn glfwFocusWindow(window: ?*GLFWwindow) void; pub extern fn glfwRequestWindowAttention(window: ?*GLFWwindow) void; pub extern fn glfwGetWindowMonitor(window: ?*GLFWwindow) ?*GLFWmonitor; pub extern fn glfwSetWindowMonitor(window: ?*GLFWwindow, monitor: ?*GLFWmonitor, xpos: c_int, ypos: c_int, width: c_int, height: c_int, refreshRate: c_int) void; pub extern fn glfwGetWindowAttrib(window: ?*GLFWwindow, attrib: c_int) c_int; pub extern fn glfwSetWindowAttrib(window: ?*GLFWwindow, attrib: c_int, value: c_int) void; pub extern fn glfwSetWindowUserPointer(window: ?*GLFWwindow, pointer: ?*anyopaque) void; pub extern fn glfwGetWindowUserPointer(window: ?*GLFWwindow) ?*anyopaque; pub extern fn glfwSetWindowPosCallback(window: ?*GLFWwindow, callback: GLFWwindowposfun) GLFWwindowposfun; pub extern fn glfwSetWindowSizeCallback(window: ?*GLFWwindow, callback: GLFWwindowsizefun) GLFWwindowsizefun; pub extern fn glfwSetWindowCloseCallback(window: ?*GLFWwindow, callback: GLFWwindowclosefun) GLFWwindowclosefun; pub extern fn glfwSetWindowRefreshCallback(window: ?*GLFWwindow, callback: GLFWwindowrefreshfun) GLFWwindowrefreshfun; pub extern fn glfwSetWindowFocusCallback(window: ?*GLFWwindow, callback: GLFWwindowfocusfun) GLFWwindowfocusfun; pub extern fn glfwSetWindowIconifyCallback(window: ?*GLFWwindow, callback: GLFWwindowiconifyfun) GLFWwindowiconifyfun; pub extern fn glfwSetWindowMaximizeCallback(window: ?*GLFWwindow, callback: GLFWwindowmaximizefun) GLFWwindowmaximizefun; pub extern fn glfwSetFramebufferSizeCallback(window: ?*GLFWwindow, callback: GLFWframebuffersizefun) GLFWframebuffersizefun; pub extern fn glfwSetWindowContentScaleCallback(window: ?*GLFWwindow, callback: GLFWwindowcontentscalefun) GLFWwindowcontentscalefun; pub extern fn glfwPollEvents() void; pub extern fn glfwWaitEvents() void; pub extern fn glfwWaitEventsTimeout(timeout: f64) void; pub extern fn glfwPostEmptyEvent() void; pub extern fn glfwGetInputMode(window: ?*GLFWwindow, mode: c_int) c_int; pub extern fn glfwSetInputMode(window: ?*GLFWwindow, mode: c_int, value: c_int) void; pub extern fn glfwRawMouseMotionSupported() c_int; pub extern fn glfwGetKeyName(key: c_int, scancode: c_int) [*c]const u8; pub extern fn glfwGetKeyScancode(key: c_int) c_int; pub extern fn glfwGetKey(window: ?*GLFWwindow, key: c_int) c_int; pub extern fn glfwGetMouseButton(window: ?*GLFWwindow, button: c_int) c_int; pub extern fn glfwGetCursorPos(window: ?*GLFWwindow, xpos: [*c]f64, ypos: [*c]f64) void; pub extern fn glfwSetCursorPos(window: ?*GLFWwindow, xpos: f64, ypos: f64) void; pub extern fn glfwCreateCursor(image: [*c]const GLFWimage, xhot: c_int, yhot: c_int) ?*GLFWcursor; pub extern fn glfwCreateStandardCursor(shape: c_int) ?*GLFWcursor; pub extern fn glfwDestroyCursor(cursor: ?*GLFWcursor) void; pub extern fn glfwSetCursor(window: ?*GLFWwindow, cursor: ?*GLFWcursor) void; pub extern fn glfwSetKeyCallback(window: ?*GLFWwindow, callback: GLFWkeyfun) GLFWkeyfun; pub extern fn glfwSetCharCallback(window: ?*GLFWwindow, callback: GLFWcharfun) GLFWcharfun; pub extern fn glfwSetCharModsCallback(window: ?*GLFWwindow, callback: GLFWcharmodsfun) GLFWcharmodsfun; pub extern fn glfwSetMouseButtonCallback(window: ?*GLFWwindow, callback: GLFWmousebuttonfun) GLFWmousebuttonfun; pub extern fn glfwSetCursorPosCallback(window: ?*GLFWwindow, callback: GLFWcursorposfun) GLFWcursorposfun; pub extern fn glfwSetCursorEnterCallback(window: ?*GLFWwindow, callback: GLFWcursorenterfun) GLFWcursorenterfun; pub extern fn glfwSetScrollCallback(window: ?*GLFWwindow, callback: GLFWscrollfun) GLFWscrollfun; pub extern fn glfwSetDropCallback(window: ?*GLFWwindow, callback: GLFWdropfun) GLFWdropfun; pub extern fn glfwJoystickPresent(jid: c_int) c_int; pub extern fn glfwGetJoystickAxes(jid: c_int, count: [*c]c_int) [*c]const f32; pub extern fn glfwGetJoystickButtons(jid: c_int, count: [*c]c_int) [*c]const u8; pub extern fn glfwGetJoystickHats(jid: c_int, count: [*c]c_int) [*c]const u8; pub extern fn glfwGetJoystickName(jid: c_int) [*c]const u8; pub extern fn glfwGetJoystickGUID(jid: c_int) [*c]const u8; pub extern fn glfwSetJoystickUserPointer(jid: c_int, pointer: ?*anyopaque) void; pub extern fn glfwGetJoystickUserPointer(jid: c_int) ?*anyopaque; pub extern fn glfwJoystickIsGamepad(jid: c_int) c_int; pub extern fn glfwSetJoystickCallback(callback: GLFWjoystickfun) GLFWjoystickfun; pub extern fn glfwUpdateGamepadMappings(string: [*c]const u8) c_int; pub extern fn glfwGetGamepadName(jid: c_int) [*c]const u8; pub extern fn glfwGetGamepadState(jid: c_int, state: [*c]GLFWgamepadstate) c_int; pub extern fn glfwSetClipboardString(window: ?*GLFWwindow, string: [*c]const u8) void; pub extern fn glfwGetClipboardString(window: ?*GLFWwindow) [*c]const u8; pub extern fn glfwGetTime() f64; pub extern fn glfwSetTime(time: f64) void; pub extern fn glfwGetTimerValue() u64; pub extern fn glfwGetTimerFrequency() u64; pub extern fn glfwMakeContextCurrent(window: ?*GLFWwindow) void; pub extern fn glfwGetCurrentContext() ?*GLFWwindow; pub extern fn glfwSwapBuffers(window: ?*GLFWwindow) void; pub extern fn glfwSwapInterval(interval: c_int) void; pub extern fn glfwExtensionSupported(extension: [*c]const u8) c_int; pub extern fn glfwGetProcAddress(procname: [*c]const u8) GLFWglproc; pub extern fn glfwVulkanSupported() c_int; pub extern fn glfwGetRequiredInstanceExtensions(count: [*c]u32) [*c][*c]const u8; pub const GLFW_VERSION_MAJOR = @as(c_int, 3); pub const GLFW_VERSION_MINOR = @as(c_int, 3); pub const GLFW_VERSION_REVISION = @as(c_int, 4); pub const GLFW_TRUE = @as(c_int, 1); pub const GLFW_FALSE = @as(c_int, 0); pub const GLFW_RELEASE = @as(c_int, 0); pub const GLFW_PRESS = @as(c_int, 1); pub const GLFW_REPEAT = @as(c_int, 2); pub const GLFW_HAT_CENTERED = @as(c_int, 0); pub const GLFW_HAT_UP = @as(c_int, 1); pub const GLFW_HAT_RIGHT = @as(c_int, 2); pub const GLFW_HAT_DOWN = @as(c_int, 4); pub const GLFW_HAT_LEFT = @as(c_int, 8); pub const GLFW_HAT_RIGHT_UP = GLFW_HAT_RIGHT | GLFW_HAT_UP; pub const GLFW_HAT_RIGHT_DOWN = GLFW_HAT_RIGHT | GLFW_HAT_DOWN; pub const GLFW_HAT_LEFT_UP = GLFW_HAT_LEFT | GLFW_HAT_UP; pub const GLFW_HAT_LEFT_DOWN = GLFW_HAT_LEFT | GLFW_HAT_DOWN; pub const GLFW_KEY_UNKNOWN = -@as(c_int, 1); pub const GLFW_KEY_SPACE = @as(c_int, 32); pub const GLFW_KEY_APOSTROPHE = @as(c_int, 39); pub const GLFW_KEY_COMMA = @as(c_int, 44); pub const GLFW_KEY_MINUS = @as(c_int, 45); pub const GLFW_KEY_PERIOD = @as(c_int, 46); pub const GLFW_KEY_SLASH = @as(c_int, 47); pub const GLFW_KEY_0 = @as(c_int, 48); pub const GLFW_KEY_1 = @as(c_int, 49); pub const GLFW_KEY_2 = @as(c_int, 50); pub const GLFW_KEY_3 = @as(c_int, 51); pub const GLFW_KEY_4 = @as(c_int, 52); pub const GLFW_KEY_5 = @as(c_int, 53); pub const GLFW_KEY_6 = @as(c_int, 54); pub const GLFW_KEY_7 = @as(c_int, 55); pub const GLFW_KEY_8 = @as(c_int, 56); pub const GLFW_KEY_9 = @as(c_int, 57); pub const GLFW_KEY_SEMICOLON = @as(c_int, 59); pub const GLFW_KEY_EQUAL = @as(c_int, 61); pub const GLFW_KEY_A = @as(c_int, 65); pub const GLFW_KEY_B = @as(c_int, 66); pub const GLFW_KEY_C = @as(c_int, 67); pub const GLFW_KEY_D = @as(c_int, 68); pub const GLFW_KEY_E = @as(c_int, 69); pub const GLFW_KEY_F = @as(c_int, 70); pub const GLFW_KEY_G = @as(c_int, 71); pub const GLFW_KEY_H = @as(c_int, 72); pub const GLFW_KEY_I = @as(c_int, 73); pub const GLFW_KEY_J = @as(c_int, 74); pub const GLFW_KEY_K = @as(c_int, 75); pub const GLFW_KEY_L = @as(c_int, 76); pub const GLFW_KEY_M = @as(c_int, 77); pub const GLFW_KEY_N = @as(c_int, 78); pub const GLFW_KEY_O = @as(c_int, 79); pub const GLFW_KEY_P = @as(c_int, 80); pub const GLFW_KEY_Q = @as(c_int, 81); pub const GLFW_KEY_R = @as(c_int, 82); pub const GLFW_KEY_S = @as(c_int, 83); pub const GLFW_KEY_T = @as(c_int, 84); pub const GLFW_KEY_U = @as(c_int, 85); pub const GLFW_KEY_V = @as(c_int, 86); pub const GLFW_KEY_W = @as(c_int, 87); pub const GLFW_KEY_X = @as(c_int, 88); pub const GLFW_KEY_Y = @as(c_int, 89); pub const GLFW_KEY_Z = @as(c_int, 90); pub const GLFW_KEY_LEFT_BRACKET = @as(c_int, 91); pub const GLFW_KEY_BACKSLASH = @as(c_int, 92); pub const GLFW_KEY_RIGHT_BRACKET = @as(c_int, 93); pub const GLFW_KEY_GRAVE_ACCENT = @as(c_int, 96); pub const GLFW_KEY_WORLD_1 = @as(c_int, 161); pub const GLFW_KEY_WORLD_2 = @as(c_int, 162); pub const GLFW_KEY_ESCAPE = @as(c_int, 256); pub const GLFW_KEY_ENTER = @as(c_int, 257); pub const GLFW_KEY_TAB = @as(c_int, 258); pub const GLFW_KEY_BACKSPACE = @as(c_int, 259); pub const GLFW_KEY_INSERT = @as(c_int, 260); pub const GLFW_KEY_DELETE = @as(c_int, 261); pub const GLFW_KEY_RIGHT = @as(c_int, 262); pub const GLFW_KEY_LEFT = @as(c_int, 263); pub const GLFW_KEY_DOWN = @as(c_int, 264); pub const GLFW_KEY_UP = @as(c_int, 265); pub const GLFW_KEY_PAGE_UP = @as(c_int, 266); pub const GLFW_KEY_PAGE_DOWN = @as(c_int, 267); pub const GLFW_KEY_HOME = @as(c_int, 268); pub const GLFW_KEY_END = @as(c_int, 269); pub const GLFW_KEY_CAPS_LOCK = @as(c_int, 280); pub const GLFW_KEY_SCROLL_LOCK = @as(c_int, 281); pub const GLFW_KEY_NUM_LOCK = @as(c_int, 282); pub const GLFW_KEY_PRINT_SCREEN = @as(c_int, 283); pub const GLFW_KEY_PAUSE = @as(c_int, 284); pub const GLFW_KEY_F1 = @as(c_int, 290); pub const GLFW_KEY_F2 = @as(c_int, 291); pub const GLFW_KEY_F3 = @as(c_int, 292); pub const GLFW_KEY_F4 = @as(c_int, 293); pub const GLFW_KEY_F5 = @as(c_int, 294); pub const GLFW_KEY_F6 = @as(c_int, 295); pub const GLFW_KEY_F7 = @as(c_int, 296); pub const GLFW_KEY_F8 = @as(c_int, 297); pub const GLFW_KEY_F9 = @as(c_int, 298); pub const GLFW_KEY_F10 = @as(c_int, 299); pub const GLFW_KEY_F11 = @as(c_int, 300); pub const GLFW_KEY_F12 = @as(c_int, 301); pub const GLFW_KEY_F13 = @as(c_int, 302); pub const GLFW_KEY_F14 = @as(c_int, 303); pub const GLFW_KEY_F15 = @as(c_int, 304); pub const GLFW_KEY_F16 = @as(c_int, 305); pub const GLFW_KEY_F17 = @as(c_int, 306); pub const GLFW_KEY_F18 = @as(c_int, 307); pub const GLFW_KEY_F19 = @as(c_int, 308); pub const GLFW_KEY_F20 = @as(c_int, 309); pub const GLFW_KEY_F21 = @as(c_int, 310); pub const GLFW_KEY_F22 = @as(c_int, 311); pub const GLFW_KEY_F23 = @as(c_int, 312); pub const GLFW_KEY_F24 = @as(c_int, 313); pub const GLFW_KEY_F25 = @as(c_int, 314); pub const GLFW_KEY_KP_0 = @as(c_int, 320); pub const GLFW_KEY_KP_1 = @as(c_int, 321); pub const GLFW_KEY_KP_2 = @as(c_int, 322); pub const GLFW_KEY_KP_3 = @as(c_int, 323); pub const GLFW_KEY_KP_4 = @as(c_int, 324); pub const GLFW_KEY_KP_5 = @as(c_int, 325); pub const GLFW_KEY_KP_6 = @as(c_int, 326); pub const GLFW_KEY_KP_7 = @as(c_int, 327); pub const GLFW_KEY_KP_8 = @as(c_int, 328); pub const GLFW_KEY_KP_9 = @as(c_int, 329); pub const GLFW_KEY_KP_DECIMAL = @as(c_int, 330); pub const GLFW_KEY_KP_DIVIDE = @as(c_int, 331); pub const GLFW_KEY_KP_MULTIPLY = @as(c_int, 332); pub const GLFW_KEY_KP_SUBTRACT = @as(c_int, 333); pub const GLFW_KEY_KP_ADD = @as(c_int, 334); pub const GLFW_KEY_KP_ENTER = @as(c_int, 335); pub const GLFW_KEY_KP_EQUAL = @as(c_int, 336); pub const GLFW_KEY_LEFT_SHIFT = @as(c_int, 340); pub const GLFW_KEY_LEFT_CONTROL = @as(c_int, 341); pub const GLFW_KEY_LEFT_ALT = @as(c_int, 342); pub const GLFW_KEY_LEFT_SUPER = @as(c_int, 343); pub const GLFW_KEY_RIGHT_SHIFT = @as(c_int, 344); pub const GLFW_KEY_RIGHT_CONTROL = @as(c_int, 345); pub const GLFW_KEY_RIGHT_ALT = @as(c_int, 346); pub const GLFW_KEY_RIGHT_SUPER = @as(c_int, 347); pub const GLFW_KEY_MENU = @as(c_int, 348); pub const GLFW_KEY_LAST = GLFW_KEY_MENU; pub const GLFW_MOD_SHIFT = @as(c_int, 0x0001); pub const GLFW_MOD_CONTROL = @as(c_int, 0x0002); pub const GLFW_MOD_ALT = @as(c_int, 0x0004); pub const GLFW_MOD_SUPER = @as(c_int, 0x0008); pub const GLFW_MOD_CAPS_LOCK = @as(c_int, 0x0010); pub const GLFW_MOD_NUM_LOCK = @as(c_int, 0x0020); pub const GLFW_MOUSE_BUTTON_1 = @as(c_int, 0); pub const GLFW_MOUSE_BUTTON_2 = @as(c_int, 1); pub const GLFW_MOUSE_BUTTON_3 = @as(c_int, 2); pub const GLFW_MOUSE_BUTTON_4 = @as(c_int, 3); pub const GLFW_MOUSE_BUTTON_5 = @as(c_int, 4); pub const GLFW_MOUSE_BUTTON_6 = @as(c_int, 5); pub const GLFW_MOUSE_BUTTON_7 = @as(c_int, 6); pub const GLFW_MOUSE_BUTTON_8 = @as(c_int, 7); pub const GLFW_MOUSE_BUTTON_LAST = GLFW_MOUSE_BUTTON_8; pub const GLFW_MOUSE_BUTTON_LEFT = GLFW_MOUSE_BUTTON_1; pub const GLFW_MOUSE_BUTTON_RIGHT = GLFW_MOUSE_BUTTON_2; pub const GLFW_MOUSE_BUTTON_MIDDLE = GLFW_MOUSE_BUTTON_3; pub const GLFW_JOYSTICK_1 = @as(c_int, 0); pub const GLFW_JOYSTICK_2 = @as(c_int, 1); pub const GLFW_JOYSTICK_3 = @as(c_int, 2); pub const GLFW_JOYSTICK_4 = @as(c_int, 3); pub const GLFW_JOYSTICK_5 = @as(c_int, 4); pub const GLFW_JOYSTICK_6 = @as(c_int, 5); pub const GLFW_JOYSTICK_7 = @as(c_int, 6); pub const GLFW_JOYSTICK_8 = @as(c_int, 7); pub const GLFW_JOYSTICK_9 = @as(c_int, 8); pub const GLFW_JOYSTICK_10 = @as(c_int, 9); pub const GLFW_JOYSTICK_11 = @as(c_int, 10); pub const GLFW_JOYSTICK_12 = @as(c_int, 11); pub const GLFW_JOYSTICK_13 = @as(c_int, 12); pub const GLFW_JOYSTICK_14 = @as(c_int, 13); pub const GLFW_JOYSTICK_15 = @as(c_int, 14); pub const GLFW_JOYSTICK_16 = @as(c_int, 15); pub const GLFW_JOYSTICK_LAST = GLFW_JOYSTICK_16; pub const GLFW_GAMEPAD_BUTTON_A = @as(c_int, 0); pub const GLFW_GAMEPAD_BUTTON_B = @as(c_int, 1); pub const GLFW_GAMEPAD_BUTTON_X = @as(c_int, 2); pub const GLFW_GAMEPAD_BUTTON_Y = @as(c_int, 3); pub const GLFW_GAMEPAD_BUTTON_LEFT_BUMPER = @as(c_int, 4); pub const GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER = @as(c_int, 5); pub const GLFW_GAMEPAD_BUTTON_BACK = @as(c_int, 6); pub const GLFW_GAMEPAD_BUTTON_START = @as(c_int, 7); pub const GLFW_GAMEPAD_BUTTON_GUIDE = @as(c_int, 8); pub const GLFW_GAMEPAD_BUTTON_LEFT_THUMB = @as(c_int, 9); pub const GLFW_GAMEPAD_BUTTON_RIGHT_THUMB = @as(c_int, 10); pub const GLFW_GAMEPAD_BUTTON_DPAD_UP = @as(c_int, 11); pub const GLFW_GAMEPAD_BUTTON_DPAD_RIGHT = @as(c_int, 12); pub const GLFW_GAMEPAD_BUTTON_DPAD_DOWN = @as(c_int, 13); pub const GLFW_GAMEPAD_BUTTON_DPAD_LEFT = @as(c_int, 14); pub const GLFW_GAMEPAD_BUTTON_LAST = GLFW_GAMEPAD_BUTTON_DPAD_LEFT; pub const GLFW_GAMEPAD_BUTTON_CROSS = GLFW_GAMEPAD_BUTTON_A; pub const GLFW_GAMEPAD_BUTTON_CIRCLE = GLFW_GAMEPAD_BUTTON_B; pub const GLFW_GAMEPAD_BUTTON_SQUARE = GLFW_GAMEPAD_BUTTON_X; pub const GLFW_GAMEPAD_BUTTON_TRIANGLE = GLFW_GAMEPAD_BUTTON_Y; pub const GLFW_GAMEPAD_AXIS_LEFT_X = @as(c_int, 0); pub const GLFW_GAMEPAD_AXIS_LEFT_Y = @as(c_int, 1); pub const GLFW_GAMEPAD_AXIS_RIGHT_X = @as(c_int, 2); pub const GLFW_GAMEPAD_AXIS_RIGHT_Y = @as(c_int, 3); pub const GLFW_GAMEPAD_AXIS_LEFT_TRIGGER = @as(c_int, 4); pub const GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER = @as(c_int, 5); pub const GLFW_GAMEPAD_AXIS_LAST = GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER; pub const GLFW_NO_ERROR = @as(c_int, 0); pub const GLFW_NOT_INITIALIZED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010001, .hexadecimal); pub const GLFW_NO_CURRENT_CONTEXT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010002, .hexadecimal); pub const GLFW_INVALID_ENUM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010003, .hexadecimal); pub const GLFW_INVALID_VALUE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010004, .hexadecimal); pub const GLFW_OUT_OF_MEMORY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010005, .hexadecimal); pub const GLFW_API_UNAVAILABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010006, .hexadecimal); pub const GLFW_VERSION_UNAVAILABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010007, .hexadecimal); pub const GLFW_PLATFORM_ERROR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010008, .hexadecimal); pub const GLFW_FORMAT_UNAVAILABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010009, .hexadecimal); pub const GLFW_NO_WINDOW_CONTEXT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0001000A, .hexadecimal); pub const GLFW_FOCUSED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020001, .hexadecimal); pub const GLFW_ICONIFIED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020002, .hexadecimal); pub const GLFW_RESIZABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020003, .hexadecimal); pub const GLFW_VISIBLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020004, .hexadecimal); pub const GLFW_DECORATED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020005, .hexadecimal); pub const GLFW_AUTO_ICONIFY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020006, .hexadecimal); pub const GLFW_FLOATING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020007, .hexadecimal); pub const GLFW_MAXIMIZED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020008, .hexadecimal); pub const GLFW_CENTER_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020009, .hexadecimal); pub const GLFW_TRANSPARENT_FRAMEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002000A, .hexadecimal); pub const GLFW_HOVERED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002000B, .hexadecimal); pub const GLFW_FOCUS_ON_SHOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002000C, .hexadecimal); pub const GLFW_RED_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021001, .hexadecimal); pub const GLFW_GREEN_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021002, .hexadecimal); pub const GLFW_BLUE_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021003, .hexadecimal); pub const GLFW_ALPHA_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021004, .hexadecimal); pub const GLFW_DEPTH_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021005, .hexadecimal); pub const GLFW_STENCIL_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021006, .hexadecimal); pub const GLFW_ACCUM_RED_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021007, .hexadecimal); pub const GLFW_ACCUM_GREEN_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021008, .hexadecimal); pub const GLFW_ACCUM_BLUE_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021009, .hexadecimal); pub const GLFW_ACCUM_ALPHA_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100A, .hexadecimal); pub const GLFW_AUX_BUFFERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100B, .hexadecimal); pub const GLFW_STEREO = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100C, .hexadecimal); pub const GLFW_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100D, .hexadecimal); pub const GLFW_SRGB_CAPABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100E, .hexadecimal); pub const GLFW_REFRESH_RATE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002100F, .hexadecimal); pub const GLFW_DOUBLEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00021010, .hexadecimal); pub const GLFW_CLIENT_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022001, .hexadecimal); pub const GLFW_CONTEXT_VERSION_MAJOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022002, .hexadecimal); pub const GLFW_CONTEXT_VERSION_MINOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022003, .hexadecimal); pub const GLFW_CONTEXT_REVISION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022004, .hexadecimal); pub const GLFW_CONTEXT_ROBUSTNESS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022005, .hexadecimal); pub const GLFW_OPENGL_FORWARD_COMPAT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022006, .hexadecimal); pub const GLFW_OPENGL_DEBUG_CONTEXT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022007, .hexadecimal); pub const GLFW_OPENGL_PROFILE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022008, .hexadecimal); pub const GLFW_CONTEXT_RELEASE_BEHAVIOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00022009, .hexadecimal); pub const GLFW_CONTEXT_NO_ERROR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002200A, .hexadecimal); pub const GLFW_CONTEXT_CREATION_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002200B, .hexadecimal); pub const GLFW_SCALE_TO_MONITOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x0002200C, .hexadecimal); pub const GLFW_COCOA_RETINA_FRAMEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00023001, .hexadecimal); pub const GLFW_COCOA_FRAME_NAME = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00023002, .hexadecimal); pub const GLFW_COCOA_GRAPHICS_SWITCHING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00023003, .hexadecimal); pub const GLFW_X11_CLASS_NAME = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00024001, .hexadecimal); pub const GLFW_X11_INSTANCE_NAME = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00024002, .hexadecimal); pub const GLFW_NO_API = @as(c_int, 0); pub const GLFW_OPENGL_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00030001, .hexadecimal); pub const GLFW_OPENGL_ES_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00030002, .hexadecimal); pub const GLFW_NO_ROBUSTNESS = @as(c_int, 0); pub const GLFW_NO_RESET_NOTIFICATION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00031001, .hexadecimal); pub const GLFW_LOSE_CONTEXT_ON_RESET = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00031002, .hexadecimal); pub const GLFW_OPENGL_ANY_PROFILE = @as(c_int, 0); pub const GLFW_OPENGL_CORE_PROFILE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00032001, .hexadecimal); pub const GLFW_OPENGL_COMPAT_PROFILE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00032002, .hexadecimal); pub const GLFW_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00033001, .hexadecimal); pub const GLFW_STICKY_KEYS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00033002, .hexadecimal); pub const GLFW_STICKY_MOUSE_BUTTONS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00033003, .hexadecimal); pub const GLFW_LOCK_KEY_MODS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00033004, .hexadecimal); pub const GLFW_RAW_MOUSE_MOTION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00033005, .hexadecimal); pub const GLFW_CURSOR_NORMAL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00034001, .hexadecimal); pub const GLFW_CURSOR_HIDDEN = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00034002, .hexadecimal); pub const GLFW_CURSOR_DISABLED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00034003, .hexadecimal); pub const GLFW_ANY_RELEASE_BEHAVIOR = @as(c_int, 0); pub const GLFW_RELEASE_BEHAVIOR_FLUSH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00035001, .hexadecimal); pub const GLFW_RELEASE_BEHAVIOR_NONE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00035002, .hexadecimal); pub const GLFW_NATIVE_CONTEXT_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036001, .hexadecimal); pub const GLFW_EGL_CONTEXT_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036002, .hexadecimal); pub const GLFW_OSMESA_CONTEXT_API = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036003, .hexadecimal); pub const GLFW_ARROW_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036001, .hexadecimal); pub const GLFW_IBEAM_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036002, .hexadecimal); pub const GLFW_CROSSHAIR_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036003, .hexadecimal); pub const GLFW_HAND_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036004, .hexadecimal); pub const GLFW_HRESIZE_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036005, .hexadecimal); pub const GLFW_VRESIZE_CURSOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00036006, .hexadecimal); pub const GLFW_CONNECTED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040001, .hexadecimal); pub const GLFW_DISCONNECTED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040002, .hexadecimal); pub const GLFW_JOYSTICK_HAT_BUTTONS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00050001, .hexadecimal); pub const GLFW_COCOA_CHDIR_RESOURCES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00051001, .hexadecimal); pub const GLFW_COCOA_MENUBAR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00051002, .hexadecimal); pub const GLFW_DONT_CARE = -@as(c_int, 1);
src/pkg/glfw.zig
const std = @import("std"); const print = std.debug.print; usingnamespace @import("common.zig"); usingnamespace @import("value.zig"); pub const OpCode = enum(u8) { OP_CONSTANT, OP_NOT, OP_NEGATE, OP_NIL, OP_TRUE, OP_FALSE, OP_GET_LOCAL, OP_SET_LOCAL, OP_DEFINE_GLOBAL, OP_SET_GLOBAL, OP_GET_GLOBAL, OP_EQUAL, OP_JUMP_IF_FALSE, OP_GREATER, OP_LESS, OP_ADD, OP_SUBTRACT, OP_MULTIPLY, OP_DIVIDE, OP_POP, OP_PRINT, OP_RETURN, }; pub const Chunk = struct { code: ArrayListOfU8, constants: ArrayListOfValue, lines: ArrayListOfUsize, pub fn init(allocator: *std.mem.Allocator) Chunk { return Chunk{ .code = ArrayListOfU8.init(allocator), .constants = ArrayListOfValue.init(allocator), .lines = ArrayListOfUsize.init(allocator), }; } pub fn deinit(self: *Chunk) void { self.code.deinit(); self.constants.deinit(); self.lines.deinit(); } pub fn writeByte(self: *Chunk, byte: u8, line: usize) !void { try self.code.append(byte); try self.lines.append(line); } pub fn writeCode(self: *Chunk, code: OpCode, line: usize) !void { try self.writeByte(@enumToInt(code), line); } pub fn addConstant(self: *Chunk, value: Value) !u8 { try self.constants.append(value); return @intCast(u8, self.constants.items.len - 1); } pub fn disassemble(self: *Chunk, name: []const u8) void { print("{:=^50}\n", .{name}); var offset: usize = 0; while (offset < self.code.items.len) { offset = self.disassembleInstruction(offset); } print("\n", .{}); } pub fn disassembleInstruction(self: *Chunk, offset: usize) usize { print("{:0>4} ", .{offset}); if (offset > 0 and self.lines.items[offset] == self.lines.items[offset - 1]) { print(" | ", .{}); } else { print("{:0>4} ", .{self.lines.items[offset]}); } const instruction = @intToEnum(OpCode, self.code.items[offset]); switch (instruction) { .OP_RETURN, .OP_NEGATE, .OP_ADD, .OP_SUBTRACT, .OP_MULTIPLY, .OP_DIVIDE, .OP_NIL, .OP_TRUE, .OP_FALSE, .OP_NOT, .OP_GREATER, .OP_LESS, .OP_EQUAL, .OP_PRINT, .OP_POP, => return simpleInstruction(@tagName(instruction), offset), .OP_CONSTANT, .OP_DEFINE_GLOBAL, .OP_SET_GLOBAL, .OP_GET_GLOBAL, => return self.constantInstruction(@tagName(instruction), offset), .OP_GET_LOCAL, .OP_SET_LOCAL, => return self.byteInstrution(@tagName(instruction), offset), .OP_JUMP_IF_FALSE => return self.jumpInstruction(1, @tagName(instruction), offset), } } fn simpleInstruction(name: []const u8, offset: usize) usize { print("{:<16}\n", .{name}); return offset + 1; } fn constantInstruction(self: *Chunk, name: []const u8, offset: usize) usize { const constant = self.code.items[offset + 1]; print("{:<16} {} '", .{ name, constant }); printValue(self.constants.items[constant]); print("'\n", .{}); return offset + 2; } fn jumpInstruction(self: *Chunk, sign: i32, name: []const u8, offset: usize) usize { var jump = @intCast(u16, self.code.items[offset + 1]) << 8; jump |= self.code.items[offset + 2]; print("{s:<16} {:>4} -> {}\n", .{ name, offset, @intCast(i32, offset) + 3 + @intCast(i32, sign) * @intCast(i32, jump) }); return offset + 3; } fn byteInstrution(self: *Chunk, name: []const u8, offset: usize) usize { const slot = self.code.items[offset + 1]; print("{:<16} {:0>4}\n", .{ name, slot }); return offset + 2; } };
vm/src/chunk.zig
const c = @import("c.zig"); const nk = @import("../nuklear.zig"); const std = @import("std"); const builtin = std.builtin; const debug = std.debug; const heap = std.heap; const math = std.math; const mem = std.mem; const meta = std.meta; const testing = std.testing; pub const Config = c.struct_nk_font_config; pub const Font = c.struct_nk_font; pub const Format = c.nk_font_atlas_format; pub fn init(allocator: *mem.Allocator) nk.FontAtlas { var res: nk.FontAtlas = undefined; c.nk_font_atlas_init(&res, &nk.allocator(allocator)); return res; } pub fn initCustom(persistent: *mem.Allocator, transient: *mem.Allocator) nk.FontAtlas { var res: nk.FontAtlas = undefined; c.nk_font_atlas_init_custom( &res, &nk.allocator(persistent), &nk.allocator(transient), ); return res; } pub fn cleanup(atlas: *nk.FontAtlas) void { c.nk_font_atlas_cleanup(atlas); } pub fn clear(atlas: *nk.FontAtlas) void { c.nk_font_atlas_clear(atlas); } pub fn begin(atlas: *nk.FontAtlas) void { c.nk_font_atlas_begin(atlas); } pub fn add(atlas: *nk.FontAtlas, config: ?*const Config) !*Font { return c.nk_font_atlas_add(atlas, config) orelse return error.OutOfMemory; } pub fn addDefault(atlas: *nk.FontAtlas, height: f32, config: ?*const Config) !*Font { return c.nk_font_atlas_add_default(atlas, height, config) orelse return error.OutOfMemory; } pub fn addFromMemory( atlas: *nk.FontAtlas, memory: []const u8, height: f32, config: ?*const Config, ) !*Font { const ptr = @ptrCast(*const c_void, memory.ptr); return c.nk_font_atlas_add_from_memory(atlas, ptr, memory.len, height, config) orelse return error.OutOfMemory; } pub fn addCompressed( atlas: *nk.FontAtlas, data: []const u8, height: f32, config: ?*const Config, ) !*Font { const ptr = @ptrCast(*const c_void, data.ptr); return c.nk_font_atlas_add_compressed(atlas, ptr, data.len, height, config) orelse return error.OutOfMemory; } pub fn addCompressedBase85( atlas: *nk.FontAtlas, data: []const u8, height: f32, config: ?*const Config, ) !*Font { return c.nk_font_atlas_add_compressed_base85(atlas, nk.slice(data), height, config) orelse return error.OutOfMemory; } pub fn bake(atlas: *nk.FontAtlas, format: Format) !Baked { var res: Baked = undefined; const data = c.nk_font_atlas_bake(atlas, &res.w, &res.h, format) orelse return error.OutOfMemory; res.data = @ptrCast([*]const u8, data); return res; } pub fn end(atlas: *nk.FontAtlas, tex: nk.Handle, null_tex: ?*c.nk_draw_null_texture) void { c.nk_font_atlas_end(atlas, tex, null_tex); } pub const Baked = struct { data: [*]const u8, w: c_int, h: c_int, }; test { testing.refAllDecls(@This()); }
src/atlas.zig
const std = @import("std"); const assert = std.debug.assert; pub const Computer = struct { rom: [4096]i32, ram: [4096]i32, pos: usize, const OP = enum(u32) { ADD = 1, MUL = 2, RDSV = 3, PRINT = 4, JIT = 5, JIF = 6, CLT = 7, CEQ = 8, HALT = 99, }; const MODE = enum(u32) { POSITION = 0, IMMEDIATE = 1, }; pub fn init(str: []const u8) Computer { var self = Computer{ .rom = undefined, .ram = undefined, .pos = 0, }; var it = std.mem.split(u8, str, ","); while (it.next()) |what| { const instr = std.fmt.parseInt(i32, what, 10) catch unreachable; self.rom[self.pos] = instr; self.pos += 1; } return self; } pub fn get(self: Computer, pos: usize) i32 { return self.ram[pos]; } pub fn set(self: *Computer, pos: usize, val: i32) void { self.ram[pos] = val; } pub fn run(self: *Computer, input: i32) i32 { var pc: usize = 0; var done = false; self.ram = self.rom; var last_printed: i32 = undefined; while (true) { var instr: u32 = @intCast(u32, self.ram[pc + 0]); // std.debug.warn("instr: {}\n", instr); const op = @intToEnum(OP, instr % 100); instr /= 100; const m1 = @intToEnum(MODE, instr % 10); instr /= 10; const m2 = @intToEnum(MODE, instr % 10); instr /= 10; // const m3 = @intToEnum(MODE, instr % 10); instr /= 10; switch (op) { OP.HALT => { // std.debug.warn("HALT\n"); done = true; break; }, OP.ADD => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); const p3 = self.ram[pc + 3]; // std.debug.warn("ADD: {} = {} + {}\n", p3, v1, v2); self.ram[@intCast(usize, p3)] = v1 + v2; pc += 4; }, OP.MUL => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); const p3 = self.ram[pc + 3]; // std.debug.warn("MUL: {} = {} * {}\n", p3, v1, v2); self.ram[@intCast(usize, p3)] = v1 * v2; pc += 4; }, OP.RDSV => { const p1 = self.ram[pc + 1]; // std.debug.warn("RDSV: {} = {}\n", p1, input); self.ram[@intCast(usize, p1)] = input; pc += 2; }, OP.PRINT => { const v1 = self.decode(pc, 1, m1); // std.debug.warn("PRINT: {}\n", v1); last_printed = v1; pc += 2; }, OP.JIT => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); // std.debug.warn("JIT: {} {}\n", v1, v2); if (v1 == 0) { pc += 3; } else { pc = @intCast(usize, v2); } }, OP.JIF => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); // std.debug.warn("JIF: {} {}\n", v1, v2); if (v1 == 0) { pc = @intCast(usize, v2); } else { pc += 3; } }, OP.CLT => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); const p3 = self.ram[pc + 3]; // std.debug.warn("CLT: {} = {} LT {}\n", p3, v1, v2); self.ram[@intCast(usize, p3)] = if (v1 < v2) 1 else 0; pc += 4; }, OP.CEQ => { const v1 = self.decode(pc, 1, m1); const v2 = self.decode(pc, 2, m2); const p3 = self.ram[pc + 3]; // std.debug.warn("CEQ: {} = {} EQ {}\n", p3, v1, v2); self.ram[@intCast(usize, p3)] = if (v1 == v2) 1 else 0; pc += 4; }, } } return last_printed; } fn decode(self: Computer, pc: usize, pos: usize, mode: MODE) i32 { const p = self.ram[pc + pos]; const v: i32 = switch (mode) { MODE.POSITION => self.ram[@intCast(usize, p)], MODE.IMMEDIATE => p, }; return v; } }; test "position mode - 1 if input equal to 8" { const data: []const u8 = "3,9,8,9,10,9,4,9,99,-1,8"; var computer = Computer.init(data[0..]); assert(computer.run(7) == 0); assert(computer.run(8) == 1); assert(computer.run(9) == 0); } test "position mode - 1 if input less than 8" { const data: []const u8 = "3,9,7,9,10,9,4,9,99,-1,8"; var computer = Computer.init(data[0..]); assert(computer.run(7) == 1); assert(computer.run(8) == 0); assert(computer.run(9) == 0); } test "immediate mode - 1 if input equal to 8" { const data: []const u8 = "3,3,1108,-1,8,3,4,3,99"; var computer = Computer.init(data[0..]); assert(computer.run(7) == 0); assert(computer.run(8) == 1); assert(computer.run(9) == 0); } test "immediate mode - 1 if input less than 8" { const data: []const u8 = "3,3,1107,-1,8,3,4,3,99"; var computer = Computer.init(data[0..]); assert(computer.run(7) == 1); assert(computer.run(8) == 0); assert(computer.run(9) == 0); } test "position mode - 0 if input is zero" { const data: []const u8 = "3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9"; var computer = Computer.init(data[0..]); assert(computer.run(0) == 0); assert(computer.run(1) == 1); assert(computer.run(2) == 1); } test "immediate mode - 0 if input is zero" { const data: []const u8 = "3,3,1105,-1,9,1101,0,0,12,4,12,99,1"; var computer = Computer.init(data[0..]); assert(computer.run(0) == 0); assert(computer.run(1) == 1); assert(computer.run(2) == 1); } test "immediate mode - multitest for 8" { const data: []const u8 = "3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99"; var computer = Computer.init(data[0..]); assert(computer.run(7) == 999); assert(computer.run(8) == 1000); assert(computer.run(9) == 1001); }
2019/p05/computer.zig
pub const Letter = enum { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, const Self = @This(); pub fn fromChar(comptime c: u8) Self { return switch (c) { 'a','A' => .a, 'b','B' => .b, 'c','C' => .c, 'd','D' => .d, 'e','E' => .e, 'f','F' => .f, 'g','G' => .g, 'h','H' => .h, 'i','I' => .i, 'j','J' => .j, 'k','K' => .k, 'l','L' => .l, 'm','M' => .m, 'n','N' => .n, 'o','O' => .o, 'p','P' => .p, 'q','Q' => .q, 'r','R' => .r, 's','S' => .s, 't','T' => .t, 'u','U' => .u, 'v','V' => .v, 'w','W' => .w, 'x','X' => .x, 'y','Y' => .y, 'z','Z' => .z, '0' => .n0, '1' => .n1, '2' => .n2, '3' => .n3, '4' => .n4, '5' => .n5, '6' => .n6, '7' => .n7, '8' => .n8, '9' => .n9, else => { @compileLog(c); @compileError("Unsupported character graphics!"); }, }; } pub fn toGraphics(comptime self: Self) [4]u8 { return comptime blk: { break :blk switch (self) { .a => A, .b => B, .c => C, .d => D, .e => E, .f => F, .g => G, .h => H, .i => I, .j => J, .k => K, .l => L, .m => M, .n => N, .o => O, .p => P, .q => Q, .r => R, .s => S, .t => T, .u => U, .v => V, .w => W, .x => X, .y => Y, .z => Z, .n0 => n0, .n1 => n1, .n2 => n2, .n3 => n3, .n4 => n4, .n5 => n5, .n6 => n6, .n7 => n7, .n8 => n8, .n9 => n9, }; }; } }; pub fn encode(comptime text: []const u8) [text.len]?[4]u8 { comptime var graphics: [text.len]?[4]u8 = undefined; inline for (text) |c, i| { comptime { if ( c == ' ' ) { graphics[i] = null; } else { graphics[i] = Letter.fromChar(c).toGraphics(); } } } return graphics; } pub const A = [4]u8{ 0b11011111, 0b10101111, 0b10001111, 0b10101111, }; pub const B = [4]u8{ 0b10111111, 0b10001111, 0b10101111, 0b10001111, }; pub const C = [4]u8{ 0b10001111, 0b10111111, 0b10111111, 0b10001111, }; pub const D = [4]u8{ 0b10011111, 0b10101111, 0b10101111, 0b10011111, }; pub const E = [4]u8{ 0b10001111, 0b10001111, 0b10111111, 0b10001111, }; pub const F = [4]u8{ 0b10001111, 0b10111111, 0b10011111, 0b10111111, }; pub const G = [4]u8{ 0b10001111, 0b10111111, 0b10101111, 0b10001111, }; pub const H = [4]u8{ 0b10111111, 0b10111111, 0b10001111, 0b10101111, }; pub const I = [4]u8{ 0b10001111, 0b11011111, 0b11011111, 0b10001111, }; pub const J = [4]u8{ 0b10001111, 0b11101111, 0b10101111, 0b10011111, }; pub const K = [4]u8{ 0b10101111, 0b10011111, 0b10011111, 0b10101111, }; pub const L = [4]u8{ 0b10111111, 0b10111111, 0b10111111, 0b10001111, }; pub const M = [4]u8{ 0b10101111, 0b10001111, 0b10101111, 0b10101111, }; pub const N = [4]u8{ 0b11111111, 0b10001111, 0b10101111, 0b10101111, }; pub const O = [4]u8{ 0b10001111, 0b10101111, 0b10101111, 0b10001111, }; pub const P = [4]u8{ 0b10001111, 0b10001111, 0b10111111, 0b10111111, }; pub const Q = [4]u8{ 0b10001111, 0b10101111, 0b10001111, 0b11101111, }; pub const R = [4]u8{ 0b10001111, 0b10101111, 0b10011111, 0b10101111, }; pub const S = [4]u8{ 0b10001111, 0b10111111, 0b11101111, 0b10001111, }; pub const T = [4]u8{ 0b10001111, 0b11011111, 0b11011111, 0b11011111, }; pub const U = [4]u8{ 0b10101111, 0b10101111, 0b10101111, 0b10001111, }; pub const V = [4]u8{ 0b10101111, 0b10101111, 0b10101111, 0b11011111, }; pub const W = [4]u8{ 0b11111111, 0b10101111, 0b10101111, 0b11011111, }; pub const X = [4]u8{ 0b10101111, 0b11011111, 0b11011111, 0b10101111, }; pub const Y = [4]u8{ 0b10101111, 0b11011111, 0b11011111, 0b11011111, }; pub const Z = [4]u8{ 0b10001111, 0b11011111, 0b10111111, 0b10001111, }; pub const n0 = [4]u8{ 0b10001111, 0b10001111, 0b10101111, 0b10001111, }; pub const n1 = [4]u8{ 0b11011111, 0b10011111, 0b11011111, 0b10001111, }; pub const n2 = [4]u8{ 0b10001111, 0b11101111, 0b10011111, 0b10001111, }; pub const n3 = [4]u8{ 0b10001111, 0b11001111, 0b11101111, 0b10001111, }; pub const n4 = [4]u8{ 0b10101111, 0b10001111, 0b11101111, 0b11101111, }; pub const n5 = [4]u8{ 0b10001111, 0b10011111, 0b11101111, 0b10001111, }; pub const n6 = [4]u8{ 0b10001111, 0b10111111, 0b10001111, 0b10001111, }; pub const n7 = [4]u8{ 0b10001111, 0b11101111, 0b11101111, 0b11101111, }; pub const n8 = [4]u8{ 0b10001111, 0b10101111, 0b10001111, 0b10001111, }; pub const n9 = [4]u8{ 0b10001111, 0b10001111, 0b11101111, 0b10001111, };
src/alphabet.zig
const std = @import("std"); const wasmer = @import("wasmer"); const assert = std.debug.assert; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const wat = \\(module \\ (type $mem_size_t (func (result i32))) \\ (type $get_at_t (func (param i32) (result i32))) \\ (type $set_at_t (func (param i32) (param i32))) \\ (memory $mem 1) \\ (func $get_at (type $get_at_t) (param $idx i32) (result i32) \\ (i32.load (local.get $idx))) \\ (func $set_at (type $set_at_t) (param $idx i32) (param $val i32) \\ (i32.store (local.get $idx) (local.get $val))) \\ (func $mem_size (type $mem_size_t) (result i32) \\ (memory.size)) \\ (export "get_at" (func $get_at)) \\ (export "set_at" (func $set_at)) \\ (export "mem_size" (func $mem_size)) \\ (export "memory" (memory $mem))) ; pub fn main() !void { run () catch |err| { const err_msg = try wasmer.lastError(std.heap.c_allocator); defer std.heap.c_allocator.free(err_msg); std.log.err("{s}", .{err_msg}); return err; }; } pub fn run() !void { var wasm_bytes = try wasmer.watToWasm(wat); defer wasm_bytes.deinit(); std.log.info("creating the store...", .{}); const engine = try wasmer.Engine.init(); defer engine.deinit(); const store = try wasmer.Store.init(engine); defer store.deinit(); std.log.info("compiling module...", .{}); const module = try wasmer.Module.init(store, wasm_bytes.toSlice()); defer module.deinit(); std.log.info("instantiating module...", .{}); const instance = try wasmer.Instance.init(store, module, &.{}); defer instance.deinit(); std.log.info("retrieving exports...", .{}); const get_at = instance.getExportFunc(module, "get_at") orelse { std.log.err("failed to retrieve \"get_at\" export from instance", .{}); return error.ExportNotFound; }; defer get_at.deinit(); const set_at = instance.getExportFunc(module, "set_at") orelse { std.log.err("failed to retrieve \"set_at\" export from instance", .{}); return error.ExportNotFound; }; defer set_at.deinit(); const mem_size = instance.getExportFunc(module, "mem_size") orelse { std.log.err("failed to retrieve \"mem_size\" export from instance", .{}); return error.ExportNotFound; }; defer mem_size.deinit(); const memory = instance.getExportMem(module, "memory") orelse { std.log.err("failed to retrieve \"memory\" export from instance", .{}); return error.ExportNotFound; }; defer memory.deinit(); memory.grow(2) catch |err| { std.log.err("Error growing memory!", .{}); return err; }; const new_pages = memory.pages(); const new_size = memory.size(); std.log.info("New memory size (byted)/(pages): {d}/{d}", .{new_size, new_pages}); const mem_addr: i32 = 0x2220; const val: i32 = 0xFEFEFFE; set_at.call(void, .{ mem_addr, val }) catch |err| { std.log.err("Failed to call \"set_at\": {s}", .{err}); return err; }; const result = get_at.call(i32, .{mem_addr}) catch |err| { std.log.err("Failed to call \"get_at\": {s}", .{err}); return err; }; std.log.info("Vale at 0x{x:0>4}: {d}", .{ mem_addr, result }); }
examples/memory.zig
const std = @import("std"); const artc = @cImport({ @cInclude("art.h"); }); const clibart = @cImport({ @cInclude("src/clibart.c"); }); extern var show_debug: c_int; const art = @import("art.zig"); const Art = art.Art; const testing = std.testing; const a = std.heap.c_allocator; const Lang = enum { c, z, both }; const lang = switch (clibart.LANG) { 'c' => .c, 'z' => .z, 'b' => .both, else => unreachable, }; const UTree = Art(usize); test "compare node keys" { var t: artc.art_tree = undefined; _ = artc.art_tree_init(&t); defer _ = artc.art_tree_destroy(&t); var ta = Art(usize).init(a); defer ta.deinit(); const f = try std.fs.cwd().openFile("./testdata/words.txt", .{ .mode = .read_only }); defer f.close(); var linei: usize = 1; const stream = &f.inStream(); var buf: [512:0]u8 = undefined; const stop_line = 200; var i: usize = 0; while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { defer i += 1; // if (i > stop_line) break; buf[line.len] = 0; if (lang == .c or lang == .both) { // this prevents all inserted values from pointing to the same value // TODO fix leak const temp = try a.create(usize); temp.* = linei; const result = artc.art_insert(&t, line.ptr, @intCast(c_int, line.len), temp); } else if (lang == .z or lang == .both) { const result = try ta.insert(buf[0..line.len :0], linei); } linei += 1; } if (lang == .c or lang == .both) { show_debug = 1; artc.art_print(&t); } if (lang == .z or lang == .both) { try ta.print(); } } // this is used to compare against output from the original c version of libart test "compare tree after delete" { var t: artc.art_tree = undefined; _ = artc.art_tree_init(&t); defer _ = artc.art_tree_destroy(&t); var ta = Art(usize).init(a); defer ta.deinit(); const f = try std.fs.cwd().openFile("./testdata/words.txt", .{ .mode = .read_only }); defer f.close(); var linei: usize = 1; const stream = &f.inStream(); var buf: [512:0]u8 = undefined; const stop_line = 197141; while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { buf[line.len] = 0; if (lang == .c or lang == .both) { // this prevents all inserted values from pointing to the same value // TODO fix leak const temp = try a.create(usize); temp.* = linei; const result = artc.art_insert(&t, line.ptr, @intCast(c_int, line.len), temp); } else if (lang == .z or lang == .both) { const result = try ta.insert(buf[0..line.len :0], linei); } // if (linei == stop_line) break; linei += 1; } _ = try f.seekTo(0); linei = 1; while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { buf[line.len] = 0; if (linei == stop_line) { if (lang == .c or lang == .both) { show_debug = 1; artc.art_print(&t); show_debug = 0; } if (lang == .z or lang == .both) { // var list = std.ArrayList(u8).init(a); // try ta.printToStream(&std.io.getStdOut().outStream()); // try ta.printToStream(&list.outStream()); try ta.print(); } } if (lang == .c or lang == .both) { const result = artc.art_delete(&t, line.ptr, @intCast(c_int, line.len)); testing.expect(result != null); } else if (lang == .z or lang == .both) { const result = try ta.delete(buf[0..line.len :0]); if (result != .found) { std.debug.warn("\nfailed on line {}:{}\n", .{ linei, line }); } testing.expect(result == .found); } if (linei == stop_line) break; linei += 1; } if (lang == .c or lang == .both) { show_debug = 1; artc.art_print(&t); show_debug = 0; } if (lang == .z or lang == .both) { // var list = std.ArrayList(u8).init(a); // try ta.printToStream(&std.io.getStdOut().outStream()); // try ta.printToStream(&list.outStream()); } } // zig test src/clibart.zig --c-source libartc/src/art.c -I/usr/include/ -I/usr/include/x86_64-linux-gnu/ -lc -I libartc/src -I. -DLANG="'c'" --test-filter bench --release-fast test "bench against libart" { var t: artc.art_tree = undefined; _ = artc.art_tree_init(&t); defer _ = artc.art_tree_destroy(&t); var ta = Art(usize).init(a); defer ta.deinit(); const filename = "./testdata/words.txt"; const f = try std.fs.cwd().openFile(filename, .{ .mode = .read_only }); defer f.close(); var linei: usize = 1; const stream = &f.inStream(); var buf: [512:0]u8 = undefined; var timer = try std.time.Timer.start(); while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { buf[line.len] = 0; if (lang == .z or lang == .both) _ = try ta.insert(buf[0..line.len :0], linei); if (lang == .c or lang == .both) { var tmp: usize = 0; const result = artc.art_insert(&t, line.ptr, @intCast(c_int, line.len), &tmp); testing.expect(result == null); } } const t1 = timer.read(); timer.reset(); try f.seekTo(0); while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { buf[line.len] = 0; if (lang == .z or lang == .both) _ = ta.search(buf[0..line.len :0]); if (lang == .c or lang == .both) { _ = artc.art_search(&t, line.ptr, @intCast(c_int, line.len)); } } const t2 = timer.read(); timer.reset(); try f.seekTo(0); while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { buf[line.len] = 0; if (lang == .z or lang == .both) _ = try ta.delete(buf[0..line.len :0]); if (lang == .c or lang == .both) { _ = artc.art_delete(&t, line.ptr, @intCast(c_int, line.len)); } } const t3 = timer.read(); std.debug.warn("{: <7} insert {}ms, search {}ms, delete {}ms, combined {}ms\n", .{ if (lang == .z) "art.zig" else "art.c", t1 / 1000000, t2 / 1000000, t3 / 1000000, (t1 + t2 + t3) / 1000000, }); }
src/clibart.zig
const std = @import("std"); const assert = std.debug.assert; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var input_file = try std.fs.cwd().openFile("input/10.txt", .{}); defer input_file.close(); var buffered_reader = std.io.bufferedReader(input_file.reader()); const total_score = try calculateMiddleScore(allocator, buffered_reader.reader()); std.debug.print("middle score: {}\n", .{total_score}); } fn calculateMiddleScore(gpa: std.mem.Allocator, reader: anytype) !u64 { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const allocator = arena.allocator(); var buf: [4096]u8 = undefined; var scores = std.ArrayList(u64).init(allocator); lines: while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { var parenthesis_stack = std.ArrayList(u8).init(allocator); for (line) |c| { switch (c) { '(', '[', '{', '<' => try parenthesis_stack.append(c), ')' => { if (parenthesis_stack.pop() != '(') continue :lines; }, ']' => { if (parenthesis_stack.pop() != '[') continue :lines; }, '}' => { if (parenthesis_stack.pop() != '{') continue :lines; }, '>' => { if (parenthesis_stack.pop() != '<') continue :lines; }, else => return error.InvalidSymbol, } } var score: u64 = 0; var i: usize = parenthesis_stack.items.len; while (i > 0) : (i -= 1) { const points: u64 = switch (parenthesis_stack.items[i - 1]) { '(' => 1, '[' => 2, '{' => 3, '<' => 4, else => unreachable, }; score = score * 5 + points; } try scores.append(score); } std.sort.sort(u64, scores.items, {}, comptime std.sort.asc(u64)); return scores.items[scores.items.len / 2]; } test "example 1" { const text = \\[({(<(())[]>[[{[]{<()<>> \\[(()[<>])]({[<{<<[]>>( \\{([(<{}[<>[]}>{[]{[(<()> \\(((({<>}<{<{<>}{[]{[]{} \\[[<[([]))<([[{}[[()]]] \\[{[{({}]{}}([{[{{{}}([] \\{<[[]]>}<{[{[{[]{()[[[] \\[<(<(<(<{}))><([]([]() \\<{([([[(<>()){}]>(<<{{ \\<{([{{}}[<[[[<>{}]]]>[]] ; var fbs = std.io.fixedBufferStream(text); const total_score = try calculateMiddleScore(std.testing.allocator, fbs.reader()); try std.testing.expectEqual(@as(u64, 288957), total_score); }
src/10_2.zig