code
stringlengths
38
801k
repo_path
stringlengths
6
263
//-------------------------------------------------------------------------------- // Section: Types (233) //-------------------------------------------------------------------------------- // TODO: this type has a FreeFunc 'EngDeleteSemaphore', what can Zig do with this information? pub const HSEMAPHORE = *opaque{}; pub const FD_XFORM = extern struct { eXX: f32, eXY: f32, eYX: f32, eYY: f32, }; pub const FD_DEVICEMETRICS = extern struct { flRealizedType: u32, pteBase: POINTE, pteSide: POINTE, lD: i32, fxMaxAscender: i32, fxMaxDescender: i32, ptlUnderline1: POINTL, ptlStrikeOut: POINTL, ptlULThickness: POINTL, ptlSOThickness: POINTL, cxMax: u32, cyMax: u32, cjGlyphMax: u32, fdxQuantized: FD_XFORM, lNonLinearExtLeading: i32, lNonLinearIntLeading: i32, lNonLinearMaxCharWidth: i32, lNonLinearAvgCharWidth: i32, lMinA: i32, lMinC: i32, lMinD: i32, alReserved: [1]i32, }; pub const WCRUN = extern struct { wcLow: u16, cGlyphs: u16, phg: ?*u32, }; pub const FD_GLYPHSET = extern struct { cjThis: u32, flAccel: u32, cGlyphsSupported: u32, cRuns: u32, awcrun: [1]WCRUN, }; pub const FD_GLYPHATTR = extern struct { cjThis: u32, cGlyphs: u32, iMode: u32, aGlyphAttr: [1]u8, }; pub const FD_KERNINGPAIR = extern struct { wcFirst: u16, wcSecond: u16, fwdKern: i16, }; pub const FONTDIFF = extern struct { jReserved1: u8, jReserved2: u8, jReserved3: u8, bWeight: u8, usWinWeight: u16, fsSelection: u16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, ptlCaret: POINTL, }; pub const FONTSIM = extern struct { dpBold: i32, dpItalic: i32, dpBoldItalic: i32, }; pub const IFIEXTRA = extern struct { ulIdentifier: u32, dpFontSig: i32, cig: u32, dpDesignVector: i32, dpAxesInfoW: i32, aulReserved: [1]u32, }; pub const DRVFN = extern struct { iFunc: u32, pfn: ?PFN, }; pub const DRVENABLEDATA = extern struct { iDriverVersion: u32, c: u32, pdrvfn: ?*DRVFN, }; pub const DEVINFO = extern struct { flGraphicsCaps: u32, lfDefaultFont: LOGFONTW, lfAnsiVarFont: LOGFONTW, lfAnsiFixFont: LOGFONTW, cFonts: u32, iDitherFormat: u32, cxDither: u16, cyDither: u16, hpalDefault: ?HPALETTE, flGraphicsCaps2: u32, }; pub const LINEATTRS = extern struct { fl: u32, iJoin: u32, iEndCap: u32, elWidth: FLOAT_LONG, eMiterLimit: f32, cstyle: u32, pstyle: ?*FLOAT_LONG, elStyleState: FLOAT_LONG, }; pub const XFORML = extern struct { eM11: f32, eM12: f32, eM21: f32, eM22: f32, eDx: f32, eDy: f32, }; pub const CIECHROMA = extern struct { x: i32, y: i32, Y: i32, }; pub const COLORINFO = extern struct { Red: CIECHROMA, Green: CIECHROMA, Blue: CIECHROMA, Cyan: CIECHROMA, Magenta: CIECHROMA, Yellow: CIECHROMA, AlignmentWhite: CIECHROMA, RedGamma: i32, GreenGamma: i32, BlueGamma: i32, MagentaInCyanDye: i32, YellowInCyanDye: i32, CyanInMagentaDye: i32, YellowInMagentaDye: i32, CyanInYellowDye: i32, MagentaInYellowDye: i32, }; pub const GDIINFO = extern struct { ulVersion: u32, ulTechnology: u32, ulHorzSize: u32, ulVertSize: u32, ulHorzRes: u32, ulVertRes: u32, cBitsPixel: u32, cPlanes: u32, ulNumColors: u32, flRaster: u32, ulLogPixelsX: u32, ulLogPixelsY: u32, flTextCaps: u32, ulDACRed: u32, ulDACGreen: u32, ulDACBlue: u32, ulAspectX: u32, ulAspectY: u32, ulAspectXY: u32, xStyleStep: i32, yStyleStep: i32, denStyleStep: i32, ptlPhysOffset: POINTL, szlPhysSize: SIZE, ulNumPalReg: u32, ciDevice: COLORINFO, ulDevicePelsDPI: u32, ulPrimaryOrder: u32, ulHTPatternSize: u32, ulHTOutputFormat: u32, flHTFlags: u32, ulVRefresh: u32, ulBltAlignment: u32, ulPanningHorzRes: u32, ulPanningVertRes: u32, xPanningAlignment: u32, yPanningAlignment: u32, cxHTPat: u32, cyHTPat: u32, pHTPatA: ?*u8, pHTPatB: ?*u8, pHTPatC: ?*u8, flShadeBlend: u32, ulPhysicalPixelCharacteristics: u32, ulPhysicalPixelGamma: u32, }; pub const BRUSHOBJ = extern struct { iSolidColor: u32, pvRbrush: ?*c_void, flColorType: u32, }; pub const CLIPOBJ = extern struct { iUniq: u32, rclBounds: RECTL, iDComplexity: u8, iFComplexity: u8, iMode: u8, fjOptions: u8, }; pub const DRIVEROBJ = extern struct { pvObj: ?*c_void, pFreeProc: ?FREEOBJPROC, hdev: ?HDEV, dhpdev: DHPDEV, }; pub const FONTOBJ = extern struct { iUniq: u32, iFace: u32, cxMax: u32, flFontType: u32, iTTUniq: usize, iFile: usize, sizLogResPpi: SIZE, ulStyleSize: u32, pvConsumer: ?*c_void, pvProducer: ?*c_void, }; pub const BLENDOBJ = extern struct { BlendFunction: BLENDFUNCTION, }; pub const PALOBJ = extern struct { ulReserved: u32, }; pub const PATHOBJ = extern struct { fl: u32, cCurves: u32, }; pub const SURFOBJ = extern struct { dhsurf: DHSURF, hsurf: ?HSURF, dhpdev: DHPDEV, hdev: ?HDEV, sizlBitmap: SIZE, cjBits: u32, pvBits: ?*c_void, pvScan0: ?*c_void, lDelta: i32, iUniq: u32, iBitmapFormat: u32, iType: u16, fjBitmap: u16, }; pub const WNDOBJ = extern struct { coClient: CLIPOBJ, pvConsumer: ?*c_void, rclClient: RECTL, psoOwner: ?*SURFOBJ, }; pub const XLATEOBJ = extern struct { iUniq: u32, flXlate: u32, iSrcType: u16, iDstType: u16, cEntries: u32, pulXlate: ?*u32, }; pub const ENUMRECTS = extern struct { c: u32, arcl: [1]RECTL, }; pub const GLYPHBITS = extern struct { ptlOrigin: POINTL, sizlBitmap: SIZE, aj: [1]u8, }; pub const GLYPHDEF = extern union { pgb: ?*GLYPHBITS, ppo: ?*PATHOBJ, }; pub const GLYPHPOS = extern struct { hg: u32, pgdf: ?*GLYPHDEF, ptl: POINTL, }; pub const GLYPHDATA = extern struct { gdf: GLYPHDEF, hg: u32, fxD: i32, fxA: i32, fxAB: i32, fxInkTop: i32, fxInkBottom: i32, rclInk: RECTL, ptqD: POINTQF, }; pub const STROBJ = extern struct { cGlyphs: u32, flAccel: u32, ulCharInc: u32, rclBkGround: RECTL, pgp: ?*GLYPHPOS, pwszOrg: ?PWSTR, }; pub const FONTINFO = extern struct { cjThis: u32, flCaps: u32, cGlyphsSupported: u32, cjMaxGlyph1: u32, cjMaxGlyph4: u32, cjMaxGlyph8: u32, cjMaxGlyph32: u32, }; pub const PATHDATA = extern struct { flags: u32, count: u32, pptfx: ?*POINTFIX, }; pub const RUN = extern struct { iStart: i32, iStop: i32, }; pub const CLIPLINE = extern struct { ptfxA: POINTFIX, ptfxB: POINTFIX, lStyleState: i32, c: u32, arun: [1]RUN, }; pub const PERBANDINFO = extern struct { bRepeatThisBand: BOOL, szlBand: SIZE, ulHorzRes: u32, ulVertRes: u32, }; pub const GAMMARAMP = extern struct { Red: [256]u16, Green: [256]u16, Blue: [256]u16, }; pub const DEVHTINFO = extern struct { HTFlags: u32, HTPatternSize: u32, DevPelsDPI: u32, ColorInfo: COLORINFO, }; pub const DEVHTADJDATA = extern struct { DeviceFlags: u32, DeviceXDPI: u32, DeviceYDPI: u32, pDefHTInfo: ?*DEVHTINFO, pAdjHTInfo: ?*DEVHTINFO, }; pub const TYPE1_FONT = extern struct { hPFM: ?HANDLE, hPFB: ?HANDLE, ulIdentifier: u32, }; pub const ENGSAFESEMAPHORE = extern struct { hsem: ?*HSEMAPHORE__, lCount: i32, }; pub const ENG_TIME_FIELDS = extern struct { usYear: u16, usMonth: u16, usDay: u16, usHour: u16, usMinute: u16, usSecond: u16, usMilliseconds: u16, usWeekday: u16, }; pub const PFN_DrvQueryGlyphAttrs = fn( param0: ?*FONTOBJ, param1: u32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHATTR; pub const DDVIDEOPORTCAPS = extern struct { dwSize: u32, dwFlags: u32, dwMaxWidth: u32, dwMaxVBIWidth: u32, dwMaxHeight: u32, dwVideoPortID: u32, dwCaps: u32, dwFX: u32, dwNumAutoFlipSurfaces: u32, dwAlignVideoPortBoundary: u32, dwAlignVideoPortPrescaleWidth: u32, dwAlignVideoPortCropBoundary: u32, dwAlignVideoPortCropWidth: u32, dwPreshrinkXStep: u32, dwPreshrinkYStep: u32, dwNumVBIAutoFlipSurfaces: u32, dwNumPreferredAutoflip: u32, wNumFilterTapsX: u16, wNumFilterTapsY: u16, }; pub const DDVIDEOPORTDESC = extern struct { dwSize: u32, dwFieldWidth: u32, dwVBIWidth: u32, dwFieldHeight: u32, dwMicrosecondsPerField: u32, dwMaxPixelsPerSecond: u32, dwVideoPortID: u32, dwReserved1: u32, VideoPortType: DDVIDEOPORTCONNECT, dwReserved2: usize, dwReserved3: usize, }; pub const DDVIDEOPORTINFO = extern struct { dwSize: u32, dwOriginX: u32, dwOriginY: u32, dwVPFlags: u32, rCrop: RECT, dwPrescaleWidth: u32, dwPrescaleHeight: u32, lpddpfInputFormat: ?*DDPIXELFORMAT, lpddpfVBIInputFormat: ?*DDPIXELFORMAT, lpddpfVBIOutputFormat: ?*DDPIXELFORMAT, dwVBIHeight: u32, dwReserved1: usize, dwReserved2: usize, }; pub const DDVIDEOPORTBANDWIDTH = extern struct { dwSize: u32, dwCaps: u32, dwOverlay: u32, dwColorkey: u32, dwYInterpolate: u32, dwYInterpAndColorkey: u32, dwReserved1: usize, dwReserved2: usize, }; pub const DDCORECAPS = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, }; pub const DDHAL_WAITFORVERTICALBLANKDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwFlags: u32, bIsInVB: u32, hEvent: usize, ddRVal: HRESULT, WaitForVerticalBlank: ?LPDDHAL_WAITFORVERTICALBLANK, }; pub const DDHAL_DESTROYDDLOCALDATA = extern struct { dwFlags: u32, pDDLcl: ?*DDRAWI_DIRECTDRAW_LCL, ddRVal: HRESULT, }; pub const VIDEOMEMORY = extern struct { dwFlags: u32, fpStart: usize, Anonymous1: extern union { fpEnd: usize, dwWidth: u32, }, ddsCaps: DDSCAPS, ddsCapsAlt: DDSCAPS, Anonymous2: extern union { lpHeap: ?*VMEMHEAP, dwHeight: u32, }, }; pub const VIDEOMEMORYINFO = extern struct { fpPrimary: usize, dwFlags: u32, dwDisplayWidth: u32, dwDisplayHeight: u32, lDisplayPitch: i32, ddpfDisplay: DDPIXELFORMAT, dwOffscreenAlign: u32, dwOverlayAlign: u32, dwTextureAlign: u32, dwZBufferAlign: u32, dwAlphaAlign: u32, pvPrimary: ?*c_void, }; pub const PDD_CANCREATESURFACE = fn( param0: ?*DD_CANCREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_WAITFORVERTICALBLANK = fn( param0: ?*DD_WAITFORVERTICALBLANKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CREATESURFACE = fn( param0: ?*DD_CREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CREATEPALETTE = fn( param0: ?*DD_CREATEPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETSCANLINE = fn( param0: ?*DD_GETSCANLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MAPMEMORY = fn( param0: ?*DD_MAPMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETDRIVERINFO = fn( param0: ?*DD_GETDRIVERINFODATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_CALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyDriver: ?PDD_DESTROYDRIVER, CreateSurface: ?PDD_CREATESURFACE, SetColorKey: ?PDD_SETCOLORKEY, SetMode: ?PDD_SETMODE, WaitForVerticalBlank: ?PDD_WAITFORVERTICALBLANK, CanCreateSurface: ?PDD_CANCREATESURFACE, CreatePalette: ?PDD_CREATEPALETTE, GetScanLine: ?PDD_GETSCANLINE, MapMemory: ?PDD_MAPMEMORY, }; pub const PDD_GETAVAILDRIVERMEMORY = fn( param0: ?*DD_GETAVAILDRIVERMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MISCELLANEOUSCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetAvailDriverMemory: ?PDD_GETAVAILDRIVERMEMORY, }; pub const PDD_CREATESURFACEEX = fn( param0: ?*DD_CREATESURFACEEXDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETDRIVERSTATE = fn( param0: ?*DD_GETDRIVERSTATEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_DESTROYDDLOCAL = fn( param0: ?*DD_DESTROYDDLOCALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MISCELLANEOUS2CALLBACKS = extern struct { dwSize: u32, dwFlags: u32, AlphaBlt: ?PDD_ALPHABLT, CreateSurfaceEx: ?PDD_CREATESURFACEEX, GetDriverState: ?PDD_GETDRIVERSTATE, DestroyDDLocal: ?PDD_DESTROYDDLOCAL, }; pub const PDD_FREEDRIVERMEMORY = fn( param0: ?*DD_FREEDRIVERMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SETEXCLUSIVEMODE = fn( param0: ?*DD_SETEXCLUSIVEMODEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_FLIPTOGDISURFACE = fn( param0: ?*DD_FLIPTOGDISURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_NTCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, FreeDriverMemory: ?PDD_FREEDRIVERMEMORY, SetExclusiveMode: ?PDD_SETEXCLUSIVEMODE, FlipToGDISurface: ?PDD_FLIPTOGDISURFACE, }; pub const PDD_PALCB_DESTROYPALETTE = fn( param0: ?*DD_DESTROYPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_PALCB_SETENTRIES = fn( param0: ?*DD_SETENTRIESDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_PALETTECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyPalette: ?PDD_PALCB_DESTROYPALETTE, SetEntries: ?PDD_PALCB_SETENTRIES, }; pub const PDD_SURFCB_LOCK = fn( param0: ?*DD_LOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_UNLOCK = fn( param0: ?*DD_UNLOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_BLT = fn( param0: ?*DD_BLTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_UPDATEOVERLAY = fn( param0: ?*DD_UPDATEOVERLAYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETOVERLAYPOSITION = fn( param0: ?*DD_SETOVERLAYPOSITIONDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETPALETTE = fn( param0: ?*DD_SETPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_FLIP = fn( param0: ?*DD_FLIPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_DESTROYSURFACE = fn( param0: ?*DD_DESTROYSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_ADDATTACHEDSURFACE = fn( param0: ?*DD_ADDATTACHEDSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETCOLORKEY = fn( param0: ?*DD_SETCOLORKEYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_GETBLTSTATUS = fn( param0: ?*DD_GETBLTSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_GETFLIPSTATUS = fn( param0: ?*DD_GETFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_SURFACECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroySurface: ?PDD_SURFCB_DESTROYSURFACE, Flip: ?PDD_SURFCB_FLIP, SetClipList: ?PDD_SURFCB_SETCLIPLIST, Lock: ?PDD_SURFCB_LOCK, Unlock: ?PDD_SURFCB_UNLOCK, Blt: ?PDD_SURFCB_BLT, SetColorKey: ?PDD_SURFCB_SETCOLORKEY, AddAttachedSurface: ?PDD_SURFCB_ADDATTACHEDSURFACE, GetBltStatus: ?PDD_SURFCB_GETBLTSTATUS, GetFlipStatus: ?PDD_SURFCB_GETFLIPSTATUS, UpdateOverlay: ?PDD_SURFCB_UPDATEOVERLAY, SetOverlayPosition: ?PDD_SURFCB_SETOVERLAYPOSITION, reserved4: ?*c_void, SetPalette: ?PDD_SURFCB_SETPALETTE, }; pub const PDD_VPORTCB_CANCREATEVIDEOPORT = fn( param0: ?*DD_CANCREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_CREATEVIDEOPORT = fn( param0: ?*DD_CREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_FLIP = fn( param0: ?*DD_FLIPVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETBANDWIDTH = fn( param0: ?*DD_GETVPORTBANDWIDTHDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETINPUTFORMATS = fn( param0: ?*DD_GETVPORTINPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETOUTPUTFORMATS = fn( param0: ?*DD_GETVPORTOUTPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETFIELD = fn( param0: ?*DD_GETVPORTFIELDDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETLINE = fn( param0: ?*DD_GETVPORTLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETVPORTCONNECT = fn( param0: ?*DD_GETVPORTCONNECTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_DESTROYVPORT = fn( param0: ?*DD_DESTROYVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETFLIPSTATUS = fn( param0: ?*DD_GETVPORTFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_UPDATE = fn( param0: ?*DD_UPDATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_WAITFORSYNC = fn( param0: ?*DD_WAITFORVPORTSYNCDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETSIGNALSTATUS = fn( param0: ?*DD_GETVPORTSIGNALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_COLORCONTROL = fn( param0: ?*DD_VPORTCOLORDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_VIDEOPORTCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateVideoPort: ?PDD_VPORTCB_CANCREATEVIDEOPORT, CreateVideoPort: ?PDD_VPORTCB_CREATEVIDEOPORT, FlipVideoPort: ?PDD_VPORTCB_FLIP, GetVideoPortBandwidth: ?PDD_VPORTCB_GETBANDWIDTH, GetVideoPortInputFormats: ?PDD_VPORTCB_GETINPUTFORMATS, GetVideoPortOutputFormats: ?PDD_VPORTCB_GETOUTPUTFORMATS, lpReserved1: ?*c_void, GetVideoPortField: ?PDD_VPORTCB_GETFIELD, GetVideoPortLine: ?PDD_VPORTCB_GETLINE, GetVideoPortConnectInfo: ?PDD_VPORTCB_GETVPORTCONNECT, DestroyVideoPort: ?PDD_VPORTCB_DESTROYVPORT, GetVideoPortFlipStatus: ?PDD_VPORTCB_GETFLIPSTATUS, UpdateVideoPort: ?PDD_VPORTCB_UPDATE, WaitForVideoPortSync: ?PDD_VPORTCB_WAITFORSYNC, GetVideoSignalStatus: ?PDD_VPORTCB_GETSIGNALSTATUS, ColorControl: ?PDD_VPORTCB_COLORCONTROL, }; pub const PDD_COLORCB_COLORCONTROL = fn( param0: ?*DD_COLORCONTROLDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_COLORCONTROLCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, ColorControl: ?PDD_COLORCB_COLORCONTROL, }; pub const PDD_KERNELCB_SYNCSURFACE = fn( param0: ?*DD_SYNCSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_KERNELCB_SYNCVIDEOPORT = fn( param0: ?*DD_SYNCVIDEOPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_KERNELCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, SyncSurfaceData: ?PDD_KERNELCB_SYNCSURFACE, SyncVideoPortData: ?PDD_KERNELCB_SYNCVIDEOPORT, }; pub const PDD_MOCOMPCB_GETGUIDS = fn( param0: ?*DD_GETMOCOMPGUIDSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETFORMATS = fn( param0: ?*DD_GETMOCOMPFORMATSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_CREATE = fn( param0: ?*DD_CREATEMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETCOMPBUFFINFO = fn( param0: ?*DD_GETMOCOMPCOMPBUFFDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETINTERNALINFO = fn( param0: ?*DD_GETINTERNALMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_BEGINFRAME = fn( param0: ?*DD_BEGINMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_ENDFRAME = fn( param0: ?*DD_ENDMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_RENDER = fn( param0: ?*DD_RENDERMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_QUERYSTATUS = fn( param0: ?*DD_QUERYMOCOMPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_DESTROY = fn( param0: ?*DD_DESTROYMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MOTIONCOMPCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetMoCompGuids: ?PDD_MOCOMPCB_GETGUIDS, GetMoCompFormats: ?PDD_MOCOMPCB_GETFORMATS, CreateMoComp: ?PDD_MOCOMPCB_CREATE, GetMoCompBuffInfo: ?PDD_MOCOMPCB_GETCOMPBUFFINFO, GetInternalMoCompInfo: ?PDD_MOCOMPCB_GETINTERNALINFO, BeginMoCompFrame: ?PDD_MOCOMPCB_BEGINFRAME, EndMoCompFrame: ?PDD_MOCOMPCB_ENDFRAME, RenderMoComp: ?PDD_MOCOMPCB_RENDER, QueryMoCompStatus: ?PDD_MOCOMPCB_QUERYSTATUS, DestroyMoComp: ?PDD_MOCOMPCB_DESTROY, }; pub const DD_NONLOCALVIDMEMCAPS = extern struct { dwSize: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, }; pub const DD_PALETTE_GLOBAL = extern struct { dwReserved1: usize, }; pub const DD_PALETTE_LOCAL = extern struct { dwReserved0: u32, dwReserved1: usize, }; pub const DD_CLIPPER_GLOBAL = extern struct { dwReserved1: usize, }; pub const DD_CLIPPER_LOCAL = extern struct { dwReserved1: usize, }; pub const DD_ATTACHLIST = extern struct { lpLink: ?*DD_ATTACHLIST, lpAttached: ?*DD_SURFACE_LOCAL, }; pub const DD_SURFACE_INT = extern struct { lpLcl: ?*DD_SURFACE_LOCAL, }; pub const DD_SURFACE_GLOBAL = extern struct { Anonymous1: extern union { dwBlockSizeY: u32, lSlicePitch: i32, }, Anonymous2: extern union { lpVidMemHeap: ?*VIDEOMEMORY, dwBlockSizeX: u32, dwUserMemSize: u32, }, fpVidMem: usize, Anonymous3: extern union { lPitch: i32, dwLinearSize: u32, }, yHint: i32, xHint: i32, wHeight: u32, wWidth: u32, dwReserved1: usize, ddpfSurface: DDPIXELFORMAT, fpHeapOffset: usize, hCreatorProcess: ?HANDLE, }; pub const DD_SURFACE_MORE = extern struct { dwMipMapCount: u32, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwOverlayFlags: u32, ddsCapsEx: DDSCAPSEX, dwSurfaceHandle: u32, }; pub const DD_SURFACE_LOCAL = extern struct { lpGbl: ?*DD_SURFACE_GLOBAL, dwFlags: u32, ddsCaps: DDSCAPS, dwReserved1: usize, Anonymous1: extern union { ddckCKSrcOverlay: DDCOLORKEY, ddckCKSrcBlt: DDCOLORKEY, }, Anonymous2: extern union { ddckCKDestOverlay: DDCOLORKEY, ddckCKDestBlt: DDCOLORKEY, }, lpSurfMore: ?*DD_SURFACE_MORE, lpAttachList: ?*DD_ATTACHLIST, lpAttachListFrom: ?*DD_ATTACHLIST, rcOverlaySrc: RECT, }; pub const DD_D3DBUFCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateD3DBuffer: ?PDD_CANCREATESURFACE, CreateD3DBuffer: ?PDD_CREATESURFACE, DestroyD3DBuffer: ?PDD_SURFCB_DESTROYSURFACE, LockD3DBuffer: ?PDD_SURFCB_LOCK, UnlockD3DBuffer: ?PDD_SURFCB_UNLOCK, }; pub const DD_HALINFO = extern struct { dwSize: u32, vmiData: VIDEOMEMORYINFO, ddCaps: DDNTCORECAPS, GetDriverInfo: ?PDD_GETDRIVERINFO, dwFlags: u32, lpD3DGlobalDriverData: ?*c_void, lpD3DHALCallbacks: ?*c_void, lpD3DBufCallbacks: ?*DD_D3DBUFCALLBACKS, }; pub const DD_DIRECTDRAW_GLOBAL = extern struct { dhpdev: ?*c_void, dwReserved1: usize, dwReserved2: usize, lpDDVideoPortCaps: ?*DDVIDEOPORTCAPS, }; pub const DD_DIRECTDRAW_LOCAL = extern struct { lpGbl: ?*DD_DIRECTDRAW_GLOBAL, }; pub const DD_VIDEOPORT_LOCAL = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, ddvpDesc: DDVIDEOPORTDESC, ddvpInfo: DDVIDEOPORTINFO, lpSurface: ?*DD_SURFACE_INT, lpVBISurface: ?*DD_SURFACE_INT, dwNumAutoflip: u32, dwNumVBIAutoflip: u32, dwReserved1: usize, dwReserved2: usize, dwReserved3: usize, }; pub const DD_MOTIONCOMP_LOCAL = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, guid: Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, lpDriverReserved1: ?*c_void, lpDriverReserved2: ?*c_void, lpDriverReserved3: ?*c_void, }; pub const DD_MORESURFACECAPS = extern struct { pub const NTExtendedHeapRestrictions = extern struct { ddsCapsEx: DDSCAPSEX, ddsCapsExAlt: DDSCAPSEX, }; dwSize: u32, ddsCapsMore: DDSCAPSEX, ddsExtendedHeapRestrictions: [1]NTExtendedHeapRestrictions, }; pub const DD_STEREOMODE = extern struct { dwSize: u32, dwHeight: u32, dwWidth: u32, dwBpp: u32, dwRefreshRate: u32, bSupported: BOOL, }; pub const DD_UPDATENONLOCALHEAPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwHeap: u32, fpGARTLin: usize, fpGARTDev: usize, ulPolicyMaxBytes: usize, ddRVal: HRESULT, UpdateNonLocalHeap: ?*c_void, }; pub const DD_NTPRIVATEDRIVERCAPS = extern struct { dwSize: u32, dwPrivateCaps: u32, }; pub const DD_BLTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, rDest: RECTL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, rSrc: RECTL, dwFlags: u32, dwROPFlags: u32, bltFX: DDBLTFX, ddRVal: HRESULT, Blt: ?*c_void, IsClipped: BOOL, rOrigDest: RECTL, rOrigSrc: RECTL, dwRectCnt: u32, prDestRects: ?*RECT, dwAFlags: u32, ddargbScaleFactors: DDARGB, }; pub const DD_LOCKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, bHasRect: u32, rArea: RECTL, lpSurfData: ?*c_void, ddRVal: HRESULT, Lock: ?*c_void, dwFlags: u32, fpProcess: usize, }; pub const DD_UNLOCKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, Unlock: ?*c_void, }; pub const DD_UPDATEOVERLAYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, rDest: RECTL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, rSrc: RECTL, dwFlags: u32, overlayFX: DDOVERLAYFX, ddRVal: HRESULT, UpdateOverlay: ?*c_void, }; pub const DD_SETOVERLAYPOSITIONDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, lXPos: i32, lYPos: i32, ddRVal: HRESULT, SetOverlayPosition: ?*c_void, }; pub const DD_SETPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, ddRVal: HRESULT, SetPalette: ?*c_void, Attach: BOOL, }; pub const DD_FLIPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpSurfCurr: ?*DD_SURFACE_LOCAL, lpSurfTarg: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, Flip: ?*c_void, lpSurfCurrLeft: ?*DD_SURFACE_LOCAL, lpSurfTargLeft: ?*DD_SURFACE_LOCAL, }; pub const DD_DESTROYSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, DestroySurface: ?*c_void, }; pub const DD_ADDATTACHEDSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpSurfAttached: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, AddAttachedSurface: ?*c_void, }; pub const DD_SETCOLORKEYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ckNew: DDCOLORKEY, ddRVal: HRESULT, SetColorKey: ?*c_void, }; pub const DD_GETBLTSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, GetBltStatus: ?*c_void, }; pub const DD_GETFLIPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, GetFlipStatus: ?*c_void, }; pub const DD_DESTROYPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, ddRVal: HRESULT, DestroyPalette: ?*c_void, }; pub const DD_SETENTRIESDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, dwBase: u32, dwNumEntries: u32, lpEntries: ?*PALETTEENTRY, ddRVal: HRESULT, SetEntries: ?*c_void, }; pub const DD_CREATESURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurfaceDesc: ?*DDSURFACEDESC, lplpSList: ?*?*DD_SURFACE_LOCAL, dwSCnt: u32, ddRVal: HRESULT, CreateSurface: ?*c_void, }; pub const DD_CANCREATESURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurfaceDesc: ?*DDSURFACEDESC, bIsDifferentPixelFormat: u32, ddRVal: HRESULT, CanCreateSurface: ?*c_void, }; pub const DD_CREATEPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, lpColorTable: ?*PALETTEENTRY, ddRVal: HRESULT, CreatePalette: ?*c_void, is_excl: BOOL, }; pub const DD_WAITFORVERTICALBLANKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwFlags: u32, bIsInVB: u32, hEvent: usize, ddRVal: HRESULT, WaitForVerticalBlank: ?*c_void, }; pub const DD_GETSCANLINEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwScanLine: u32, ddRVal: HRESULT, GetScanLine: ?*c_void, }; pub const DD_MAPMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, bMap: BOOL, hProcess: ?HANDLE, fpProcess: usize, ddRVal: HRESULT, }; pub const DD_CANCREATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, ddRVal: HRESULT, CanCreateVideoPort: ?*c_void, }; pub const DD_CREATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, ddRVal: HRESULT, CreateVideoPort: ?*c_void, }; pub const DD_FLIPVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lpSurfCurr: ?*DD_SURFACE_LOCAL, lpSurfTarg: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, FlipVideoPort: ?*c_void, }; pub const DD_GETVPORTBANDWIDTHDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lpddpfFormat: ?*DDPIXELFORMAT, dwWidth: u32, dwHeight: u32, dwFlags: u32, lpBandwidth: ?*DDVIDEOPORTBANDWIDTH, ddRVal: HRESULT, GetVideoPortBandwidth: ?*c_void, }; pub const DD_GETVPORTINPUTFORMATDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpddpfFormat: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortInputFormats: ?*c_void, }; pub const DD_GETVPORTOUTPUTFORMATDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpddpfInputFormat: ?*DDPIXELFORMAT, lpddpfOutputFormats: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortInputFormats: ?*c_void, }; pub const DD_GETVPORTFIELDDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, bField: BOOL, ddRVal: HRESULT, GetVideoPortField: ?*c_void, }; pub const DD_GETVPORTLINEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwLine: u32, ddRVal: HRESULT, GetVideoPortLine: ?*c_void, }; pub const DD_GETVPORTCONNECTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, dwPortId: u32, lpConnect: ?*DDVIDEOPORTCONNECT, dwNumEntries: u32, ddRVal: HRESULT, GetVideoPortConnectInfo: ?*c_void, }; pub const DD_DESTROYVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, ddRVal: HRESULT, DestroyVideoPort: ?*c_void, }; pub const DD_GETVPORTFLIPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, fpSurface: usize, ddRVal: HRESULT, GetVideoPortFlipStatus: ?*c_void, }; pub const DD_UPDATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lplpDDSurface: ?*?*DD_SURFACE_INT, lplpDDVBISurface: ?*?*DD_SURFACE_INT, lpVideoInfo: ?*DDVIDEOPORTINFO, dwFlags: u32, dwNumAutoflip: u32, dwNumVBIAutoflip: u32, ddRVal: HRESULT, UpdateVideoPort: ?*c_void, }; pub const DD_WAITFORVPORTSYNCDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, dwLine: u32, dwTimeOut: u32, ddRVal: HRESULT, UpdateVideoPort: ?*c_void, }; pub const DD_GETVPORTSIGNALDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwStatus: u32, ddRVal: HRESULT, GetVideoSignalStatus: ?*c_void, }; pub const DD_VPORTCOLORDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpColorData: ?*DDCOLORCONTROL, ddRVal: HRESULT, ColorControl: ?*c_void, }; pub const DD_COLORCONTROLDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpColorData: ?*DDCOLORCONTROL, dwFlags: u32, ddRVal: HRESULT, ColorControl: ?*c_void, }; pub const DD_GETDRIVERINFODATA = extern struct { dhpdev: ?*c_void, dwSize: u32, dwFlags: u32, guidInfo: Guid, dwExpectedSize: u32, lpvData: ?*c_void, dwActualSize: u32, ddRVal: HRESULT, }; pub const DD_GETAVAILDRIVERMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, DDSCaps: DDSCAPS, dwTotal: u32, dwFree: u32, ddRVal: HRESULT, GetAvailDriverMemory: ?*c_void, }; pub const DD_FREEDRIVERMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, FreeDriverMemory: ?*c_void, }; pub const DD_SETEXCLUSIVEMODEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwEnterExcl: u32, dwReserved: u32, ddRVal: HRESULT, SetExclusiveMode: ?*c_void, }; pub const DD_FLIPTOGDISURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwToGDI: u32, dwReserved: u32, ddRVal: HRESULT, FlipToGDISurface: ?*c_void, }; pub const DD_SYNCSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwSurfaceOffset: u32, fpLockPtr: usize, lPitch: i32, dwOverlayOffset: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, dwDriverReserved4: u32, ddRVal: HRESULT, }; pub const DD_SYNCVIDEOPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwOriginOffset: u32, dwHeight: u32, dwVBIHeight: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, ddRVal: HRESULT, }; pub const DD_GETMOCOMPGUIDSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, dwNumGuids: u32, lpGuids: ?*Guid, ddRVal: HRESULT, }; pub const DD_GETMOCOMPFORMATSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwNumFormats: u32, lpFormats: ?*DDPIXELFORMAT, ddRVal: HRESULT, }; pub const DD_CREATEMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpGuid: ?*Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, lpData: ?*c_void, dwDataSize: u32, ddRVal: HRESULT, }; pub const DDCOMPBUFFERINFO = extern struct { dwSize: u32, dwNumCompBuffers: u32, dwWidthToCreate: u32, dwHeightToCreate: u32, dwBytesToAllocate: u32, ddCompCaps: DDSCAPS2, ddPixelFormat: DDPIXELFORMAT, }; pub const DD_GETMOCOMPCOMPBUFFDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwNumTypesCompBuffs: u32, lpCompBuffInfo: ?*DDCOMPBUFFERINFO, ddRVal: HRESULT, }; pub const DD_GETINTERNALMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwScratchMemAlloc: u32, ddRVal: HRESULT, }; pub const DD_BEGINMOCOMPFRAMEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpDestSurface: ?*DD_SURFACE_LOCAL, dwInputDataSize: u32, lpInputData: ?*c_void, dwOutputDataSize: u32, lpOutputData: ?*c_void, ddRVal: HRESULT, }; pub const DD_ENDMOCOMPFRAMEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpInputData: ?*c_void, dwInputDataSize: u32, ddRVal: HRESULT, }; pub const DDMOCOMPBUFFERINFO = extern struct { dwSize: u32, lpCompSurface: ?*DD_SURFACE_LOCAL, dwDataOffset: u32, dwDataSize: u32, lpPrivate: ?*c_void, }; pub const DD_RENDERMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, dwNumBuffers: u32, lpBufferInfo: ?*DDMOCOMPBUFFERINFO, dwFunction: u32, lpInputData: ?*c_void, dwInputDataSize: u32, lpOutputData: ?*c_void, dwOutputDataSize: u32, ddRVal: HRESULT, }; pub const DD_QUERYMOCOMPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, }; pub const DD_DESTROYMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, ddRVal: HRESULT, }; pub const DD_CREATESURFACEEXDATA = extern struct { dwFlags: u32, lpDDLcl: ?*DD_DIRECTDRAW_LOCAL, lpDDSLcl: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, }; pub const DD_GETDRIVERSTATEDATA = extern struct { dwFlags: u32, Anonymous: extern union { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwhContext: usize, }, lpdwStates: ?*u32, dwLength: u32, ddRVal: HRESULT, }; pub const DEVMODEA = extern struct { dmDeviceName: [32]u8, dmSpecVersion: u16, dmDriverVersion: u16, dmSize: u16, dmDriverExtra: u16, dmFields: u32, Anonymous1: extern union { Anonymous1: extern struct { dmOrientation: i16, dmPaperSize: i16, dmPaperLength: i16, dmPaperWidth: i16, dmScale: i16, dmCopies: i16, dmDefaultSource: i16, dmPrintQuality: i16, }, Anonymous2: extern struct { dmPosition: POINTL, dmDisplayOrientation: u32, dmDisplayFixedOutput: u32, }, }, dmColor: i16, dmDuplex: i16, dmYResolution: i16, dmTTOption: i16, dmCollate: i16, dmFormName: [32]u8, dmLogPixels: u16, dmBitsPerPel: u32, dmPelsWidth: u32, dmPelsHeight: u32, Anonymous2: extern union { dmDisplayFlags: u32, dmNup: u32, }, dmDisplayFrequency: u32, dmICMMethod: u32, dmICMIntent: u32, dmMediaType: u32, dmDitherType: u32, dmReserved1: u32, dmReserved2: u32, dmPanningWidth: u32, dmPanningHeight: u32, }; pub const DEVMODEW = extern struct { dmDeviceName: [32]u16, dmSpecVersion: u16, dmDriverVersion: u16, dmSize: u16, dmDriverExtra: u16, dmFields: u32, Anonymous1: extern union { Anonymous1: extern struct { dmOrientation: i16, dmPaperSize: i16, dmPaperLength: i16, dmPaperWidth: i16, dmScale: i16, dmCopies: i16, dmDefaultSource: i16, dmPrintQuality: i16, }, Anonymous2: extern struct { dmPosition: POINTL, dmDisplayOrientation: u32, dmDisplayFixedOutput: u32, }, }, dmColor: i16, dmDuplex: i16, dmYResolution: i16, dmTTOption: i16, dmCollate: i16, dmFormName: [32]u16, dmLogPixels: u16, dmBitsPerPel: u32, dmPelsWidth: u32, dmPelsHeight: u32, Anonymous2: extern union { dmDisplayFlags: u32, dmNup: u32, }, dmDisplayFrequency: u32, dmICMMethod: u32, dmICMIntent: u32, dmMediaType: u32, dmDitherType: u32, dmReserved1: u32, dmReserved2: u32, dmPanningWidth: u32, dmPanningHeight: u32, }; pub const DISPLAYCONFIG_RATIONAL = extern struct { Numerator: u32, Denominator: u32, }; pub const DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY = enum(i32) { OTHER = -1, HD15 = 0, SVIDEO = 1, COMPOSITE_VIDEO = 2, COMPONENT_VIDEO = 3, DVI = 4, HDMI = 5, LVDS = 6, D_JPN = 8, SDI = 9, DISPLAYPORT_EXTERNAL = 10, DISPLAYPORT_EMBEDDED = 11, UDI_EXTERNAL = 12, UDI_EMBEDDED = 13, SDTVDONGLE = 14, MIRACAST = 15, INDIRECT_WIRED = 16, INDIRECT_VIRTUAL = 17, INTERNAL = -2147483648, // FORCE_UINT32 = -1, this enum value conflicts with OTHER }; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.OTHER; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15 = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.HD15; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SVIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SVIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPOSITE_VIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.COMPOSITE_VIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPONENT_VIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.COMPONENT_VIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DVI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.HDMI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_LVDS = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.LVDS; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_D_JPN = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.D_JPN; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SDI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EXTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DISPLAYPORT_EXTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DISPLAYPORT_EMBEDDED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EXTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.UDI_EXTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.UDI_EMBEDDED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDTVDONGLE = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SDTVDONGLE; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_MIRACAST = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.MIRACAST; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_WIRED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INDIRECT_WIRED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_VIRTUAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INDIRECT_VIRTUAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_FORCE_UINT32 = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.OTHER; pub const DISPLAYCONFIG_SCANLINE_ORDERING = enum(i32) { UNSPECIFIED = 0, PROGRESSIVE = 1, INTERLACED = 2, // INTERLACED_UPPERFIELDFIRST = 2, this enum value conflicts with INTERLACED INTERLACED_LOWERFIELDFIRST = 3, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = DISPLAYCONFIG_SCANLINE_ORDERING.UNSPECIFIED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = DISPLAYCONFIG_SCANLINE_ORDERING.PROGRESSIVE; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED_LOWERFIELDFIRST; pub const DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = DISPLAYCONFIG_SCANLINE_ORDERING.FORCE_UINT32; pub const DISPLAYCONFIG_2DREGION = extern struct { cx: u32, cy: u32, }; pub const DISPLAYCONFIG_VIDEO_SIGNAL_INFO = extern struct { pixelRate: u64, hSyncFreq: DISPLAYCONFIG_RATIONAL, vSyncFreq: DISPLAYCONFIG_RATIONAL, activeSize: DISPLAYCONFIG_2DREGION, totalSize: DISPLAYCONFIG_2DREGION, Anonymous: extern union { AdditionalSignalInfo: extern struct { _bitfield: u32, }, videoStandard: u32, }, scanLineOrdering: DISPLAYCONFIG_SCANLINE_ORDERING, }; pub const DISPLAYCONFIG_SCALING = enum(i32) { IDENTITY = 1, CENTERED = 2, STRETCHED = 3, ASPECTRATIOCENTEREDMAX = 4, CUSTOM = 5, PREFERRED = 128, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_SCALING_IDENTITY = DISPLAYCONFIG_SCALING.IDENTITY; pub const DISPLAYCONFIG_SCALING_CENTERED = DISPLAYCONFIG_SCALING.CENTERED; pub const DISPLAYCONFIG_SCALING_STRETCHED = DISPLAYCONFIG_SCALING.STRETCHED; pub const DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX = DISPLAYCONFIG_SCALING.ASPECTRATIOCENTEREDMAX; pub const DISPLAYCONFIG_SCALING_CUSTOM = DISPLAYCONFIG_SCALING.CUSTOM; pub const DISPLAYCONFIG_SCALING_PREFERRED = DISPLAYCONFIG_SCALING.PREFERRED; pub const DISPLAYCONFIG_SCALING_FORCE_UINT32 = DISPLAYCONFIG_SCALING.FORCE_UINT32; pub const DISPLAYCONFIG_ROTATION = enum(i32) { IDENTITY = 1, ROTATE90 = 2, ROTATE180 = 3, ROTATE270 = 4, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_ROTATION_IDENTITY = DISPLAYCONFIG_ROTATION.IDENTITY; pub const DISPLAYCONFIG_ROTATION_ROTATE90 = DISPLAYCONFIG_ROTATION.ROTATE90; pub const DISPLAYCONFIG_ROTATION_ROTATE180 = DISPLAYCONFIG_ROTATION.ROTATE180; pub const DISPLAYCONFIG_ROTATION_ROTATE270 = DISPLAYCONFIG_ROTATION.ROTATE270; pub const DISPLAYCONFIG_ROTATION_FORCE_UINT32 = DISPLAYCONFIG_ROTATION.FORCE_UINT32; pub const DISPLAYCONFIG_MODE_INFO_TYPE = enum(i32) { SOURCE = 1, TARGET = 2, DESKTOP_IMAGE = 3, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_MODE_INFO_TYPE_SOURCE = DISPLAYCONFIG_MODE_INFO_TYPE.SOURCE; pub const DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = DISPLAYCONFIG_MODE_INFO_TYPE.TARGET; pub const DISPLAYCONFIG_MODE_INFO_TYPE_DESKTOP_IMAGE = DISPLAYCONFIG_MODE_INFO_TYPE.DESKTOP_IMAGE; pub const DISPLAYCONFIG_MODE_INFO_TYPE_FORCE_UINT32 = DISPLAYCONFIG_MODE_INFO_TYPE.FORCE_UINT32; pub const DISPLAYCONFIG_PIXELFORMAT = enum(i32) { @"8BPP" = 1, @"16BPP" = 2, @"24BPP" = 3, @"32BPP" = 4, NONGDI = 5, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_PIXELFORMAT_8BPP = DISPLAYCONFIG_PIXELFORMAT.@"8BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_16BPP = DISPLAYCONFIG_PIXELFORMAT.@"16BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_24BPP = DISPLAYCONFIG_PIXELFORMAT.@"24BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_32BPP = DISPLAYCONFIG_PIXELFORMAT.@"32BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_NONGDI = DISPLAYCONFIG_PIXELFORMAT.NONGDI; pub const DISPLAYCONFIG_PIXELFORMAT_FORCE_UINT32 = DISPLAYCONFIG_PIXELFORMAT.FORCE_UINT32; pub const DISPLAYCONFIG_SOURCE_MODE = extern struct { width: u32, height: u32, pixelFormat: DISPLAYCONFIG_PIXELFORMAT, position: POINTL, }; pub const DISPLAYCONFIG_TARGET_MODE = extern struct { targetVideoSignalInfo: DISPLAYCONFIG_VIDEO_SIGNAL_INFO, }; pub const DISPLAYCONFIG_DESKTOP_IMAGE_INFO = extern struct { PathSourceSize: POINTL, DesktopImageRegion: RECTL, DesktopImageClip: RECTL, }; pub const DISPLAYCONFIG_MODE_INFO = extern struct { infoType: DISPLAYCONFIG_MODE_INFO_TYPE, id: u32, adapterId: LUID, Anonymous: extern union { targetMode: DISPLAYCONFIG_TARGET_MODE, sourceMode: DISPLAYCONFIG_SOURCE_MODE, desktopImageInfo: DISPLAYCONFIG_DESKTOP_IMAGE_INFO, }, }; pub const DISPLAYCONFIG_PATH_SOURCE_INFO = extern struct { adapterId: LUID, id: u32, Anonymous: extern union { modeInfoIdx: u32, Anonymous: extern struct { _bitfield: u32, }, }, statusFlags: u32, }; pub const DISPLAYCONFIG_PATH_TARGET_INFO = extern struct { adapterId: LUID, id: u32, Anonymous: extern union { modeInfoIdx: u32, Anonymous: extern struct { _bitfield: u32, }, }, outputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, rotation: DISPLAYCONFIG_ROTATION, scaling: DISPLAYCONFIG_SCALING, refreshRate: DISPLAYCONFIG_RATIONAL, scanLineOrdering: DISPLAYCONFIG_SCANLINE_ORDERING, targetAvailable: BOOL, statusFlags: u32, }; pub const DISPLAYCONFIG_PATH_INFO = extern struct { sourceInfo: DISPLAYCONFIG_PATH_SOURCE_INFO, targetInfo: DISPLAYCONFIG_PATH_TARGET_INFO, flags: u32, }; pub const DISPLAYCONFIG_TOPOLOGY_ID = enum(i32) { INTERNAL = 1, CLONE = 2, EXTEND = 4, EXTERNAL = 8, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_TOPOLOGY_INTERNAL = DISPLAYCONFIG_TOPOLOGY_ID.INTERNAL; pub const DISPLAYCONFIG_TOPOLOGY_CLONE = DISPLAYCONFIG_TOPOLOGY_ID.CLONE; pub const DISPLAYCONFIG_TOPOLOGY_EXTEND = DISPLAYCONFIG_TOPOLOGY_ID.EXTEND; pub const DISPLAYCONFIG_TOPOLOGY_EXTERNAL = DISPLAYCONFIG_TOPOLOGY_ID.EXTERNAL; pub const DISPLAYCONFIG_TOPOLOGY_FORCE_UINT32 = DISPLAYCONFIG_TOPOLOGY_ID.FORCE_UINT32; pub const DISPLAYCONFIG_DEVICE_INFO_TYPE = enum(i32) { GET_SOURCE_NAME = 1, GET_TARGET_NAME = 2, GET_TARGET_PREFERRED_MODE = 3, GET_ADAPTER_NAME = 4, SET_TARGET_PERSISTENCE = 5, GET_TARGET_BASE_TYPE = 6, GET_SUPPORT_VIRTUAL_RESOLUTION = 7, SET_SUPPORT_VIRTUAL_RESOLUTION = 8, GET_ADVANCED_COLOR_INFO = 9, SET_ADVANCED_COLOR_STATE = 10, GET_SDR_WHITE_LEVEL = 11, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SOURCE_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_PREFERRED_MODE = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_PREFERRED_MODE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_ADAPTER_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_ADAPTER_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_SET_TARGET_PERSISTENCE = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_TARGET_PERSISTENCE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_BASE_TYPE = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_BASE_TYPE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SUPPORT_VIRTUAL_RESOLUTION = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SUPPORT_VIRTUAL_RESOLUTION; pub const DISPLAYCONFIG_DEVICE_INFO_SET_SUPPORT_VIRTUAL_RESOLUTION = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_SUPPORT_VIRTUAL_RESOLUTION; pub const DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_ADVANCED_COLOR_INFO; pub const DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_ADVANCED_COLOR_STATE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SDR_WHITE_LEVEL; pub const DISPLAYCONFIG_DEVICE_INFO_FORCE_UINT32 = DISPLAYCONFIG_DEVICE_INFO_TYPE.FORCE_UINT32; pub const DISPLAYCONFIG_DEVICE_INFO_HEADER = extern struct { type: DISPLAYCONFIG_DEVICE_INFO_TYPE, size: u32, adapterId: LUID, id: u32, }; pub const DISPLAYCONFIG_SOURCE_DEVICE_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, viewGdiDeviceName: [32]u16, }; pub const DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS = extern struct { Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_TARGET_DEVICE_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, flags: DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS, outputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, edidManufactureId: u16, edidProductCodeId: u16, connectorInstance: u32, monitorFriendlyDeviceName: [64]u16, monitorDevicePath: [128]u16, }; pub const DISPLAYCONFIG_TARGET_PREFERRED_MODE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, width: u32, height: u32, targetMode: DISPLAYCONFIG_TARGET_MODE, }; pub const DISPLAYCONFIG_ADAPTER_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, adapterDevicePath: [128]u16, }; pub const DISPLAYCONFIG_TARGET_BASE_TYPE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, baseOutputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, }; pub const DISPLAYCONFIG_SET_TARGET_PERSISTENCE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_SUPPORT_VIRTUAL_RESOLUTION = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const VIDEOPARAMETERS = extern struct { Guid: Guid, dwOffset: u32, dwCommand: u32, dwFlags: u32, dwMode: u32, dwTVStandard: u32, dwAvailableModes: u32, dwAvailableTVStandard: u32, dwFlickerFilter: u32, dwOverScanX: u32, dwOverScanY: u32, dwMaxUnscaledX: u32, dwMaxUnscaledY: u32, dwPositionX: u32, dwPositionY: u32, dwBrightness: u32, dwContrast: u32, dwCPType: u32, dwCPCommand: u32, dwCPStandard: u32, dwCPKey: u32, bCP_APSTriggerBits: u32, bOEMCopyProtection: [256]u8, }; const IID_IDirectDrawKernel_Value = @import("../zig.zig").Guid.initString("8d56c120-6a08-11d0-9b06-00a0c903a3b8"); pub const IID_IDirectDrawKernel = &IID_IDirectDrawKernel_Value; pub const IDirectDrawKernel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCaps: fn( self: *const IDirectDrawKernel, param0: ?*DDKERNELCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKernelHandle: fn( self: *const IDirectDrawKernel, param0: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseKernelHandle: fn( self: *const IDirectDrawKernel, ) 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 IDirectDrawKernel_GetCaps(self: *const T, param0: ?*DDKERNELCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawKernel_GetKernelHandle(self: *const T, param0: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).GetKernelHandle(@ptrCast(*const IDirectDrawKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawKernel_ReleaseKernelHandle(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).ReleaseKernelHandle(@ptrCast(*const IDirectDrawKernel, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurfaceKernel_Value = @import("../zig.zig").Guid.initString("60755da0-6a40-11d0-9b06-00a0c903a3b8"); pub const IID_IDirectDrawSurfaceKernel = &IID_IDirectDrawSurfaceKernel_Value; pub const IDirectDrawSurfaceKernel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetKernelHandle: fn( self: *const IDirectDrawSurfaceKernel, param0: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseKernelHandle: fn( self: *const IDirectDrawSurfaceKernel, ) 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 IDirectDrawSurfaceKernel_GetKernelHandle(self: *const T, param0: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurfaceKernel.VTable, self.vtable).GetKernelHandle(@ptrCast(*const IDirectDrawSurfaceKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurfaceKernel_ReleaseKernelHandle(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurfaceKernel.VTable, self.vtable).ReleaseKernelHandle(@ptrCast(*const IDirectDrawSurfaceKernel, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DDKERNELCAPS = extern struct { dwSize: u32, dwCaps: u32, dwIRQCaps: u32, }; pub const IFIMETRICS = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cjThis: u32, cjIfiExtra: u32, dpwszFamilyName: i32, dpwszStyleName: i32, dpwszFaceName: i32, dpwszUniqueName: i32, dpFontSim: i32, lEmbedId: i32, lItalicAngle: i32, lCharBias: i32, dpCharSets: i32, jWinCharSet: u8, jWinPitchAndFamily: u8, usWinWeight: u16, flInfo: u32, fsSelection: u16, fsType: u16, fwdUnitsPerEm: i16, fwdLowestPPEm: i16, fwdWinAscender: i16, fwdWinDescender: i16, fwdMacAscender: i16, fwdMacDescender: i16, fwdMacLineGap: i16, fwdTypoAscender: i16, fwdTypoDescender: i16, fwdTypoLineGap: i16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, fwdCapHeight: i16, fwdXHeight: i16, fwdSubscriptXSize: i16, fwdSubscriptYSize: i16, fwdSubscriptXOffset: i16, fwdSubscriptYOffset: i16, fwdSuperscriptXSize: i16, fwdSuperscriptYSize: i16, fwdSuperscriptXOffset: i16, fwdSuperscriptYOffset: i16, fwdUnderscoreSize: i16, fwdUnderscorePosition: i16, fwdStrikeoutSize: i16, fwdStrikeoutPosition: i16, chFirstChar: u8, chLastChar: u8, chDefaultChar: u8, chBreakChar: u8, wcFirstChar: u16, wcLastChar: u16, wcDefaultChar: u16, wcBreakChar: u16, ptlBaseline: POINTL, ptlAspect: POINTL, ptlCaret: POINTL, rclFontBox: RECTL, achVendId: [4]u8, cKerningPairs: u32, ulPanoseCulture: u32, panose: PANOSE, Align: ?*c_void, }, .X86 => extern struct { cjThis: u32, cjIfiExtra: u32, dpwszFamilyName: i32, dpwszStyleName: i32, dpwszFaceName: i32, dpwszUniqueName: i32, dpFontSim: i32, lEmbedId: i32, lItalicAngle: i32, lCharBias: i32, dpCharSets: i32, jWinCharSet: u8, jWinPitchAndFamily: u8, usWinWeight: u16, flInfo: u32, fsSelection: u16, fsType: u16, fwdUnitsPerEm: i16, fwdLowestPPEm: i16, fwdWinAscender: i16, fwdWinDescender: i16, fwdMacAscender: i16, fwdMacDescender: i16, fwdMacLineGap: i16, fwdTypoAscender: i16, fwdTypoDescender: i16, fwdTypoLineGap: i16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, fwdCapHeight: i16, fwdXHeight: i16, fwdSubscriptXSize: i16, fwdSubscriptYSize: i16, fwdSubscriptXOffset: i16, fwdSubscriptYOffset: i16, fwdSuperscriptXSize: i16, fwdSuperscriptYSize: i16, fwdSuperscriptXOffset: i16, fwdSuperscriptYOffset: i16, fwdUnderscoreSize: i16, fwdUnderscorePosition: i16, fwdStrikeoutSize: i16, fwdStrikeoutPosition: i16, chFirstChar: u8, chLastChar: u8, chDefaultChar: u8, chBreakChar: u8, wcFirstChar: u16, wcLastChar: u16, wcDefaultChar: u16, wcBreakChar: u16, ptlBaseline: POINTL, ptlAspect: POINTL, ptlCaret: POINTL, rclFontBox: RECTL, achVendId: [4]u8, cKerningPairs: u32, ulPanoseCulture: u32, panose: PANOSE, }, }; //-------------------------------------------------------------------------------- // Section: Functions (83) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_pvAllocRbrush( pbo: ?*BRUSHOBJ, cj: u32, ) callconv(@import("std").os.windows.WINAPI) ?*c_void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_pvGetRbrush( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*c_void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_ulGetBrushColor( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_hGetColorTransform( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_cEnumStart( pco: ?*CLIPOBJ, bAll: BOOL, iType: u32, iDirection: u32, cLimit: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_bEnum( pco: ?*CLIPOBJ, cj: u32, pul: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_ppoGetPath( pco: ?*CLIPOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*PATHOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_cGetAllGlyphHandles( pfo: ?*FONTOBJ, phg: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_vGetInfo( pfo: ?*FONTOBJ, cjSize: u32, pfi: ?*FONTINFO, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_cGetGlyphs( pfo: ?*FONTOBJ, iMode: u32, cGlyph: u32, phg: ?*u32, ppvGlyph: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pxoGetXform( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*XFORMOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pifi( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*IFIMETRICS; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pfdg( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHSET; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pvTrueTypeFontFile( pfo: ?*FONTOBJ, pcjFile: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?*c_void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pQueryGlyphAttrs( pfo: ?*FONTOBJ, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHATTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vEnumStart( ppo: ?*PATHOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_bEnum( ppo: ?*PATHOBJ, ppd: ?*PATHDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vEnumStartClipLines( ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pso: ?*SURFOBJ, pla: ?*LINEATTRS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_bEnumClipLines( ppo: ?*PATHOBJ, cb: u32, pcl: ?*CLIPLINE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vGetBounds( ppo: ?*PATHOBJ, prectfx: ?*RECTFX, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_vEnumStart( pstro: ?*STROBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bEnum( pstro: ?*STROBJ, pc: ?*u32, ppgpos: ?*?*GLYPHPOS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bEnumPositionsOnly( pstro: ?*STROBJ, pc: ?*u32, ppgpos: ?*?*GLYPHPOS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_dwGetCodePage( pstro: ?*STROBJ, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bGetAdvanceWidths( pso: ?*STROBJ, iFirst: u32, c: u32, pptqD: ?*POINTQF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XFORMOBJ_iGetXform( pxo: ?*XFORMOBJ, pxform: ?*XFORML, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XFORMOBJ_bApplyXform( pxo: ?*XFORMOBJ, iMode: u32, cPoints: u32, pvIn: ?*c_void, pvOut: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_iXlate( pxlo: ?*XLATEOBJ, iColor: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_piVector( pxlo: ?*XLATEOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_cGetPalette( pxlo: ?*XLATEOBJ, iPal: u32, cPal: u32, pPal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_hGetColorTransform( pxlo: ?*XLATEOBJ, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateBitmap( sizl: SIZE, lWidth: i32, iFormat: u32, fl: u32, pvBits: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateDeviceSurface( dhsurf: DHSURF, sizl: SIZE, iFormatCompat: u32, ) callconv(@import("std").os.windows.WINAPI) ?HSURF; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateDeviceBitmap( dhsurf: DHSURF, sizl: SIZE, iFormatCompat: u32, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLockSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) ?*SURFOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngUnlockSurface( pso: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngEraseSurface( pso: ?*SURFOBJ, prcl: ?*RECTL, iColor: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAssociateSurface( hsurf: ?HSURF, hdev: ?HDEV, flHooks: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMarkBandingSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCheckAbort( pso: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeletePath( ppo: ?*PATHOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreatePalette( iMode: u32, cColors: u32, pulColors: ?*u32, flRed: u32, flGreen: u32, flBlue: u32, ) callconv(@import("std").os.windows.WINAPI) ?HPALETTE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeletePalette( hpal: ?HPALETTE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateClip( ) callconv(@import("std").os.windows.WINAPI) ?*CLIPOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteClip( pco: ?*CLIPOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngBitBlt( psoTrg: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclTrg: ?*RECTL, pptlSrc: ?*POINTL, pptlMask: ?*POINTL, pbo: ?*BRUSHOBJ, pptlBrush: ?*POINTL, rop4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLineTo( pso: ?*SURFOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, x1: i32, y1: i32, x2: i32, y2: i32, prclBounds: ?*RECTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStretchBlt( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlHTOrg: ?*POINTL, prclDest: ?*RECTL, prclSrc: ?*RECTL, pptlMask: ?*POINTL, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStretchBltROP( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlHTOrg: ?*POINTL, prclDest: ?*RECTL, prclSrc: ?*RECTL, pptlMask: ?*POINTL, iMode: u32, pbo: ?*BRUSHOBJ, rop4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAlphaBlend( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDest: ?*RECTL, prclSrc: ?*RECTL, pBlendObj: ?*BLENDOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGradientFill( psoDest: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pVertex: ?*TRIVERTEX, nVertex: u32, pMesh: ?*c_void, nMesh: u32, prclExtents: ?*RECTL, pptlDitherOrg: ?*POINTL, ulMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngTransparentBlt( psoDst: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDst: ?*RECTL, prclSrc: ?*RECTL, TransColor: u32, bCalledFromBitBlt: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngTextOut( pso: ?*SURFOBJ, pstro: ?*STROBJ, pfo: ?*FONTOBJ, pco: ?*CLIPOBJ, prclExtra: ?*RECTL, prclOpaque: ?*RECTL, pboFore: ?*BRUSHOBJ, pboOpaque: ?*BRUSHOBJ, pptlOrg: ?*POINTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStrokePath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pxo: ?*XFORMOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, plineattrs: ?*LINEATTRS, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFillPath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mix: u32, flOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStrokeAndFillPath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pxo: ?*XFORMOBJ, pboStroke: ?*BRUSHOBJ, plineattrs: ?*LINEATTRS, pboFill: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mixFill: u32, flOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngPaint( pso: ?*SURFOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCopyBits( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDest: ?*RECTL, pptlSrc: ?*POINTL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngPlgBlt( psoTrg: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMsk: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlBrushOrg: ?*POINTL, pptfx: ?*POINTFIX, prcl: ?*RECTL, pptl: ?*POINTL, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn HT_Get8BPPFormatPalette( pPaletteEntry: ?*PALETTEENTRY, RedGamma: u16, GreenGamma: u16, BlueGamma: u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn HT_Get8BPPMaskPalette( pPaletteEntry: ?*PALETTEENTRY, Use8BPPMaskPal: BOOL, CMYMask: u8, RedGamma: u16, GreenGamma: u16, BlueGamma: u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetPrinterDataFileName( hdev: ?HDEV, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetDriverName( hdev: ?HDEV, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLoadModule( pwsz: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFindResource( h: ?HANDLE, iName: i32, iType: i32, pulSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?*c_void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFreeModule( h: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateSemaphore( ) callconv(@import("std").os.windows.WINAPI) ?*HSEMAPHORE__; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAcquireSemaphore( hsem: ?*HSEMAPHORE__, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngReleaseSemaphore( hsem: ?*HSEMAPHORE__, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteSemaphore( hsem: ?*HSEMAPHORE__, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMultiByteToUnicodeN( // TODO: what to do with BytesParamIndex 1? UnicodeString: ?PWSTR, MaxBytesInUnicodeString: u32, BytesInUnicodeString: ?*u32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?[*]u8, BytesInMultiByteString: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngUnicodeToMultiByteN( // TODO: what to do with BytesParamIndex 1? MultiByteString: ?[*]u8, MaxBytesInMultiByteString: u32, BytesInMultiByteString: ?*u32, // TODO: what to do with BytesParamIndex 4? UnicodeString: ?PWSTR, BytesInUnicodeString: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngQueryLocalTime( param0: ?*ENG_TIME_FIELDS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngComputeGlyphSet( nCodePage: i32, nFirstChar: i32, cChars: i32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHSET; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMultiByteToWideChar( CodePage: u32, // TODO: what to do with BytesParamIndex 2? WideCharString: ?PWSTR, BytesInWideCharString: i32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?PSTR, BytesInMultiByteString: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngWideCharToMultiByte( CodePage: u32, // TODO: what to do with BytesParamIndex 2? WideCharString: ?PWSTR, BytesInWideCharString: i32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?PSTR, BytesInMultiByteString: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetCurrentCodePage( OemCodePage: ?*u16, AnsiCodePage: ?*u16, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn GetDisplayConfigBufferSizes( flags: u32, numPathArrayElements: ?*u32, numModeInfoArrayElements: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn SetDisplayConfig( numPathArrayElements: u32, pathArray: ?[*]DISPLAYCONFIG_PATH_INFO, numModeInfoArrayElements: u32, modeInfoArray: ?[*]DISPLAYCONFIG_MODE_INFO, flags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn QueryDisplayConfig( flags: u32, numPathArrayElements: ?*u32, pathArray: [*]DISPLAYCONFIG_PATH_INFO, numModeInfoArrayElements: ?*u32, modeInfoArray: [*]DISPLAYCONFIG_MODE_INFO, currentTopologyId: ?*DISPLAYCONFIG_TOPOLOGY_ID, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn DisplayConfigGetDeviceInfo( requestPacket: ?*DISPLAYCONFIG_DEVICE_INFO_HEADER, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn DisplayConfigSetDeviceInfo( setPacket: ?*DISPLAYCONFIG_DEVICE_INFO_HEADER, ) callconv(@import("std").os.windows.WINAPI) i32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (1) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const DEVMODE = thismodule.DEVMODEA; }, .wide => struct { pub const DEVMODE = thismodule.DEVMODEW; }, .unspecified => if (@import("builtin").is_test) struct { pub const DEVMODE = *opaque{}; } else struct { pub const DEVMODE = @compileError("'DEVMODE' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (55) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BLENDFUNCTION = @import("../graphics/gdi.zig").BLENDFUNCTION; const BOOL = @import("../foundation.zig").BOOL; const COLORADJUSTMENT = @import("../graphics/gdi.zig").COLORADJUSTMENT; const DD_DESTROYDDLOCALDATA = @import("../graphics/direct_draw.zig").DD_DESTROYDDLOCALDATA; const DDARGB = @import("../graphics/direct_draw.zig").DDARGB; const DDBLTFX = @import("../graphics/direct_draw.zig").DDBLTFX; const DDCOLORCONTROL = @import("../graphics/direct_draw.zig").DDCOLORCONTROL; const DDCOLORKEY = @import("../graphics/direct_draw.zig").DDCOLORKEY; const DDNTCORECAPS = @import("../graphics/direct_draw.zig").DDNTCORECAPS; const DDOVERLAYFX = @import("../graphics/direct_draw.zig").DDOVERLAYFX; const DDPIXELFORMAT = @import("../graphics/direct_draw.zig").DDPIXELFORMAT; const DDRAWI_DIRECTDRAW_GBL = @import("../graphics/direct_draw.zig").DDRAWI_DIRECTDRAW_GBL; const DDRAWI_DIRECTDRAW_LCL = @import("../graphics/direct_draw.zig").DDRAWI_DIRECTDRAW_LCL; const DDSCAPS = @import("../graphics/direct_draw.zig").DDSCAPS; const DDSCAPS2 = @import("../graphics/direct_draw.zig").DDSCAPS2; const DDSCAPSEX = @import("../graphics/direct_draw.zig").DDSCAPSEX; const DDSURFACEDESC = @import("../graphics/direct_draw.zig").DDSURFACEDESC; const DDVIDEOPORTCONNECT = @import("../graphics/direct_draw.zig").DDVIDEOPORTCONNECT; const DHPDEV = @import("../system/system_services.zig").DHPDEV; const DHSURF = @import("../system/system_services.zig").DHSURF; const FLOAT_LONG = @import("../system/system_services.zig").FLOAT_LONG; const FREEOBJPROC = @import("../system/system_services.zig").FREEOBJPROC; const HANDLE = @import("../foundation.zig").HANDLE; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HDEV = @import("../system/system_services.zig").HDEV; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HRESULT = @import("../foundation.zig").HRESULT; const HSEMAPHORE__ = @import("../system/system_services.zig").HSEMAPHORE__; const HSURF = @import("../system/system_services.zig").HSURF; const IUnknown = @import("../system/com.zig").IUnknown; const LOGFONTW = @import("../graphics/gdi.zig").LOGFONTW; const LPDDHAL_WAITFORVERTICALBLANK = @import("../graphics/direct_draw.zig").LPDDHAL_WAITFORVERTICALBLANK; const LUID = @import("../system/system_services.zig").LUID; const PALETTEENTRY = @import("../graphics/gdi.zig").PALETTEENTRY; const PANOSE = @import("../graphics/gdi.zig").PANOSE; const PDD_ALPHABLT = @import("../graphics/direct_draw.zig").PDD_ALPHABLT; const PDD_DESTROYDRIVER = @import("../graphics/direct_draw.zig").PDD_DESTROYDRIVER; const PDD_SETCOLORKEY = @import("../graphics/direct_draw.zig").PDD_SETCOLORKEY; const PDD_SETMODE = @import("../graphics/direct_draw.zig").PDD_SETMODE; const PDD_SURFCB_SETCLIPLIST = @import("../graphics/direct_draw.zig").PDD_SURFCB_SETCLIPLIST; const PFN = @import("../system/system_services.zig").PFN; const POINTE = @import("../system/system_services.zig").POINTE; const POINTFIX = @import("../system/system_services.zig").POINTFIX; const POINTL = @import("../foundation.zig").POINTL; const POINTQF = @import("../system/system_services.zig").POINTQF; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const RECTFX = @import("../system/system_services.zig").RECTFX; const RECTL = @import("../foundation.zig").RECTL; const SIZE = @import("../foundation.zig").SIZE; const TRIVERTEX = @import("../graphics/gdi.zig").TRIVERTEX; const VMEMHEAP = @import("../devices/display.zig").VMEMHEAP; const XFORMOBJ = @import("../system/system_services.zig").XFORMOBJ; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_DrvQueryGlyphAttrs")) { _ = PFN_DrvQueryGlyphAttrs; } if (@hasDecl(@This(), "PDD_CANCREATESURFACE")) { _ = PDD_CANCREATESURFACE; } if (@hasDecl(@This(), "PDD_WAITFORVERTICALBLANK")) { _ = PDD_WAITFORVERTICALBLANK; } if (@hasDecl(@This(), "PDD_CREATESURFACE")) { _ = PDD_CREATESURFACE; } if (@hasDecl(@This(), "PDD_CREATEPALETTE")) { _ = PDD_CREATEPALETTE; } if (@hasDecl(@This(), "PDD_GETSCANLINE")) { _ = PDD_GETSCANLINE; } if (@hasDecl(@This(), "PDD_MAPMEMORY")) { _ = PDD_MAPMEMORY; } if (@hasDecl(@This(), "PDD_GETDRIVERINFO")) { _ = PDD_GETDRIVERINFO; } if (@hasDecl(@This(), "PDD_GETAVAILDRIVERMEMORY")) { _ = PDD_GETAVAILDRIVERMEMORY; } if (@hasDecl(@This(), "PDD_CREATESURFACEEX")) { _ = PDD_CREATESURFACEEX; } if (@hasDecl(@This(), "PDD_GETDRIVERSTATE")) { _ = PDD_GETDRIVERSTATE; } if (@hasDecl(@This(), "PDD_DESTROYDDLOCAL")) { _ = PDD_DESTROYDDLOCAL; } if (@hasDecl(@This(), "PDD_FREEDRIVERMEMORY")) { _ = PDD_FREEDRIVERMEMORY; } if (@hasDecl(@This(), "PDD_SETEXCLUSIVEMODE")) { _ = PDD_SETEXCLUSIVEMODE; } if (@hasDecl(@This(), "PDD_FLIPTOGDISURFACE")) { _ = PDD_FLIPTOGDISURFACE; } if (@hasDecl(@This(), "PDD_PALCB_DESTROYPALETTE")) { _ = PDD_PALCB_DESTROYPALETTE; } if (@hasDecl(@This(), "PDD_PALCB_SETENTRIES")) { _ = PDD_PALCB_SETENTRIES; } if (@hasDecl(@This(), "PDD_SURFCB_LOCK")) { _ = PDD_SURFCB_LOCK; } if (@hasDecl(@This(), "PDD_SURFCB_UNLOCK")) { _ = PDD_SURFCB_UNLOCK; } if (@hasDecl(@This(), "PDD_SURFCB_BLT")) { _ = PDD_SURFCB_BLT; } if (@hasDecl(@This(), "PDD_SURFCB_UPDATEOVERLAY")) { _ = PDD_SURFCB_UPDATEOVERLAY; } if (@hasDecl(@This(), "PDD_SURFCB_SETOVERLAYPOSITION")) { _ = PDD_SURFCB_SETOVERLAYPOSITION; } if (@hasDecl(@This(), "PDD_SURFCB_SETPALETTE")) { _ = PDD_SURFCB_SETPALETTE; } if (@hasDecl(@This(), "PDD_SURFCB_FLIP")) { _ = PDD_SURFCB_FLIP; } if (@hasDecl(@This(), "PDD_SURFCB_DESTROYSURFACE")) { _ = PDD_SURFCB_DESTROYSURFACE; } if (@hasDecl(@This(), "PDD_SURFCB_ADDATTACHEDSURFACE")) { _ = PDD_SURFCB_ADDATTACHEDSURFACE; } if (@hasDecl(@This(), "PDD_SURFCB_SETCOLORKEY")) { _ = PDD_SURFCB_SETCOLORKEY; } if (@hasDecl(@This(), "PDD_SURFCB_GETBLTSTATUS")) { _ = PDD_SURFCB_GETBLTSTATUS; } if (@hasDecl(@This(), "PDD_SURFCB_GETFLIPSTATUS")) { _ = PDD_SURFCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_CANCREATEVIDEOPORT")) { _ = PDD_VPORTCB_CANCREATEVIDEOPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_CREATEVIDEOPORT")) { _ = PDD_VPORTCB_CREATEVIDEOPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_FLIP")) { _ = PDD_VPORTCB_FLIP; } if (@hasDecl(@This(), "PDD_VPORTCB_GETBANDWIDTH")) { _ = PDD_VPORTCB_GETBANDWIDTH; } if (@hasDecl(@This(), "PDD_VPORTCB_GETINPUTFORMATS")) { _ = PDD_VPORTCB_GETINPUTFORMATS; } if (@hasDecl(@This(), "PDD_VPORTCB_GETOUTPUTFORMATS")) { _ = PDD_VPORTCB_GETOUTPUTFORMATS; } if (@hasDecl(@This(), "PDD_VPORTCB_GETFIELD")) { _ = PDD_VPORTCB_GETFIELD; } if (@hasDecl(@This(), "PDD_VPORTCB_GETLINE")) { _ = PDD_VPORTCB_GETLINE; } if (@hasDecl(@This(), "PDD_VPORTCB_GETVPORTCONNECT")) { _ = PDD_VPORTCB_GETVPORTCONNECT; } if (@hasDecl(@This(), "PDD_VPORTCB_DESTROYVPORT")) { _ = PDD_VPORTCB_DESTROYVPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_GETFLIPSTATUS")) { _ = PDD_VPORTCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_UPDATE")) { _ = PDD_VPORTCB_UPDATE; } if (@hasDecl(@This(), "PDD_VPORTCB_WAITFORSYNC")) { _ = PDD_VPORTCB_WAITFORSYNC; } if (@hasDecl(@This(), "PDD_VPORTCB_GETSIGNALSTATUS")) { _ = PDD_VPORTCB_GETSIGNALSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_COLORCONTROL")) { _ = PDD_VPORTCB_COLORCONTROL; } if (@hasDecl(@This(), "PDD_COLORCB_COLORCONTROL")) { _ = PDD_COLORCB_COLORCONTROL; } if (@hasDecl(@This(), "PDD_KERNELCB_SYNCSURFACE")) { _ = PDD_KERNELCB_SYNCSURFACE; } if (@hasDecl(@This(), "PDD_KERNELCB_SYNCVIDEOPORT")) { _ = PDD_KERNELCB_SYNCVIDEOPORT; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETGUIDS")) { _ = PDD_MOCOMPCB_GETGUIDS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETFORMATS")) { _ = PDD_MOCOMPCB_GETFORMATS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_CREATE")) { _ = PDD_MOCOMPCB_CREATE; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETCOMPBUFFINFO")) { _ = PDD_MOCOMPCB_GETCOMPBUFFINFO; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETINTERNALINFO")) { _ = PDD_MOCOMPCB_GETINTERNALINFO; } if (@hasDecl(@This(), "PDD_MOCOMPCB_BEGINFRAME")) { _ = PDD_MOCOMPCB_BEGINFRAME; } if (@hasDecl(@This(), "PDD_MOCOMPCB_ENDFRAME")) { _ = PDD_MOCOMPCB_ENDFRAME; } if (@hasDecl(@This(), "PDD_MOCOMPCB_RENDER")) { _ = PDD_MOCOMPCB_RENDER; } if (@hasDecl(@This(), "PDD_MOCOMPCB_QUERYSTATUS")) { _ = PDD_MOCOMPCB_QUERYSTATUS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_DESTROY")) { _ = PDD_MOCOMPCB_DESTROY; } @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/display_devices.zig
const std = @import("std"); const assert = std.debug.assert; const imgui = @import("imgui"); const glfw = @import("include/glfw.zig"); const vk = @import("include/vk.zig"); const impl_glfw = @import("imgui_impl_glfw.zig"); const impl_vulkan = @import("imgui_impl_vulkan.zig"); const build_mode = @import("builtin").mode; const build_safe = build_mode != .ReleaseFast; const IMGUI_UNLIMITED_FRAME_RATE = false; const IMGUI_VULKAN_DEBUG_REPORT = build_safe; var g_Allocator: ?*vk.AllocationCallbacks = null; var g_Instance: vk.Instance = undefined; var g_PhysicalDevice: vk.PhysicalDevice = undefined; var g_Device: vk.Device = undefined; var g_QueueFamily = ~@as(u32, 0); var g_Queue: vk.Queue = undefined; var g_DebugReport: vk.DebugReportCallbackEXT = undefined; var g_PipelineCache: vk.PipelineCache = undefined; var g_DescriptorPool: vk.DescriptorPool = undefined; var g_MainWindowData = impl_vulkan.Window{}; var g_MinImageCount = @as(u32, 2); var g_SwapChainRebuild = false; var g_SwapChainResizeWidth = @as(u32, 0); var g_SwapChainResizeHeight = @as(u32, 0); var g_ClearColor = imgui.Vec4{ .x = 0.5, .y = 0, .z = 1, .w = 1 }; fn debug_report(flags: vk.DebugReportFlagsEXT.IntType, objectType: vk.DebugReportObjectTypeEXT, object: u64, location: usize, messageCode: i32, pLayerPrefix: ?[*]const u8, pMessage: ?[*]const u8, pUserData: ?*c_void) callconv(vk.CallConv) vk.Bool32 { std.debug.warn("[vulkan] ObjectType: {}\nMessage: {}\n\n", .{ objectType, pMessage }); @panic("VK Error"); //return vk.FALSE; } fn SetupVulkan(extensions: []const [*:0]const u8, allocator: *std.mem.Allocator) !void { // Create Vulkan Instance { var create_info = vk.InstanceCreateInfo{ .enabledExtensionCount = @intCast(u32, extensions.len), .ppEnabledExtensionNames = extensions.ptr, }; if (IMGUI_VULKAN_DEBUG_REPORT) { // Enabling multiple validation layers grouped as LunarG standard validation const layers = [_][*:0]const u8{"VK_LAYER_LUNARG_standard_validation"}; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = &layers; // Enable debug report extension (we need additional storage, so we duplicate the user array to add our new extension to it) const extensions_ext = try allocator.alloc([*:0]const u8, extensions.len + 1); defer allocator.free(extensions_ext); std.mem.copy([*:0]const u8, extensions_ext[0..extensions.len], extensions); extensions_ext[extensions.len] = "VK_EXT_debug_report"; create_info.enabledExtensionCount = @intCast(u32, extensions_ext.len); create_info.ppEnabledExtensionNames = extensions_ext.ptr; // Create Vulkan Instance g_Instance = try vk.CreateInstance(create_info, g_Allocator); // Get the function pointer (required for any extensions) var vkCreateDebugReportCallbackEXT = @ptrCast(?@TypeOf(vk.vkCreateDebugReportCallbackEXT), vk.GetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT")).?; // Setup the debug report callback var debug_report_ci = vk.DebugReportCallbackCreateInfoEXT{ .flags = .{ .errorBit = true, .warning = true, .performanceWarning = true }, .pfnCallback = debug_report, .pUserData = null, }; var err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); if (@enumToInt(err) < 0) { return error.CreateDebugCallbackFailed; } } else { // Create Vulkan Instance without any debug feature g_Instance = try vk.CreateInstance(create_info, g_Allocator); } } // Select GPU { var gpu_count = try vk.EnumeratePhysicalDevicesCount(g_Instance); assert(gpu_count > 0); var gpus = try allocator.alloc(vk.PhysicalDevice, gpu_count); defer allocator.free(gpus); _ = try vk.EnumeratePhysicalDevices(g_Instance, gpus); // If a number >1 of GPUs got reported, you should find the best fit GPU for your purpose // e.g. VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU if available, or with the greatest memory available, etc. // for sake of simplicity we'll just take the first one, assuming it has a graphics queue family. g_PhysicalDevice = gpus[0]; } // Select graphics queue family { var count = vk.GetPhysicalDeviceQueueFamilyPropertiesCount(g_PhysicalDevice); var queues = try allocator.alloc(vk.QueueFamilyProperties, count); defer allocator.free(queues); _ = vk.GetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, queues); for (queues) |queue, i| { if (queue.queueFlags.graphics) { g_QueueFamily = @intCast(u32, i); break; } } assert(g_QueueFamily != ~@as(u32, 0)); } // Create Logical Device (with 1 queue) { var device_extensions = [_][*:0]const u8{"VK_KHR_swapchain"}; var queue_priority = [_]f32{1.0}; var queue_info = [_]vk.DeviceQueueCreateInfo{ vk.DeviceQueueCreateInfo{ .queueFamilyIndex = g_QueueFamily, .queueCount = 1, .pQueuePriorities = &queue_priority, }, }; var create_info = vk.DeviceCreateInfo{ .queueCreateInfoCount = @intCast(u32, queue_info.len), .pQueueCreateInfos = &queue_info, .enabledExtensionCount = @intCast(u32, device_extensions.len), .ppEnabledExtensionNames = &device_extensions, }; g_Device = try vk.CreateDevice(g_PhysicalDevice, create_info, g_Allocator); g_Queue = vk.GetDeviceQueue(g_Device, g_QueueFamily, 0); } // Create Descriptor Pool { var pool_sizes = [_]vk.DescriptorPoolSize{ vk.DescriptorPoolSize{ .inType = .SAMPLER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .COMBINED_IMAGE_SAMPLER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .SAMPLED_IMAGE, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .STORAGE_IMAGE, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .UNIFORM_TEXEL_BUFFER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .STORAGE_TEXEL_BUFFER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .UNIFORM_BUFFER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .STORAGE_BUFFER, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .UNIFORM_BUFFER_DYNAMIC, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .STORAGE_BUFFER_DYNAMIC, .descriptorCount = 1000 }, vk.DescriptorPoolSize{ .inType = .INPUT_ATTACHMENT, .descriptorCount = 1000 }, }; var pool_info = vk.DescriptorPoolCreateInfo{ .flags = .{ .freeDescriptorSet = true }, .maxSets = 1000 * @intCast(u32, pool_sizes.len), .poolSizeCount = @intCast(u32, pool_sizes.len), .pPoolSizes = &pool_sizes, }; g_DescriptorPool = try vk.CreateDescriptorPool(g_Device, pool_info, g_Allocator); } } // All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. // Your real engine/app may not use them. fn SetupVulkanWindow(wd: *impl_vulkan.Window, surface: vk.SurfaceKHR, width: u32, height: u32, allocator: *std.mem.Allocator) !void { wd.Surface = surface; wd.Allocator = allocator; var res = try vk.GetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface); if (res != vk.TRUE) { return error.NoWSISupport; } // Select Surface Format const requestSurfaceImageFormat = [_]vk.Format{ .B8G8R8A8_UNORM, .R8G8B8A8_UNORM, .B8G8R8_UNORM, .R8G8B8_UNORM }; const requestSurfaceColorSpace = vk.ColorSpaceKHR.SRGB_NONLINEAR; wd.SurfaceFormat = try impl_vulkan.SelectSurfaceFormat(g_PhysicalDevice, surface, &requestSurfaceImageFormat, requestSurfaceColorSpace, allocator); // Select Present Mode if (IMGUI_UNLIMITED_FRAME_RATE) { var present_modes = [_]vk.PresentModeKHR{ .MAILBOX, .IMMEDIATE, .FIFO }; wd.PresentMode = try impl_vulkan.SelectPresentMode(g_PhysicalDevice, surface, &present_modes, allocator); } else { var present_modes = [_]vk.PresentModeKHR{.FIFO}; wd.PresentMode = try impl_vulkan.SelectPresentMode(g_PhysicalDevice, surface, &present_modes, allocator); } // Create SwapChain, RenderPass, Framebuffer, etc. assert(g_MinImageCount >= 2); try impl_vulkan.CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } fn CleanupVulkan() void { vk.DestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); if (IMGUI_VULKAN_DEBUG_REPORT) { // Remove the debug report callback const vkDestroyDebugReportCallbackEXT = @ptrCast(?@TypeOf(vk.vkDestroyDebugReportCallbackEXT), vk.GetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT")); assert(vkDestroyDebugReportCallbackEXT != null); vkDestroyDebugReportCallbackEXT.?(g_Instance, g_DebugReport, g_Allocator); } vk.DestroyDevice(g_Device, g_Allocator); vk.DestroyInstance(g_Instance, g_Allocator); } fn CleanupVulkanWindow() !void { try impl_vulkan.DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } fn FrameRender(wd: *impl_vulkan.Window) !void { const image_acquired_semaphore = wd.FrameSemaphores[wd.SemaphoreIndex].ImageAcquiredSemaphore; const render_complete_semaphore = wd.FrameSemaphores[wd.SemaphoreIndex].RenderCompleteSemaphore; wd.FrameIndex = (try vk.AcquireNextImageKHR(g_Device, wd.Swapchain, ~@as(u64, 0), image_acquired_semaphore, .Null)).imageIndex; const fd = &wd.Frames[wd.FrameIndex]; { _ = try vk.WaitForFences(g_Device, arrayPtr(&fd.Fence), vk.TRUE, ~@as(u64, 0)); // wait indefinitely instead of periodically checking try vk.ResetFences(g_Device, arrayPtr(&fd.Fence)); } { try vk.ResetCommandPool(g_Device, fd.CommandPool, .{}); var info = vk.CommandBufferBeginInfo{ .flags = .{ .oneTimeSubmit = true }, }; try vk.BeginCommandBuffer(fd.CommandBuffer, info); } { var info = vk.RenderPassBeginInfo{ .renderPass = wd.RenderPass, .framebuffer = fd.Framebuffer, .renderArea = vk.Rect2D{ .offset = vk.Offset2D{ .x = 0, .y = 0 }, .extent = vk.Extent2D{ .width = wd.Width, .height = wd.Height }, }, .clearValueCount = 1, .pClearValues = @ptrCast([*]vk.ClearValue, &g_ClearColor), }; vk.CmdBeginRenderPass(fd.CommandBuffer, info, .INLINE); } // Record Imgui Draw Data and draw funcs into command buffer try impl_vulkan.RenderDrawData(imgui.GetDrawData(), fd.CommandBuffer); // Submit command buffer vk.CmdEndRenderPass(fd.CommandBuffer); { const wait_stage: vk.PipelineStageFlags align(4) = .{ .colorAttachmentOutput = true }; var info = vk.SubmitInfo{ .waitSemaphoreCount = 1, .pWaitSemaphores = arrayPtr(&image_acquired_semaphore), .pWaitDstStageMask = arrayPtr(&wait_stage), .commandBufferCount = 1, .pCommandBuffers = arrayPtr(&fd.CommandBuffer), .signalSemaphoreCount = 1, .pSignalSemaphores = arrayPtr(&render_complete_semaphore), }; try vk.EndCommandBuffer(fd.CommandBuffer); try vk.QueueSubmit(g_Queue, arrayPtr(&info), fd.Fence); } } fn FramePresent(wd: *impl_vulkan.Window) !void { const render_complete_semaphore = wd.FrameSemaphores[wd.SemaphoreIndex].RenderCompleteSemaphore; var info = vk.PresentInfoKHR{ .waitSemaphoreCount = 1, .pWaitSemaphores = arrayPtr(&render_complete_semaphore), .swapchainCount = 1, .pSwapchains = arrayPtr(&wd.Swapchain), .pImageIndices = arrayPtr(&wd.FrameIndex), }; _ = try vk.QueuePresentKHR(g_Queue, info); wd.SemaphoreIndex = (wd.SemaphoreIndex + 1) % wd.ImageCount; // Now we can use the next set of semaphores } fn glfw_error_callback(err: c_int, description: ?[*:0]const u8) callconv(.C) void { std.debug.warn("Glfw Error {}: {}\n", .{ err, std.mem.spanZ(description.?) }); } fn glfw_resize_callback(window: ?*glfw.GLFWwindow, w: c_int, h: c_int) callconv(.C) void { g_SwapChainRebuild = true; g_SwapChainResizeWidth = @intCast(u32, w); g_SwapChainResizeHeight = @intCast(u32, h); } pub fn main() !void { const allocator = std.heap.c_allocator; // Setup GLFW window _ = glfw.glfwSetErrorCallback(glfw_error_callback); if (glfw.glfwInit() == 0) return error.GlfwInitFailed; glfw.glfwWindowHint(glfw.GLFW_CLIENT_API, glfw.GLFW_NO_API); var window = glfw.glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Vulkan example", null, null).?; // Setup Vulkan if (glfw.glfwVulkanSupported() == 0) { return error.VulkanNotSupported; } var extensions_count: u32 = 0; var extensions = glfw.glfwGetRequiredInstanceExtensions(&extensions_count); try SetupVulkan(extensions[0..extensions_count], allocator); // Create Window Surface var surface: vk.SurfaceKHR = undefined; const err = glfw.glfwCreateWindowSurface(g_Instance, window, g_Allocator, &surface); if (@enumToInt(err) < 0) { return error.CouldntCreateSufrace; } // Create Framebuffers var w: c_int = 0; var h: c_int = 0; glfw.glfwGetFramebufferSize(window, &w, &h); _ = glfw.glfwSetFramebufferSizeCallback(window, glfw_resize_callback); const wd = &g_MainWindowData; try SetupVulkanWindow(wd, surface, @intCast(u32, w), @intCast(u32, h), allocator); // Setup Dear ImGui context imgui.CHECKVERSION(); _ = imgui.CreateContext(); var io = imgui.GetIO(); //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style imgui.StyleColorsDark(); //imgui.StyleColorsClassic(null); // Setup Platform/Renderer bindings var initResult = impl_glfw.InitForVulkan(window, true); assert(initResult); var init_info = impl_vulkan.InitInfo{ .Allocator = allocator, .Instance = g_Instance, .PhysicalDevice = g_PhysicalDevice, .Device = g_Device, .QueueFamily = g_QueueFamily, .Queue = g_Queue, .PipelineCache = g_PipelineCache, .DescriptorPool = g_DescriptorPool, .VkAllocator = g_Allocator, .MinImageCount = g_MinImageCount, .MSAASamples = .{}, .ImageCount = wd.ImageCount, }; try impl_vulkan.Init(&init_info, wd.RenderPass); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use imgui.PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts.?.AddFontDefault(); //io.Fonts.?.AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts.?.AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts.?.AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts.?.AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts.?.AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts.?.GetGlyphRangesJapanese()); //assert(font != NULL); // Upload Fonts if (true) { // Use any command queue const command_pool = wd.Frames[wd.FrameIndex].CommandPool; const command_buffer = wd.Frames[wd.FrameIndex].CommandBuffer; try vk.ResetCommandPool(g_Device, command_pool, .{}); const begin_info = vk.CommandBufferBeginInfo{ .flags = .{ .oneTimeSubmit = true }, }; try vk.BeginCommandBuffer(command_buffer, begin_info); try impl_vulkan.CreateFontsTexture(command_buffer); const end_info = vk.SubmitInfo{ .commandBufferCount = 1, .pCommandBuffers = arrayPtr(&command_buffer), }; try vk.EndCommandBuffer(command_buffer); try vk.QueueSubmit(g_Queue, arrayPtr(&end_info), .Null); try vk.DeviceWaitIdle(g_Device); impl_vulkan.DestroyFontUploadObjects(); } else { // Trick imgui into thinking we've built fonts var pixels: [*]u8 = undefined; var width: i32 = 0; var height: i32 = 0; var bpp: i32 = 0; io.Fonts.?.GetTexDataAsRGBA32(&pixels, &width, &height, &bpp); } // Our state var show_demo_window = true; var show_another_window = false; var slider_value: f32 = 0; var counter: i32 = 0; // Main loop while (glfw.glfwWindowShouldClose(window) == 0) { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfw.glfwPollEvents(); if (g_SwapChainRebuild) { g_SwapChainRebuild = false; try impl_vulkan.SetMinImageCount(g_MinImageCount); try impl_vulkan.CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } // Start the Dear ImGui frame impl_vulkan.NewFrame(); impl_glfw.NewFrame(); imgui.NewFrame(); // 1. Show the big demo window (Most of the sample code is in imgui.ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) imgui.ShowDemoWindowExt(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. { _ = imgui.Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. imgui.Text("This is some useful text."); // Display some text (you can use a format strings too) _ = imgui.Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state _ = imgui.Checkbox("Another Window", &show_another_window); _ = imgui.SliderFloat("float", &slider_value, 0.0, 1.0); // Edit 1 float using a slider from 0.0 to 1.0 _ = imgui.ColorEdit3("clear color", @ptrCast(*[3]f32, &g_ClearColor)); // Edit 3 floats representing a color if (imgui.Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter += 1; imgui.SameLine(); imgui.Text("counter = %d", counter); imgui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / imgui.GetIO().Framerate, imgui.GetIO().Framerate); imgui.End(); } // 3. Show another simple window. if (show_another_window) { _ = imgui.BeginExt("Another Window", &show_another_window, .{}); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) imgui.Text("Hello from another window!"); if (imgui.Button("Close Me")) show_another_window = false; imgui.End(); } // Rendering imgui.Render(); try FrameRender(wd); try FramePresent(wd); } // Cleanup try vk.DeviceWaitIdle(g_Device); impl_vulkan.Shutdown(); impl_glfw.Shutdown(); imgui.DestroyContext(); try CleanupVulkanWindow(); CleanupVulkan(); glfw.glfwDestroyWindow(window); glfw.glfwTerminate(); } /// Takes a pointer type like *T, *const T, *align(4)T, etc, /// returns the pointer type *[1]T, *const [1]T, *align(4) [1]T, etc. fn ArrayPtrType(comptime ptrType: type) type { comptime { // Check that the input is of type *T var info = @typeInfo(ptrType); assert(info == .Pointer); assert(info.Pointer.size == .One); assert(info.Pointer.sentinel == null); // Create the new value type, [1]T const arrayInfo = std.builtin.TypeInfo{ .Array = .{ .len = 1, .child = info.Pointer.child, .sentinel = @as(?info.Pointer.child, null), }, }; // Patch the type to be *[1]T, preserving other modifiers const singleArrayType = @Type(arrayInfo); info.Pointer.child = singleArrayType; // also need to change the type of the sentinel // we checked that this is null above so no work needs to be done here. info.Pointer.sentinel = @as(?singleArrayType, null); return @Type(info); } } fn arrayPtr(ptr: var) ArrayPtrType(@TypeOf(ptr)) { return @as(ArrayPtrType(@TypeOf(ptr)), ptr); }
examples/example_glfw_vulkan.zig
const std = @import("../std.zig"); const builtin = std.builtin; const assert = std.debug.assert; const maxInt = std.math.maxInt; const elf = std.elf; const vdso = @import("linux/vdso.zig"); const dl = @import("../dynamic_library.zig"); pub usingnamespace switch (builtin.arch) { .i386 => @import("linux/i386.zig"), .x86_64 => @import("linux/x86_64.zig"), .aarch64 => @import("linux/arm64.zig"), .arm => @import("linux/arm-eabi.zig"), .riscv64 => @import("linux/riscv64.zig"), .sparcv9 => @import("linux/sparc64.zig"), .mips, .mipsel => @import("linux/mips.zig"), .powerpc64, .powerpc64le => @import("linux/powerpc64.zig"), else => struct {}, }; pub usingnamespace @import("bits.zig"); pub const tls = @import("linux/tls.zig"); pub const BPF = @import("linux/bpf.zig"); pub usingnamespace @import("linux/io_uring.zig"); /// Set by startup code, used by `getauxval`. pub var elf_aux_maybe: ?[*]std.elf.Auxv = null; /// See `std.elf` for the constants. pub fn getauxval(index: usize) usize { const auxv = elf_aux_maybe orelse return 0; var i: usize = 0; while (auxv[i].a_type != std.elf.AT_NULL) : (i += 1) { if (auxv[i].a_type == index) return auxv[i].a_un.a_val; } return 0; } // Some architectures (and some syscalls) require 64bit parameters to be passed // in a even-aligned register pair. const require_aligned_register_pair = std.Target.current.cpu.arch.isMIPS() or std.Target.current.cpu.arch.isARM() or std.Target.current.cpu.arch.isThumb(); // Split a 64bit value into a {LSB,MSB} pair. fn splitValue64(val: u64) [2]u32 { switch (builtin.endian) { .Little => return [2]u32{ @truncate(u32, val), @truncate(u32, val >> 32), }, .Big => return [2]u32{ @truncate(u32, val >> 32), @truncate(u32, val), }, } } /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) u12 { const signed_r = @bitCast(isize, r); return if (signed_r > -4096 and signed_r < 0) @intCast(u12, -signed_r) else 0; } pub fn dup2(old: i32, new: i32) usize { if (@hasField(SYS, "dup2")) { return syscall2(.dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new))); } else { if (old == new) { if (std.debug.runtime_safety) { const rc = syscall2(.fcntl, @bitCast(usize, @as(isize, old)), F_GETFD); if (@bitCast(isize, rc) < 0) return rc; } return @intCast(usize, old); } else { return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0); } } } pub fn dup3(old: i32, new: i32, flags: u32) usize { return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags); } pub fn chdir(path: [*:0]const u8) usize { return syscall1(.chdir, @ptrToInt(path)); } pub fn fchdir(fd: fd_t) usize { return syscall1(.fchdir, @bitCast(usize, @as(isize, fd))); } pub fn chroot(path: [*:0]const u8) usize { return syscall1(.chroot, @ptrToInt(path)); } pub fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) usize { return syscall3(.execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); } pub fn fork() usize { if (comptime builtin.arch.isSPARC()) { return syscall_fork(); } else if (@hasField(SYS, "fork")) { return syscall0(.fork); } else { return syscall2(.clone, SIGCHLD, 0); } } /// This must be inline, and inline call the syscall function, because if the /// child does a return it will clobber the parent's stack. /// It is advised to avoid this function and use clone instead, because /// the compiler is not aware of how vfork affects control flow and you may /// see different results in optimized builds. pub inline fn vfork() usize { return @call(.{ .modifier = .always_inline }, syscall0, .{.vfork}); } pub fn futimens(fd: i32, times: *const [2]timespec) usize { return utimensat(fd, null, times, 0); } pub fn utimensat(dirfd: i32, path: ?[*:0]const u8, times: *const [2]timespec, flags: u32) usize { return syscall4(.utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags); } pub fn fallocate(fd: i32, mode: i32, offset: u64, length: u64) usize { if (@sizeOf(usize) == 4) { const offset_halves = splitValue64(offset); const length_halves = splitValue64(length); return syscall6( .fallocate, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, mode)), offset_halves[0], offset_halves[1], length_halves[0], length_halves[1], ); } else { return syscall4( .fallocate, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, mode)), offset, length, ); } } pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize { return syscall4(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout)); } pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize { return syscall3(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val)); } pub fn getcwd(buf: [*]u8, size: usize) usize { return syscall2(.getcwd, @ptrToInt(buf), size); } pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize { return syscall3( .getdents, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), std.math.min(len, maxInt(c_int)), ); } pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize { return syscall3( .getdents64, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), std.math.min(len, maxInt(c_int)), ); } pub fn inotify_init1(flags: u32) usize { return syscall1(.inotify_init1, flags); } pub fn inotify_add_watch(fd: i32, pathname: [*:0]const u8, mask: u32) usize { return syscall3(.inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask); } pub fn inotify_rm_watch(fd: i32, wd: i32) usize { return syscall2(.inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd))); } pub fn readlink(noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { if (@hasField(SYS, "readlink")) { return syscall3(.readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } else { return syscall4(.readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } } pub fn readlinkat(dirfd: i32, noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { return syscall4(.readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } pub fn mkdir(path: [*:0]const u8, mode: u32) usize { if (@hasField(SYS, "mkdir")) { return syscall2(.mkdir, @ptrToInt(path), mode); } else { return syscall3(.mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode); } } pub fn mkdirat(dirfd: i32, path: [*:0]const u8, mode: u32) usize { return syscall3(.mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode); } pub fn mount(special: [*:0]const u8, dir: [*:0]const u8, fstype: [*:0]const u8, flags: u32, data: usize) usize { return syscall5(.mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); } pub fn umount(special: [*:0]const u8) usize { return syscall2(.umount2, @ptrToInt(special), 0); } pub fn umount2(special: [*:0]const u8, flags: u32) usize { return syscall2(.umount2, @ptrToInt(special), flags); } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: u64) usize { if (@hasField(SYS, "mmap2")) { // Make sure the offset is also specified in multiples of page size if ((offset & (MMAP2_UNIT - 1)) != 0) return @bitCast(usize, @as(isize, -EINVAL)); return syscall6( .mmap2, @ptrToInt(address), length, prot, flags, @bitCast(usize, @as(isize, fd)), @truncate(usize, offset / MMAP2_UNIT), ); } else { return syscall6( .mmap, @ptrToInt(address), length, prot, flags, @bitCast(usize, @as(isize, fd)), offset, ); } } pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize { return syscall3(.mprotect, @ptrToInt(address), length, protection); } pub fn munmap(address: [*]const u8, length: usize) usize { return syscall2(.munmap, @ptrToInt(address), length); } pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize { if (@hasField(SYS, "poll")) { return syscall3(.poll, @ptrToInt(fds), n, @bitCast(u32, timeout)); } else { return syscall5( .ppoll, @ptrToInt(fds), n, @ptrToInt(if (timeout >= 0) &timespec{ .tv_sec = @divTrunc(timeout, 1000), .tv_nsec = @rem(timeout, 1000) * 1000000, } else null), 0, NSIG / 8, ); } } pub fn ppoll(fds: [*]pollfd, n: nfds_t, timeout: ?*timespec, sigmask: ?*const sigset_t) usize { return syscall5(.ppoll, @ptrToInt(fds), n, @ptrToInt(timeout), @ptrToInt(sigmask), NSIG / 8); } pub fn read(fd: i32, buf: [*]u8, count: usize) usize { return syscall3(.read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); } pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize { const offset_halves = splitValue64(offset); return syscall5( .preadv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, offset_halves[0], offset_halves[1], ); } pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize { const offset_halves = splitValue64(offset); return syscall6( .preadv2, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, offset_halves[0], offset_halves[1], flags, ); } pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize { return syscall3(.readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); } pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize { return syscall3(.writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); } pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize { const offset_halves = splitValue64(offset); return syscall5( .pwritev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, offset_halves[0], offset_halves[1], ); } pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize { const offset_halves = splitValue64(offset); return syscall6( .pwritev2, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, offset_halves[0], offset_halves[1], flags, ); } pub fn rmdir(path: [*:0]const u8) usize { if (@hasField(SYS, "rmdir")) { return syscall1(.rmdir, @ptrToInt(path)); } else { return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR); } } pub fn symlink(existing: [*:0]const u8, new: [*:0]const u8) usize { if (@hasField(SYS, "symlink")) { return syscall2(.symlink, @ptrToInt(existing), @ptrToInt(new)); } else { return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); } } pub fn symlinkat(existing: [*:0]const u8, newfd: i32, newpath: [*:0]const u8) usize { return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath)); } pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize { if (@hasField(SYS, "pread64")) { const offset_halves = splitValue64(offset); if (require_aligned_register_pair) { return syscall6( .pread64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, 0, offset_halves[0], offset_halves[1], ); } else { return syscall5( .pread64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset_halves[0], offset_halves[1], ); } } else { return syscall4( .pread, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset, ); } } pub fn access(path: [*:0]const u8, mode: u32) usize { if (@hasField(SYS, "access")) { return syscall2(.access, @ptrToInt(path), mode); } else { return syscall4(.faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0); } } pub fn faccessat(dirfd: i32, path: [*:0]const u8, mode: u32, flags: u32) usize { return syscall4(.faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags); } pub fn pipe(fd: *[2]i32) usize { if (comptime (builtin.arch.isMIPS() or builtin.arch.isSPARC())) { return syscall_pipe(fd); } else if (@hasField(SYS, "pipe")) { return syscall1(.pipe, @ptrToInt(fd)); } else { return syscall2(.pipe2, @ptrToInt(fd), 0); } } pub fn pipe2(fd: *[2]i32, flags: u32) usize { return syscall2(.pipe2, @ptrToInt(fd), flags); } pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { return syscall3(.write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); } pub fn ftruncate(fd: i32, length: u64) usize { if (@hasField(SYS, "ftruncate64")) { const length_halves = splitValue64(length); if (require_aligned_register_pair) { return syscall4( .ftruncate64, @bitCast(usize, @as(isize, fd)), 0, length_halves[0], length_halves[1], ); } else { return syscall3( .ftruncate64, @bitCast(usize, @as(isize, fd)), length_halves[0], length_halves[1], ); } } else { return syscall2( .ftruncate, @bitCast(usize, @as(isize, fd)), @truncate(usize, length), ); } } pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: u64) usize { if (@hasField(SYS, "pwrite64")) { const offset_halves = splitValue64(offset); if (require_aligned_register_pair) { return syscall6( .pwrite64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, 0, offset_halves[0], offset_halves[1], ); } else { return syscall5( .pwrite64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset_halves[0], offset_halves[1], ); } } else { return syscall4( .pwrite, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset, ); } } pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize { if (@hasField(SYS, "rename")) { return syscall2(.rename, @ptrToInt(old), @ptrToInt(new)); } else if (@hasField(SYS, "renameat")) { return syscall4(.renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); } else { return syscall5(.renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0); } } pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize { if (@hasField(SYS, "renameat")) { return syscall4( .renameat, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath), ); } else { return syscall5( .renameat2, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath), 0, ); } } pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]const u8, flags: u32) usize { return syscall5( .renameat2, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath), flags, ); } pub fn open(path: [*:0]const u8, flags: u32, perm: mode_t) usize { if (@hasField(SYS, "open")) { return syscall3(.open, @ptrToInt(path), flags, perm); } else { return syscall4( .openat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), flags, perm, ); } } pub fn create(path: [*:0]const u8, perm: mode_t) usize { return syscall2(.creat, @ptrToInt(path), perm); } pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, mode: mode_t) usize { // dirfd could be negative, for example AT_FDCWD is -100 return syscall4(.openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize { return syscall5(.clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); } /// See also `clone` (from the arch-specific include) pub fn clone2(flags: u32, child_stack_ptr: usize) usize { return syscall2(.clone, flags, child_stack_ptr); } pub fn close(fd: i32) usize { return syscall1(.close, @bitCast(usize, @as(isize, fd))); } /// Can only be called on 32 bit systems. For 64 bit see `lseek`. pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize { // NOTE: The offset parameter splitting is independent from the target // endianness. return syscall5( ._llseek, @bitCast(usize, @as(isize, fd)), @truncate(usize, offset >> 32), @truncate(usize, offset), @ptrToInt(result), whence, ); } /// Can only be called on 64 bit systems. For 32 bit see `llseek`. pub fn lseek(fd: i32, offset: i64, whence: usize) usize { return syscall3(.lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence); } pub fn exit(status: i32) noreturn { _ = syscall1(.exit, @bitCast(usize, @as(isize, status))); unreachable; } pub fn exit_group(status: i32) noreturn { _ = syscall1(.exit_group, @bitCast(usize, @as(isize, status))); unreachable; } pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize { return syscall3(.getrandom, @ptrToInt(buf), count, flags); } pub fn kill(pid: pid_t, sig: i32) usize { return syscall2(.kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig))); } pub fn tkill(tid: pid_t, sig: i32) usize { return syscall2(.tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); } pub fn tgkill(tgid: pid_t, tid: pid_t, sig: i32) usize { return syscall2(.tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); } pub fn unlink(path: [*:0]const u8) usize { if (@hasField(SYS, "unlink")) { return syscall1(.unlink, @ptrToInt(path)); } else { return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0); } } pub fn unlinkat(dirfd: i32, path: [*:0]const u8, flags: u32) usize { return syscall3(.unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags); } pub fn waitpid(pid: pid_t, status: *u32, flags: u32) usize { return syscall4(.wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0); } pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) usize { return syscall3(.fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg); } pub fn flock(fd: fd_t, operation: i32) usize { return syscall2(.flock, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, operation))); } var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime); // We must follow the C calling convention when we call into the VDSO const vdso_clock_gettime_ty = fn (i32, *timespec) callconv(.C) usize; pub fn clock_gettime(clk_id: i32, tp: *timespec) usize { if (@hasDecl(@This(), "VDSO_CGT_SYM")) { const ptr = @atomicLoad(?*const c_void, &vdso_clock_gettime, .Unordered); if (ptr) |fn_ptr| { const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr); const rc = f(clk_id, tp); switch (rc) { 0, @bitCast(usize, @as(isize, -EINVAL)) => return rc, else => {}, } } } return syscall2(.clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize { const ptr = @intToPtr(?*const c_void, vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM)); // Note that we may not have a VDSO at all, update the stub address anyway // so that clock_gettime will fall back on the good old (and slow) syscall @atomicStore(?*const c_void, &vdso_clock_gettime, ptr, .Monotonic); // Call into the VDSO if available if (ptr) |fn_ptr| { const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr); return f(clk, ts); } return @bitCast(usize, @as(isize, -ENOSYS)); } pub fn clock_getres(clk_id: i32, tp: *timespec) usize { return syscall2(.clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } pub fn clock_settime(clk_id: i32, tp: *const timespec) usize { return syscall2(.clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } pub fn gettimeofday(tv: *timeval, tz: *timezone) usize { return syscall2(.gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize { return syscall2(.settimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return syscall2(.nanosleep, @ptrToInt(req), @ptrToInt(rem)); } pub fn setuid(uid: uid_t) usize { if (@hasField(SYS, "setuid32")) { return syscall1(.setuid32, uid); } else { return syscall1(.setuid, uid); } } pub fn setgid(gid: gid_t) usize { if (@hasField(SYS, "setgid32")) { return syscall1(.setgid32, gid); } else { return syscall1(.setgid, gid); } } pub fn setreuid(ruid: uid_t, euid: uid_t) usize { if (@hasField(SYS, "setreuid32")) { return syscall2(.setreuid32, ruid, euid); } else { return syscall2(.setreuid, ruid, euid); } } pub fn setregid(rgid: gid_t, egid: gid_t) usize { if (@hasField(SYS, "setregid32")) { return syscall2(.setregid32, rgid, egid); } else { return syscall2(.setregid, rgid, egid); } } pub fn getuid() uid_t { if (@hasField(SYS, "getuid32")) { return @as(uid_t, syscall0(.getuid32)); } else { return @as(uid_t, syscall0(.getuid)); } } pub fn getgid() gid_t { if (@hasField(SYS, "getgid32")) { return @as(gid_t, syscall0(.getgid32)); } else { return @as(gid_t, syscall0(.getgid)); } } pub fn geteuid() uid_t { if (@hasField(SYS, "geteuid32")) { return @as(uid_t, syscall0(.geteuid32)); } else { return @as(uid_t, syscall0(.geteuid)); } } pub fn getegid() gid_t { if (@hasField(SYS, "getegid32")) { return @as(gid_t, syscall0(.getegid32)); } else { return @as(gid_t, syscall0(.getegid)); } } pub fn seteuid(euid: uid_t) usize { // We use setresuid here instead of setreuid to ensure that the saved uid // is not changed. This is what musl and recent glibc versions do as well. // // The setresuid(2) man page says that if -1 is passed the corresponding // id will not be changed. Since uid_t is unsigned, this wraps around to the // max value in C. comptime assert(@typeInfo(uid_t) == .Int and @typeInfo(uid_t).Int.signedness == .unsigned); return setresuid(std.math.maxInt(uid_t), euid, std.math.maxInt(uid_t)); } pub fn setegid(egid: gid_t) usize { // We use setresgid here instead of setregid to ensure that the saved uid // is not changed. This is what musl and recent glibc versions do as well. // // The setresgid(2) man page says that if -1 is passed the corresponding // id will not be changed. Since gid_t is unsigned, this wraps around to the // max value in C. comptime assert(@typeInfo(uid_t) == .Int and @typeInfo(uid_t).Int.signedness == .unsigned); return setresgid(std.math.maxInt(gid_t), egid, std.math.maxInt(gid_t)); } pub fn getresuid(ruid: *uid_t, euid: *uid_t, suid: *uid_t) usize { if (@hasField(SYS, "getresuid32")) { return syscall3(.getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } else { return syscall3(.getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } } pub fn getresgid(rgid: *gid_t, egid: *gid_t, sgid: *gid_t) usize { if (@hasField(SYS, "getresgid32")) { return syscall3(.getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } else { return syscall3(.getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } } pub fn setresuid(ruid: uid_t, euid: uid_t, suid: uid_t) usize { if (@hasField(SYS, "setresuid32")) { return syscall3(.setresuid32, ruid, euid, suid); } else { return syscall3(.setresuid, ruid, euid, suid); } } pub fn setresgid(rgid: gid_t, egid: gid_t, sgid: gid_t) usize { if (@hasField(SYS, "setresgid32")) { return syscall3(.setresgid32, rgid, egid, sgid); } else { return syscall3(.setresgid, rgid, egid, sgid); } } pub fn getgroups(size: usize, list: *gid_t) usize { if (@hasField(SYS, "getgroups32")) { return syscall2(.getgroups32, size, @ptrToInt(list)); } else { return syscall2(.getgroups, size, @ptrToInt(list)); } } pub fn setgroups(size: usize, list: *const gid_t) usize { if (@hasField(SYS, "setgroups32")) { return syscall2(.setgroups32, size, @ptrToInt(list)); } else { return syscall2(.setgroups, size, @ptrToInt(list)); } } pub fn getpid() pid_t { return @bitCast(pid_t, @truncate(u32, syscall0(.getpid))); } pub fn gettid() pid_t { return @bitCast(pid_t, @truncate(u32, syscall0(.gettid))); } pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) usize { return syscall4(.rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); } pub fn sigaction(sig: u6, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) usize { assert(sig >= 1); assert(sig != SIGKILL); assert(sig != SIGSTOP); var ksa: k_sigaction = undefined; var oldksa: k_sigaction = undefined; const mask_size = @sizeOf(@TypeOf(ksa.mask)); if (act) |new| { const restorer_fn = if ((new.flags & SA_SIGINFO) != 0) restore_rt else restore; ksa = k_sigaction{ .handler = new.handler.handler, .flags = new.flags | SA_RESTORER, .mask = undefined, .restorer = @ptrCast(fn () callconv(.C) void, restorer_fn), }; @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &new.mask), mask_size); } const ksa_arg = if (act != null) @ptrToInt(&ksa) else 0; const oldksa_arg = if (oact != null) @ptrToInt(&oldksa) else 0; const result = switch (builtin.arch) { // The sparc version of rt_sigaction needs the restorer function to be passed as an argument too. .sparc, .sparcv9 => syscall5(.rt_sigaction, sig, ksa_arg, oldksa_arg, @ptrToInt(ksa.restorer), mask_size), else => syscall4(.rt_sigaction, sig, ksa_arg, oldksa_arg, mask_size), }; if (getErrno(result) != 0) return result; if (oact) |old| { old.handler.handler = oldksa.handler; old.flags = @truncate(c_uint, oldksa.flags); @memcpy(@ptrCast([*]u8, &old.mask), @ptrCast([*]const u8, &oldksa.mask), mask_size); } return 0; } const usize_bits = @typeInfo(usize).Int.bits; pub fn sigaddset(set: *sigset_t, sig: u6) void { const s = sig - 1; // shift in musl: s&8*sizeof *set->__bits-1 const shift = @intCast(u5, s & (usize_bits - 1)); const val = @intCast(u32, 1) << shift; (set.*)[@intCast(usize, s) / usize_bits] |= val; } pub fn sigismember(set: *const sigset_t, sig: u6) bool { const s = sig - 1; return ((set.*)[@intCast(usize, s) / usize_bits] & (@intCast(usize, 1) << (s & (usize_bits - 1)))) != 0; } pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) }); } return syscall3(.getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); } pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) }); } return syscall3(.getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); } pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_socket, &[3]usize{ domain, socket_type, protocol }); } return syscall3(.socket, domain, socket_type, protocol); } pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) }); } return syscall5(.setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen)); } pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) }); } return syscall5(.getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags }); } return syscall3(.sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); } pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize { if (@typeInfo(usize).Int.bits > @typeInfo(@TypeOf(mmsghdr(undefined).msg_len)).Int.bits) { // workaround kernel brokenness: // if adding up all iov_len overflows a i32 then split into multiple calls // see https://www.openwall.com/lists/musl/2014/06/07/5 const kvlen = if (vlen > IOV_MAX) IOV_MAX else vlen; // matches kernel var next_unsent: usize = 0; for (msgvec[0..kvlen]) |*msg, i| { var size: i32 = 0; const msg_iovlen = @intCast(usize, msg.msg_hdr.msg_iovlen); // kernel side this is treated as unsigned for (msg.msg_hdr.msg_iov[0..msg_iovlen]) |iov, j| { if (iov.iov_len > std.math.maxInt(i32) or @addWithOverflow(i32, size, @intCast(i32, iov.iov_len), &size)) { // batch-send all messages up to the current message if (next_unsent < i) { const batch_size = i - next_unsent; const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); if (getErrno(r) != 0) return next_unsent; if (r < batch_size) return next_unsent + r; } // send current message as own packet const r = sendmsg(fd, &msg.msg_hdr, flags); if (getErrno(r) != 0) return r; // Linux limits the total bytes sent by sendmsg to INT_MAX, so this cast is safe. msg.msg_len = @intCast(u32, r); next_unsent = i + 1; break; } } } if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR) const batch_size = kvlen - next_unsent; const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); if (getErrno(r) != 0) return r; return next_unsent + r; } return kvlen; } return syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags); } pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len }); } return syscall3(.connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len); } pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags }); } return syscall3(.recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); } pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) }); } return syscall6(.recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } pub fn shutdown(fd: i32, how: i32) usize { if (builtin.arch == .i386) { return socketcall(SC_shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) }); } return syscall2(.shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how))); } pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) }); } return syscall3(.bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len)); } pub fn listen(fd: i32, backlog: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog }); } return syscall2(.listen, @bitCast(usize, @as(isize, fd)), backlog); } pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) }); } return syscall6(.sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen)); } pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize { if (@hasField(SYS, "sendfile64")) { return syscall4( .sendfile64, @bitCast(usize, @as(isize, outfd)), @bitCast(usize, @as(isize, infd)), @ptrToInt(offset), count, ); } else { return syscall4( .sendfile, @bitCast(usize, @as(isize, outfd)), @bitCast(usize, @as(isize, infd)), @ptrToInt(offset), count, ); } } pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize { if (builtin.arch == .i386) { return socketcall(SC_socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]) }); } return syscall4(.socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0])); } pub fn accept(fd: i32, noalias addr: ?*sockaddr, noalias len: ?*socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_accept, &[4]usize{ fd, addr, len, 0 }); } return accept4(fd, addr, len, 0); } pub fn accept4(fd: i32, noalias addr: ?*sockaddr, noalias len: ?*socklen_t, flags: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags }); } return syscall4(.accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags); } pub fn fstat(fd: i32, stat_buf: *kernel_stat) usize { if (@hasField(SYS, "fstat64")) { return syscall2(.fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); } else { return syscall2(.fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); } } pub fn stat(pathname: [*:0]const u8, statbuf: *kernel_stat) usize { if (@hasField(SYS, "stat64")) { return syscall2(.stat64, @ptrToInt(pathname), @ptrToInt(statbuf)); } else { return syscall2(.stat, @ptrToInt(pathname), @ptrToInt(statbuf)); } } pub fn lstat(pathname: [*:0]const u8, statbuf: *kernel_stat) usize { if (@hasField(SYS, "lstat64")) { return syscall2(.lstat64, @ptrToInt(pathname), @ptrToInt(statbuf)); } else { return syscall2(.lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); } } pub fn fstatat(dirfd: i32, path: [*:0]const u8, stat_buf: *kernel_stat, flags: u32) usize { if (@hasField(SYS, "fstatat64")) { return syscall4(.fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); } else if (@hasField(SYS, "newfstatat")) { return syscall4(.newfstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); } else { return syscall4(.fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); } } pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize { if (@hasField(SYS, "statx")) { return syscall5( .statx, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mask, @ptrToInt(statx_buf), ); } return @bitCast(usize, @as(isize, -ENOSYS)); } pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize { return syscall3(.listxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn llistxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize { return syscall3(.llistxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize { return syscall3(.flistxattr, fd, @ptrToInt(list), size); } pub fn getxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize { return syscall4(.getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn lgetxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize { return syscall4(.lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn fgetxattr(fd: usize, name: [*:0]const u8, value: [*]u8, size: usize) usize { return syscall4(.lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(.setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn lsetxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(.lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn fsetxattr(fd: usize, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(.fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn removexattr(path: [*:0]const u8, name: [*:0]const u8) usize { return syscall2(.removexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn lremovexattr(path: [*:0]const u8, name: [*:0]const u8) usize { return syscall2(.lremovexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn fremovexattr(fd: usize, name: [*:0]const u8) usize { return syscall2(.fremovexattr, fd, @ptrToInt(name)); } pub fn sched_yield() usize { return syscall0(.sched_yield); } pub fn sched_getaffinity(pid: pid_t, size: usize, set: *cpu_set_t) usize { const rc = syscall3(.sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set)); if (@bitCast(isize, rc) < 0) return rc; if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc); return 0; } pub fn epoll_create() usize { return epoll_create1(0); } pub fn epoll_create1(flags: usize) usize { return syscall1(.epoll_create1, flags); } pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize { return syscall4(.epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev)); } pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize { return epoll_pwait(epoll_fd, events, maxevents, timeout, null); } pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*const sigset_t) usize { return syscall6( .epoll_pwait, @bitCast(usize, @as(isize, epoll_fd)), @ptrToInt(events), @intCast(usize, maxevents), @bitCast(usize, @as(isize, timeout)), @ptrToInt(sigmask), @sizeOf(sigset_t), ); } pub fn eventfd(count: u32, flags: u32) usize { return syscall2(.eventfd2, count, flags); } pub fn timerfd_create(clockid: i32, flags: u32) usize { return syscall2(.timerfd_create, @bitCast(usize, @as(isize, clockid)), flags); } pub const itimerspec = extern struct { it_interval: timespec, it_value: timespec, }; pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize { return syscall2(.timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value)); } pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize { return syscall4(.timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value)); } pub fn unshare(flags: usize) usize { return syscall1(.unshare, flags); } pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize { return syscall2(.capget, @ptrToInt(hdrp), @ptrToInt(datap)); } pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize { return syscall2(.capset, @ptrToInt(hdrp), @ptrToInt(datap)); } pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize { return syscall2(.sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss)); } pub fn uname(uts: *utsname) usize { return syscall1(.uname, @ptrToInt(uts)); } pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize { return syscall2(.io_uring_setup, entries, @ptrToInt(p)); } pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize { return syscall6(.io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8); } pub fn io_uring_register(fd: i32, opcode: IORING_REGISTER, arg: ?*const c_void, nr_args: u32) usize { return syscall4(.io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args); } pub fn memfd_create(name: [*:0]const u8, flags: u32) usize { return syscall2(.memfd_create, @ptrToInt(name), flags); } pub fn getrusage(who: i32, usage: *rusage) usize { return syscall2(.getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage)); } pub fn tcgetattr(fd: fd_t, termios_p: *termios) usize { return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCGETS, @ptrToInt(termios_p)); } pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usize { return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCSETS + @enumToInt(optional_action), @ptrToInt(termios_p)); } pub fn ioctl(fd: fd_t, request: u32, arg: usize) usize { return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), request, arg); } pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) usize { return syscall4(.signalfd4, @bitCast(usize, @as(isize, fd)), @ptrToInt(mask), NSIG / 8, flags); } pub fn copy_file_range(fd_in: fd_t, off_in: ?*i64, fd_out: fd_t, off_out: ?*i64, len: usize, flags: u32) usize { return syscall6( .copy_file_range, @bitCast(usize, @as(isize, fd_in)), @ptrToInt(off_in), @bitCast(usize, @as(isize, fd_out)), @ptrToInt(off_out), len, flags, ); } pub fn bpf(cmd: BPF.Cmd, attr: *BPF.Attr, size: u32) usize { return syscall3(.bpf, @enumToInt(cmd), @ptrToInt(attr), size); } pub fn sync() void { _ = syscall0(.sync); } pub fn syncfs(fd: fd_t) usize { return syscall1(.syncfs, @bitCast(usize, @as(isize, fd))); } pub fn fsync(fd: fd_t) usize { return syscall1(.fsync, @bitCast(usize, @as(isize, fd))); } pub fn fdatasync(fd: fd_t) usize { return syscall1(.fdatasync, @bitCast(usize, @as(isize, fd))); } pub fn prctl(option: i32, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return syscall5(.prctl, @bitCast(usize, @as(isize, option)), arg2, arg3, arg4, arg5); } pub fn getrlimit(resource: rlimit_resource, rlim: *rlimit) usize { // use prlimit64 to have 64 bit limits on 32 bit platforms return prlimit(0, resource, null, rlim); } pub fn setrlimit(resource: rlimit_resource, rlim: *const rlimit) usize { // use prlimit64 to have 64 bit limits on 32 bit platforms return prlimit(0, resource, rlim, null); } pub fn prlimit(pid: pid_t, resource: rlimit_resource, new_limit: ?*const rlimit, old_limit: ?*rlimit) usize { return syscall4( .prlimit64, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, @enumToInt(resource))), @ptrToInt(new_limit), @ptrToInt(old_limit), ); } pub fn madvise(address: [*]u8, len: usize, advice: u32) usize { return syscall3(.madvise, @ptrToInt(address), len, advice); } test "" { if (builtin.os.tag == .linux) { _ = @import("linux/test.zig"); } }
lib/std/os/linux.zig
const builtin = @import("builtin"); const std = @import("std.zig"); const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const warn = std.debug.warn; const coff = std.coff; const fs = std.fs; const File = std.fs.File; const ArrayList = std.ArrayList; // Note: most of this is based on information gathered from LLVM source code, // documentation and/or contributors. // https://llvm.org/docs/PDB/DbiStream.html#stream-header pub const DbiStreamHeader = packed struct { VersionSignature: i32, VersionHeader: u32, Age: u32, GlobalStreamIndex: u16, BuildNumber: u16, PublicStreamIndex: u16, PdbDllVersion: u16, SymRecordStream: u16, PdbDllRbld: u16, ModInfoSize: u32, SectionContributionSize: u32, SectionMapSize: u32, SourceInfoSize: i32, TypeServerSize: i32, MFCTypeServerIndex: u32, OptionalDbgHeaderSize: i32, ECSubstreamSize: i32, Flags: u16, Machine: u16, Padding: u32, }; pub const SectionContribEntry = packed struct { /// COFF Section index, 1-based Section: u16, Padding1: [2]u8, Offset: u32, Size: u32, Characteristics: u32, ModuleIndex: u16, Padding2: [2]u8, DataCrc: u32, RelocCrc: u32, }; pub const ModInfo = packed struct { Unused1: u32, SectionContr: SectionContribEntry, Flags: u16, ModuleSymStream: u16, SymByteSize: u32, C11ByteSize: u32, C13ByteSize: u32, SourceFileCount: u16, Padding: [2]u8, Unused2: u32, SourceFileNameIndex: u32, PdbFilePathNameIndex: u32, // These fields are variable length //ModuleName: char[], //ObjFileName: char[], }; pub const SectionMapHeader = packed struct { /// Number of segment descriptors Count: u16, /// Number of logical segment descriptors LogCount: u16, }; pub const SectionMapEntry = packed struct { /// See the SectionMapEntryFlags enum below. Flags: u16, /// Logical overlay number Ovl: u16, /// Group index into descriptor array. Group: u16, Frame: u16, /// Byte index of segment / group name in string table, or 0xFFFF. SectionName: u16, /// Byte index of class in string table, or 0xFFFF. ClassName: u16, /// Byte offset of the logical segment within physical segment. If group is set in flags, this is the offset of the group. Offset: u32, /// Byte count of the segment or group. SectionLength: u32, }; pub const StreamType = enum(u16) { Pdb = 1, Tpi = 2, Dbi = 3, Ipi = 4, }; /// Duplicate copy of SymbolRecordKind, but using the official CV names. Useful /// for reference purposes and when dealing with unknown record types. pub const SymbolKind = packed enum(u16) { S_COMPILE = 1, S_REGISTER_16t = 2, S_CONSTANT_16t = 3, S_UDT_16t = 4, S_SSEARCH = 5, S_SKIP = 7, S_CVRESERVE = 8, S_OBJNAME_ST = 9, S_ENDARG = 10, S_COBOLUDT_16t = 11, S_MANYREG_16t = 12, S_RETURN = 13, S_ENTRYTHIS = 14, S_BPREL16 = 256, S_LDATA16 = 257, S_GDATA16 = 258, S_PUB16 = 259, S_LPROC16 = 260, S_GPROC16 = 261, S_THUNK16 = 262, S_BLOCK16 = 263, S_WITH16 = 264, S_LABEL16 = 265, S_CEXMODEL16 = 266, S_VFTABLE16 = 267, S_REGREL16 = 268, S_BPREL32_16t = 512, S_LDATA32_16t = 513, S_GDATA32_16t = 514, S_PUB32_16t = 515, S_LPROC32_16t = 516, S_GPROC32_16t = 517, S_THUNK32_ST = 518, S_BLOCK32_ST = 519, S_WITH32_ST = 520, S_LABEL32_ST = 521, S_CEXMODEL32 = 522, S_VFTABLE32_16t = 523, S_REGREL32_16t = 524, S_LTHREAD32_16t = 525, S_GTHREAD32_16t = 526, S_SLINK32 = 527, S_LPROCMIPS_16t = 768, S_GPROCMIPS_16t = 769, S_PROCREF_ST = 1024, S_DATAREF_ST = 1025, S_ALIGN = 1026, S_LPROCREF_ST = 1027, S_OEM = 1028, S_TI16_MAX = 4096, S_REGISTER_ST = 4097, S_CONSTANT_ST = 4098, S_UDT_ST = 4099, S_COBOLUDT_ST = 4100, S_MANYREG_ST = 4101, S_BPREL32_ST = 4102, S_LDATA32_ST = 4103, S_GDATA32_ST = 4104, S_PUB32_ST = 4105, S_LPROC32_ST = 4106, S_GPROC32_ST = 4107, S_VFTABLE32 = 4108, S_REGREL32_ST = 4109, S_LTHREAD32_ST = 4110, S_GTHREAD32_ST = 4111, S_LPROCMIPS_ST = 4112, S_GPROCMIPS_ST = 4113, S_COMPILE2_ST = 4115, S_MANYREG2_ST = 4116, S_LPROCIA64_ST = 4117, S_GPROCIA64_ST = 4118, S_LOCALSLOT_ST = 4119, S_PARAMSLOT_ST = 4120, S_ANNOTATION = 4121, S_GMANPROC_ST = 4122, S_LMANPROC_ST = 4123, S_RESERVED1 = 4124, S_RESERVED2 = 4125, S_RESERVED3 = 4126, S_RESERVED4 = 4127, S_LMANDATA_ST = 4128, S_GMANDATA_ST = 4129, S_MANFRAMEREL_ST = 4130, S_MANREGISTER_ST = 4131, S_MANSLOT_ST = 4132, S_MANMANYREG_ST = 4133, S_MANREGREL_ST = 4134, S_MANMANYREG2_ST = 4135, S_MANTYPREF = 4136, S_UNAMESPACE_ST = 4137, S_ST_MAX = 4352, S_WITH32 = 4356, S_MANYREG = 4362, S_LPROCMIPS = 4372, S_GPROCMIPS = 4373, S_MANYREG2 = 4375, S_LPROCIA64 = 4376, S_GPROCIA64 = 4377, S_LOCALSLOT = 4378, S_PARAMSLOT = 4379, S_MANFRAMEREL = 4382, S_MANREGISTER = 4383, S_MANSLOT = 4384, S_MANMANYREG = 4385, S_MANREGREL = 4386, S_MANMANYREG2 = 4387, S_UNAMESPACE = 4388, S_DATAREF = 4390, S_ANNOTATIONREF = 4392, S_TOKENREF = 4393, S_GMANPROC = 4394, S_LMANPROC = 4395, S_ATTR_FRAMEREL = 4398, S_ATTR_REGISTER = 4399, S_ATTR_REGREL = 4400, S_ATTR_MANYREG = 4401, S_SEPCODE = 4402, S_LOCAL_2005 = 4403, S_DEFRANGE_2005 = 4404, S_DEFRANGE2_2005 = 4405, S_DISCARDED = 4411, S_LPROCMIPS_ID = 4424, S_GPROCMIPS_ID = 4425, S_LPROCIA64_ID = 4426, S_GPROCIA64_ID = 4427, S_DEFRANGE_HLSL = 4432, S_GDATA_HLSL = 4433, S_LDATA_HLSL = 4434, S_LOCAL_DPC_GROUPSHARED = 4436, S_DEFRANGE_DPC_PTR_TAG = 4439, S_DPC_SYM_TAG_MAP = 4440, S_ARMSWITCHTABLE = 4441, S_POGODATA = 4444, S_INLINESITE2 = 4445, S_MOD_TYPEREF = 4447, S_REF_MINIPDB = 4448, S_PDBMAP = 4449, S_GDATA_HLSL32 = 4450, S_LDATA_HLSL32 = 4451, S_GDATA_HLSL32_EX = 4452, S_LDATA_HLSL32_EX = 4453, S_FASTLINK = 4455, S_INLINEES = 4456, S_END = 6, S_INLINESITE_END = 4430, S_PROC_ID_END = 4431, S_THUNK32 = 4354, S_TRAMPOLINE = 4396, S_SECTION = 4406, S_COFFGROUP = 4407, S_EXPORT = 4408, S_LPROC32 = 4367, S_GPROC32 = 4368, S_LPROC32_ID = 4422, S_GPROC32_ID = 4423, S_LPROC32_DPC = 4437, S_LPROC32_DPC_ID = 4438, S_REGISTER = 4358, S_PUB32 = 4366, S_PROCREF = 4389, S_LPROCREF = 4391, S_ENVBLOCK = 4413, S_INLINESITE = 4429, S_LOCAL = 4414, S_DEFRANGE = 4415, S_DEFRANGE_SUBFIELD = 4416, S_DEFRANGE_REGISTER = 4417, S_DEFRANGE_FRAMEPOINTER_REL = 4418, S_DEFRANGE_SUBFIELD_REGISTER = 4419, S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE = 4420, S_DEFRANGE_REGISTER_REL = 4421, S_BLOCK32 = 4355, S_LABEL32 = 4357, S_OBJNAME = 4353, S_COMPILE2 = 4374, S_COMPILE3 = 4412, S_FRAMEPROC = 4114, S_CALLSITEINFO = 4409, S_FILESTATIC = 4435, S_HEAPALLOCSITE = 4446, S_FRAMECOOKIE = 4410, S_CALLEES = 4442, S_CALLERS = 4443, S_UDT = 4360, S_COBOLUDT = 4361, S_BUILDINFO = 4428, S_BPREL32 = 4363, S_REGREL32 = 4369, S_CONSTANT = 4359, S_MANCONSTANT = 4397, S_LDATA32 = 4364, S_GDATA32 = 4365, S_LMANDATA = 4380, S_GMANDATA = 4381, S_LTHREAD32 = 4370, S_GTHREAD32 = 4371, }; pub const TypeIndex = u32; pub const ProcSym = packed struct { Parent: u32, End: u32, Next: u32, CodeSize: u32, DbgStart: u32, DbgEnd: u32, FunctionType: TypeIndex, CodeOffset: u32, Segment: u16, Flags: ProcSymFlags, // following is a null terminated string // Name: [*]u8, }; pub const ProcSymFlags = packed struct { HasFP: bool, HasIRET: bool, HasFRET: bool, IsNoReturn: bool, IsUnreachable: bool, HasCustomCallingConv: bool, IsNoInline: bool, HasOptimizedDebugInfo: bool, }; pub const SectionContrSubstreamVersion = enum(u32) { Ver60 = 0xeffe0000 + 19970605, V2 = 0xeffe0000 + 20140516, }; pub const RecordPrefix = packed struct { /// Record length, starting from &RecordKind. RecordLen: u16, /// Record kind enum (SymRecordKind or TypeRecordKind) RecordKind: SymbolKind, }; /// The following variable length array appears immediately after the header. /// The structure definition follows. /// LineBlockFragmentHeader Blocks[] /// Each `LineBlockFragmentHeader` as specified below. pub const LineFragmentHeader = packed struct { /// Code offset of line contribution. RelocOffset: u32, /// Code segment of line contribution. RelocSegment: u16, Flags: LineFlags, /// Code size of this line contribution. CodeSize: u32, }; pub const LineFlags = packed struct { /// CV_LINES_HAVE_COLUMNS LF_HaveColumns: bool, unused: u15, }; /// The following two variable length arrays appear immediately after the /// header. The structure definitions follow. /// LineNumberEntry Lines[NumLines]; /// ColumnNumberEntry Columns[NumLines]; pub const LineBlockFragmentHeader = packed struct { /// Offset of FileChecksum entry in File /// checksums buffer. The checksum entry then /// contains another offset into the string /// table of the actual name. NameIndex: u32, NumLines: u32, /// code size of block, in bytes BlockSize: u32, }; pub const LineNumberEntry = packed struct { /// Offset to start of code bytes for line number Offset: u32, Flags: u32, /// TODO runtime crash when I make the actual type of Flags this pub const Flags = packed struct { /// Start line number Start: u24, /// Delta of lines to the end of the expression. Still unclear. // TODO figure out the point of this field. End: u7, IsStatement: bool, }; }; pub const ColumnNumberEntry = packed struct { StartColumn: u16, EndColumn: u16, }; /// Checksum bytes follow. pub const FileChecksumEntryHeader = packed struct { /// Byte offset of filename in global string table. FileNameOffset: u32, /// Number of bytes of checksum. ChecksumSize: u8, /// FileChecksumKind ChecksumKind: u8, }; pub const DebugSubsectionKind = packed enum(u32) { None = 0, Symbols = 0xf1, Lines = 0xf2, StringTable = 0xf3, FileChecksums = 0xf4, FrameData = 0xf5, InlineeLines = 0xf6, CrossScopeImports = 0xf7, CrossScopeExports = 0xf8, // These appear to relate to .Net assembly info. ILLines = 0xf9, FuncMDTokenMap = 0xfa, TypeMDTokenMap = 0xfb, MergedAssemblyInput = 0xfc, CoffSymbolRVA = 0xfd, }; pub const DebugSubsectionHeader = packed struct { /// codeview::DebugSubsectionKind enum Kind: DebugSubsectionKind, /// number of bytes occupied by this record. Length: u32, }; pub const PDBStringTableHeader = packed struct { /// PDBStringTableSignature Signature: u32, /// 1 or 2 HashVersion: u32, /// Number of bytes of names buffer. ByteSize: u32, }; pub const Pdb = struct { in_file: File, allocator: *mem.Allocator, coff: *coff.Coff, string_table: *MsfStream, dbi: *MsfStream, msf: Msf, pub fn openFile(self: *Pdb, coff_ptr: *coff.Coff, file_name: []u8) !void { self.in_file = try fs.cwd().openFile(file_name, .{}); self.allocator = coff_ptr.allocator; self.coff = coff_ptr; try self.msf.openFile(self.allocator, self.in_file); } pub fn getStreamById(self: *Pdb, id: u32) ?*MsfStream { if (id >= self.msf.streams.len) return null; return &self.msf.streams[id]; } pub fn getStream(self: *Pdb, stream: StreamType) ?*MsfStream { const id = @enumToInt(stream); return self.getStreamById(id); } }; // see https://llvm.org/docs/PDB/MsfFile.html const Msf = struct { directory: MsfStream, streams: []MsfStream, fn openFile(self: *Msf, allocator: *mem.Allocator, file: File) !void { const in = file.inStream(); const superblock = try in.readStruct(SuperBlock); // Sanity checks if (!mem.eql(u8, &superblock.FileMagic, SuperBlock.file_magic)) return error.InvalidDebugInfo; if (superblock.FreeBlockMapBlock != 1 and superblock.FreeBlockMapBlock != 2) return error.InvalidDebugInfo; if (superblock.NumBlocks * superblock.BlockSize != try file.getEndPos()) return error.InvalidDebugInfo; switch (superblock.BlockSize) { // llvm only supports 4096 but we can handle any of these values 512, 1024, 2048, 4096 => {}, else => return error.InvalidDebugInfo, } const dir_block_count = blockCountFromSize(superblock.NumDirectoryBytes, superblock.BlockSize); if (dir_block_count > superblock.BlockSize / @sizeOf(u32)) return error.UnhandledBigDirectoryStream; // cf. BlockMapAddr comment. try file.seekTo(superblock.BlockSize * superblock.BlockMapAddr); var dir_blocks = try allocator.alloc(u32, dir_block_count); for (dir_blocks) |*b| { b.* = try in.readIntLittle(u32); } self.directory = MsfStream.init( superblock.BlockSize, file, dir_blocks, ); const begin = self.directory.pos; const stream_count = try self.directory.inStream().readIntLittle(u32); const stream_sizes = try allocator.alloc(u32, stream_count); defer allocator.free(stream_sizes); // Microsoft's implementation uses @as(u32, -1) for inexistant streams. // These streams are not used, but still participate in the file // and must be taken into account when resolving stream indices. const Nil = 0xFFFFFFFF; for (stream_sizes) |*s, i| { const size = try self.directory.inStream().readIntLittle(u32); s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize); } self.streams = try allocator.alloc(MsfStream, stream_count); for (self.streams) |*stream, i| { const size = stream_sizes[i]; if (size == 0) { stream.* = MsfStream{ .blocks = &[_]u32{}, }; } else { var blocks = try allocator.alloc(u32, size); var j: u32 = 0; while (j < size) : (j += 1) { const block_id = try self.directory.inStream().readIntLittle(u32); const n = (block_id % superblock.BlockSize); // 0 is for SuperBlock, 1 and 2 for FPMs. if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.BlockSize > try file.getEndPos()) return error.InvalidBlockIndex; blocks[j] = block_id; } stream.* = MsfStream.init( superblock.BlockSize, file, blocks, ); } } const end = self.directory.pos; if (end - begin != superblock.NumDirectoryBytes) return error.InvalidStreamDirectory; } }; fn blockCountFromSize(size: u32, block_size: u32) u32 { return (size + block_size - 1) / block_size; } // https://llvm.org/docs/PDB/MsfFile.html#the-superblock const SuperBlock = packed struct { /// The LLVM docs list a space between C / C++ but empirically this is not the case. const file_magic = "Microsoft C/C++ MSF 7.00\r\n\x1a\x44\x53\x00\x00\x00"; FileMagic: [file_magic.len]u8, /// The block size of the internal file system. Valid values are 512, 1024, /// 2048, and 4096 bytes. Certain aspects of the MSF file layout vary depending /// on the block sizes. For the purposes of LLVM, we handle only block sizes of /// 4KiB, and all further discussion assumes a block size of 4KiB. BlockSize: u32, /// The index of a block within the file, at which begins a bitfield representing /// the set of all blocks within the file which are “free” (i.e. the data within /// that block is not used). See The Free Block Map for more information. Important: /// FreeBlockMapBlock can only be 1 or 2! FreeBlockMapBlock: u32, /// The total number of blocks in the file. NumBlocks * BlockSize should equal the /// size of the file on disk. NumBlocks: u32, /// The size of the stream directory, in bytes. The stream directory contains /// information about each stream’s size and the set of blocks that it occupies. /// It will be described in more detail later. NumDirectoryBytes: u32, Unknown: u32, /// The index of a block within the MSF file. At this block is an array of /// ulittle32_t’s listing the blocks that the stream directory resides on. /// For large MSF files, the stream directory (which describes the block /// layout of each stream) may not fit entirely on a single block. As a /// result, this extra layer of indirection is introduced, whereby this /// block contains the list of blocks that the stream directory occupies, /// and the stream directory itself can be stitched together accordingly. /// The number of ulittle32_t’s in this array is given by /// ceil(NumDirectoryBytes / BlockSize). // Note: microsoft-pdb code actually suggests this is a variable-length // array. If the indices of blocks occupied by the Stream Directory didn't // fit in one page, there would be other u32 following it. // This would mean the Stream Directory is bigger than BlockSize / sizeof(u32) // blocks. We're not even close to this with a 1GB pdb file, and LLVM didn't // implement it so we're kind of safe making this assumption for now. BlockMapAddr: u32, }; const MsfStream = struct { in_file: File = undefined, pos: u64 = undefined, blocks: []u32 = undefined, block_size: u32 = undefined, pub const Error = @TypeOf(read).ReturnType.ErrorSet; fn init(block_size: u32, file: File, blocks: []u32) MsfStream { const stream = MsfStream{ .in_file = file, .pos = 0, .blocks = blocks, .block_size = block_size, }; return stream; } fn readNullTermString(self: *MsfStream, allocator: *mem.Allocator) ![]u8 { var list = ArrayList(u8).init(allocator); while (true) { const byte = try self.inStream().readByte(); if (byte == 0) { return list.span(); } try list.append(byte); } } fn read(self: *MsfStream, buffer: []u8) !usize { var block_id = @intCast(usize, self.pos / self.block_size); var block = self.blocks[block_id]; var offset = self.pos % self.block_size; try self.in_file.seekTo(block * self.block_size + offset); const in = self.in_file.inStream(); var size: usize = 0; var rem_buffer = buffer; while (size < buffer.len) { const size_to_read = math.min(self.block_size - offset, rem_buffer.len); size += try in.read(rem_buffer[0..size_to_read]); rem_buffer = buffer[size..]; offset += size_to_read; // If we're at the end of a block, go to the next one. if (offset == self.block_size) { offset = 0; block_id += 1; block = self.blocks[block_id]; try self.in_file.seekTo(block * self.block_size); } } self.pos += buffer.len; return buffer.len; } fn seekBy(self: *MsfStream, len: i64) !void { self.pos = @intCast(u64, @intCast(i64, self.pos) + len); if (self.pos >= self.blocks.len * self.block_size) return error.EOF; } fn seekTo(self: *MsfStream, len: u64) !void { self.pos = len; if (self.pos >= self.blocks.len * self.block_size) return error.EOF; } fn getSize(self: *const MsfStream) u64 { return self.blocks.len * self.block_size; } fn getFilePos(self: MsfStream) u64 { const block_id = self.pos / self.block_size; const block = self.blocks[block_id]; const offset = self.pos % self.block_size; return block * self.block_size + offset; } fn inStream(self: *MsfStream) std.io.InStream(*MsfStream, Error, read) { return .{ .context = self }; } };
lib/std/pdb.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const mem = std.mem; const os = std.os; const assert = std.debug.assert; const testing = std.testing; const elf = std.elf; const windows = std.os.windows; const system = std.os.system; const maxInt = std.math.maxInt; const max = std.math.max; pub const DynLib = switch (builtin.os.tag) { .linux => if (builtin.link_libc) DlDynlib else ElfDynLib, .windows => WindowsDynLib, .macos, .tvos, .watchos, .ios, .freebsd, .netbsd, .openbsd, .dragonfly, .solaris => DlDynlib, else => void, }; // The link_map structure is not completely specified beside the fields // reported below, any libc is free to store additional data in the remaining // space. // An iterator is provided in order to traverse the linked list in a idiomatic // fashion. const LinkMap = extern struct { l_addr: usize, l_name: [*:0]const u8, l_ld: ?*elf.Dyn, l_next: ?*LinkMap, l_prev: ?*LinkMap, pub const Iterator = struct { current: ?*LinkMap, pub fn end(self: *Iterator) bool { return self.current == null; } pub fn next(self: *Iterator) ?*LinkMap { if (self.current) |it| { self.current = it.l_next; return it; } return null; } }; }; const RDebug = extern struct { r_version: i32, r_map: ?*LinkMap, r_brk: usize, r_ldbase: usize, }; /// TODO make it possible to reference this same external symbol 2x so we don't need this /// helper function. pub fn get_DYNAMIC() ?[*]elf.Dyn { return @extern([*]elf.Dyn, .{ .name = "_DYNAMIC", .linkage = .Weak }); } pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator { _ = phdrs; const _DYNAMIC = get_DYNAMIC() orelse { // No PT_DYNAMIC means this is either a statically-linked program or a // badly corrupted dynamically-linked one. return LinkMap.Iterator{ .current = null }; }; const link_map_ptr = init: { var i: usize = 0; while (_DYNAMIC[i].d_tag != elf.DT_NULL) : (i += 1) { switch (_DYNAMIC[i].d_tag) { elf.DT_DEBUG => { const ptr = @intToPtr(?*RDebug, _DYNAMIC[i].d_val); if (ptr) |r_debug| { if (r_debug.r_version != 1) return error.InvalidExe; break :init r_debug.r_map; } }, elf.DT_PLTGOT => { const ptr = @intToPtr(?[*]usize, _DYNAMIC[i].d_val); if (ptr) |got_table| { // The address to the link_map structure is stored in // the second slot break :init @intToPtr(?*LinkMap, got_table[1]); } }, else => {}, } } return LinkMap.Iterator{ .current = null }; }; return LinkMap.Iterator{ .current = link_map_ptr }; } pub const ElfDynLib = struct { strings: [*:0]u8, syms: [*]elf.Sym, hashtab: [*]os.Elf_Symndx, versym: ?[*]u16, verdef: ?*elf.Verdef, memory: []align(mem.page_size) u8, pub const Error = error{ NotElfFile, NotDynamicLibrary, MissingDynamicLinkingInformation, ElfStringSectionNotFound, ElfSymSectionNotFound, ElfHashTableNotFound, }; /// Trusts the file. Malicious file will be able to execute arbitrary code. pub fn open(path: []const u8) !ElfDynLib { const fd = try os.open(path, 0, os.O.RDONLY | os.O.CLOEXEC); defer os.close(fd); const stat = try os.fstat(fd); const size = try std.math.cast(usize, stat.size); // This one is to read the ELF info. We do more mmapping later // corresponding to the actual LOAD sections. const file_bytes = try os.mmap( null, mem.alignForward(size, mem.page_size), os.PROT.READ, os.MAP.PRIVATE, fd, 0, ); defer os.munmap(file_bytes); const eh = @ptrCast(*elf.Ehdr, file_bytes.ptr); if (!mem.eql(u8, eh.e_ident[0..4], elf.MAGIC)) return error.NotElfFile; if (eh.e_type != elf.ET.DYN) return error.NotDynamicLibrary; const elf_addr = @ptrToInt(file_bytes.ptr); // Iterate over the program header entries to find out the // dynamic vector as well as the total size of the virtual memory. var maybe_dynv: ?[*]usize = null; var virt_addr_end: usize = 0; { var i: usize = 0; var ph_addr: usize = elf_addr + eh.e_phoff; while (i < eh.e_phnum) : ({ i += 1; ph_addr += eh.e_phentsize; }) { const ph = @intToPtr(*elf.Phdr, ph_addr); switch (ph.p_type) { elf.PT_LOAD => virt_addr_end = max(virt_addr_end, ph.p_vaddr + ph.p_memsz), elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, elf_addr + ph.p_offset), else => {}, } } } const dynv = maybe_dynv orelse return error.MissingDynamicLinkingInformation; // Reserve the entire range (with no permissions) so that we can do MAP.FIXED below. const all_loaded_mem = try os.mmap( null, virt_addr_end, os.PROT.NONE, os.MAP.PRIVATE | os.MAP.ANONYMOUS, -1, 0, ); errdefer os.munmap(all_loaded_mem); const base = @ptrToInt(all_loaded_mem.ptr); // Now iterate again and actually load all the program sections. { var i: usize = 0; var ph_addr: usize = elf_addr + eh.e_phoff; while (i < eh.e_phnum) : ({ i += 1; ph_addr += eh.e_phentsize; }) { const ph = @intToPtr(*elf.Phdr, ph_addr); switch (ph.p_type) { elf.PT_LOAD => { // The VirtAddr may not be page-aligned; in such case there will be // extra nonsense mapped before/after the VirtAddr,MemSiz const aligned_addr = (base + ph.p_vaddr) & ~(@as(usize, mem.page_size) - 1); const extra_bytes = (base + ph.p_vaddr) - aligned_addr; const extended_memsz = mem.alignForward(ph.p_memsz + extra_bytes, mem.page_size); const ptr = @intToPtr([*]align(mem.page_size) u8, aligned_addr); const prot = elfToMmapProt(ph.p_flags); if ((ph.p_flags & elf.PF_W) == 0) { // If it does not need write access, it can be mapped from the fd. _ = try os.mmap( ptr, extended_memsz, prot, os.MAP.PRIVATE | os.MAP.FIXED, fd, ph.p_offset - extra_bytes, ); } else { const sect_mem = try os.mmap( ptr, extended_memsz, prot, os.MAP.PRIVATE | os.MAP.FIXED | os.MAP.ANONYMOUS, -1, 0, ); mem.copy(u8, sect_mem, file_bytes[0..ph.p_filesz]); } }, else => {}, } } } var maybe_strings: ?[*:0]u8 = null; var maybe_syms: ?[*]elf.Sym = null; var maybe_hashtab: ?[*]os.Elf_Symndx = null; var maybe_versym: ?[*]u16 = null; var maybe_verdef: ?*elf.Verdef = null; { var i: usize = 0; while (dynv[i] != 0) : (i += 2) { const p = base + dynv[i + 1]; switch (dynv[i]) { elf.DT_STRTAB => maybe_strings = @intToPtr([*:0]u8, p), elf.DT_SYMTAB => maybe_syms = @intToPtr([*]elf.Sym, p), elf.DT_HASH => maybe_hashtab = @intToPtr([*]os.Elf_Symndx, p), elf.DT_VERSYM => maybe_versym = @intToPtr([*]u16, p), elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p), else => {}, } } } return ElfDynLib{ .memory = all_loaded_mem, .strings = maybe_strings orelse return error.ElfStringSectionNotFound, .syms = maybe_syms orelse return error.ElfSymSectionNotFound, .hashtab = maybe_hashtab orelse return error.ElfHashTableNotFound, .versym = maybe_versym, .verdef = maybe_verdef, }; } /// Trusts the file. Malicious file will be able to execute arbitrary code. pub fn openZ(path_c: [*:0]const u8) !ElfDynLib { return open(mem.sliceTo(path_c, 0)); } /// Trusts the file pub fn close(self: *ElfDynLib) void { os.munmap(self.memory); self.* = undefined; } pub fn lookup(self: *ElfDynLib, comptime T: type, name: [:0]const u8) ?T { if (self.lookupAddress("", name)) |symbol| { return @intToPtr(T, symbol); } else { return null; } } /// Returns the address of the symbol pub fn lookupAddress(self: *const ElfDynLib, vername: []const u8, name: []const u8) ?usize { const maybe_versym = if (self.verdef == null) null else self.versym; const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON); const OK_BINDS = (1 << elf.STB_GLOBAL | 1 << elf.STB_WEAK | 1 << elf.STB_GNU_UNIQUE); var i: usize = 0; while (i < self.hashtab[1]) : (i += 1) { if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue; if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == self.syms[i].st_shndx) continue; if (!mem.eql(u8, name, mem.sliceTo(self.strings + self.syms[i].st_name, 0))) continue; if (maybe_versym) |versym| { if (!checkver(self.verdef.?, versym[i], vername, self.strings)) continue; } return @ptrToInt(self.memory.ptr) + self.syms[i].st_value; } return null; } fn elfToMmapProt(elf_prot: u64) u32 { var result: u32 = os.PROT.NONE; if ((elf_prot & elf.PF_R) != 0) result |= os.PROT.READ; if ((elf_prot & elf.PF_W) != 0) result |= os.PROT.WRITE; if ((elf_prot & elf.PF_X) != 0) result |= os.PROT.EXEC; return result; } }; fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [*:0]u8) bool { var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) break; if (def.vd_next == 0) return false; def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next); } const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); return mem.eql(u8, vername, mem.sliceTo(strings + aux.vda_name, 0)); } pub const WindowsDynLib = struct { pub const Error = error{FileNotFound}; dll: windows.HMODULE, pub fn open(path: []const u8) !WindowsDynLib { const path_w = try windows.sliceToPrefixedFileW(path); return openW(path_w.span().ptr); } pub fn openZ(path_c: [*:0]const u8) !WindowsDynLib { const path_w = try windows.cStrToPrefixedFileW(path_c); return openW(path_w.span().ptr); } pub fn openW(path_w: [*:0]const u16) !WindowsDynLib { var offset: usize = 0; if (path_w[0] == '\\' and path_w[1] == '?' and path_w[2] == '?' and path_w[3] == '\\') { // + 4 to skip over the \??\ offset = 4; } return WindowsDynLib{ .dll = try windows.LoadLibraryW(path_w + offset), }; } pub fn close(self: *WindowsDynLib) void { windows.FreeLibrary(self.dll); self.* = undefined; } pub fn lookup(self: *WindowsDynLib, comptime T: type, name: [:0]const u8) ?T { if (windows.kernel32.GetProcAddress(self.dll, name.ptr)) |addr| { return @ptrCast(T, addr); } else { return null; } } }; pub const DlDynlib = struct { pub const Error = error{FileNotFound}; handle: *anyopaque, pub fn open(path: []const u8) !DlDynlib { const path_c = try os.toPosixPath(path); return openZ(&path_c); } pub fn openZ(path_c: [*:0]const u8) !DlDynlib { return DlDynlib{ .handle = system.dlopen(path_c, system.RTLD.LAZY) orelse { return error.FileNotFound; }, }; } pub fn close(self: *DlDynlib) void { _ = system.dlclose(self.handle); self.* = undefined; } pub fn lookup(self: *DlDynlib, comptime T: type, name: [:0]const u8) ?T { // dlsym (and other dl-functions) secretly take shadow parameter - return address on stack // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66826 if (@call(.{ .modifier = .never_tail }, system.dlsym, .{ self.handle, name.ptr })) |symbol| { return @ptrCast(T, symbol); } else { return null; } } }; test "dynamic_library" { const libname = switch (builtin.os.tag) { .linux, .freebsd, .openbsd => "invalid_so.so", .windows => "invalid_dll.dll", .macos, .tvos, .watchos, .ios => "invalid_dylib.dylib", else => return error.SkipZigTest, }; _ = DynLib.open(libname) catch |err| { try testing.expect(err == error.FileNotFound); return; }; }
lib/std/dynamic_library.zig
const std = @import("std"); const Impulse = @import("notes.zig").Impulse; const Notes = @import("notes.zig").Notes; const Span = @import("basics.zig").Span; pub const ConstantOrBuffer = union(enum) { constant: f32, buffer: []const f32, }; pub fn constant(x: f32) ConstantOrBuffer { return .{ .constant = x }; } pub fn buffer(buf: []const f32) ConstantOrBuffer { return .{ .buffer = buf }; } pub fn Trigger(comptime ParamsType: type) type { const NoteSpanNote = struct { id: usize, params: ParamsType, }; const NoteSpan = struct { start: usize, end: usize, note: ?NoteSpanNote, }; return struct { // once set, this is never set back to null, because note-off should // still be rendered (for envelope release) note: ?NoteSpanNote, pub const Counter = struct { iap: Notes(ParamsType).ImpulsesAndParamses, impulse_index: usize, start: usize, end: usize, }; pub const NewPaintReturnValue = struct { span: Span, params: ParamsType, note_id_changed: bool, }; pub fn init() @This() { return @This() { .note = null, }; } pub fn reset(self: *@This()) void { self.note = null; } pub fn counter( self: *@This(), span: Span, iap: Notes(ParamsType).ImpulsesAndParamses, ) Counter { return Counter { .iap = iap, .impulse_index = 0, .start = span.start, .end = span.end, }; } pub fn next(self: *@This(), ctr: *Counter) ?NewPaintReturnValue { while (ctr.start < ctr.end) { // first, try to continue a previously started note (this will // peek ahead in order to stop as soon as the first next new // note comes). then, take impulses from the ctr // (getNextNoteSpan). const note_span = carryOver(ctr, self.note) orelse getNextNoteSpan(ctr); ctr.start = note_span.end; if (note_span.note) |note| { defer self.note = note; return NewPaintReturnValue { .span = Span.init(note_span.start, note_span.end), .params = note.params, .note_id_changed = if (self.note) |self_note| note.id != self_note.id else true, }; } } return null; } fn carryOver(ctr: *const Counter, current_note: ?NoteSpanNote) ?NoteSpan { // check for currently playing note if (current_note) |note| { if (ctr.impulse_index < ctr.iap.impulses.len) { const next_impulse_frame = ctr.iap.impulses[ctr.impulse_index].frame; if (next_impulse_frame > ctr.start) { // next impulse starts later, so play the current note // for now return NoteSpan { .start = ctr.start, .end = std.math.min(ctr.end, next_impulse_frame), .note = note, }; } else { // next impulse starts now return null; } } else { // no new impulses - play current note for the whole buffer return NoteSpan { .start = ctr.start, .end = ctr.end, .note = note, }; } } else { return null; } } fn getNextNoteSpan(ctr: *Counter) NoteSpan { const impulses = ctr.iap.impulses[ctr.impulse_index..]; const paramses = ctr.iap.paramses[ctr.impulse_index..]; for (impulses) |impulse, i| { if (impulse.frame >= ctr.end) { // this impulse (and all after it, since they're in // chronological order) starts after the end of the buffer. // this should never happen (the impulses coming in should // have been clipped already) break; } if (impulse.frame > ctr.start) { // gap before the note begins return NoteSpan { .start = ctr.start, .end = impulse.frame, .note = null, }; } std.debug.assert(impulse.frame == ctr.start); ctr.impulse_index += 1; // this span ends at the start of the next impulse (if one // exists), or the end of the buffer, whichever comes first const note_end_clipped = if (i + 1 < impulses.len) std.math.min(ctr.end, impulses[i + 1].frame) else ctr.end; if (note_end_clipped <= ctr.start) { // either the impulse is entirely in the past (which // should be impossible), or the next one starts at the // same time continue; } return NoteSpan { .start = ctr.start, .end = note_end_clipped, .note = NoteSpanNote { .id = impulse.note_id, .params = paramses[i], }, }; } // no more impulses return NoteSpan { .start = ctr.start, .end = ctr.end, .note = null, }; } }; }
src/zang/trigger.zig
const std = @import("std"); const g = @cImport(@cInclude("grok.h")); const GrokError = @import("error.zig").GrokErrors; const get_error = @import("error.zig").get_error; const json = std.json; const jstruct = struct { word1: ?[]const u8 = null, word2: ?[]const u8 = null, }; pub fn main() !void { const user_patterns = "%{WORD:word1} %{WORD:word2} in %{NUMBER:n}"; const base_patterns = "/home/caster/software/grok/patterns/base"; const input_text = "hello world in 2021"; var page = std.heap.page_allocator; var arena = std.heap.ArenaAllocator.init(page); var allocator = &arena.allocator; defer arena.deinit(); var js = jstruct{}; var iter1 = try getIterator(base_patterns, user_patterns, input_text); defer iter1.deinit(); try toStructAlloc(jstruct, &js, &iter1, allocator); std.debug.print("Result is: {}\n", .{js}); js = jstruct{}; var iter3 = try getIterator(base_patterns, user_patterns, input_text); defer iter3.deinit(); var buf2 = try allocator.alloc(u8, 100); try toStruct(jstruct, &js, &iter3, buf2[0..50], buf2[50..]); std.debug.print("Result is: {}\n", .{js}); } pub fn toStruct(comptime T: type, st: anytype, iter: *Iterator, key: []u8, value: []u8) !void { comptime var struct_t: std.builtin.TypeInfo = @typeInfo(T); while (try iter.next(key, value)) |token| { inline for (struct_t.Struct.fields) |field| { if (std.mem.eql(u8, token.get_name(), field.name)) { @field(st, field.name) = token.get_value(); break; } } } } pub fn toStructAlloc(comptime T: type, st: anytype, iter: *Iterator, allocator: *std.mem.Allocator) !void { comptime var struct_t: std.builtin.TypeInfo = @typeInfo(T); while (try iter.nextAlloc(allocator)) |token| { inline for (struct_t.Struct.fields) |field| { if (std.mem.eql(u8, token.get_name(), field.name)) { @field(st, field.name) = token.get_value(); break; } } } } const Result = struct { name: []const u8, namelen: usize, str: []const u8, strlen: usize, pub fn init(name: []const u8, str: []const u8) Result { return Result{ .name = name, .str = str, }; } pub fn get_value(self: *const Result) []const u8 { return self.str[0..self.strlen]; } pub fn get_type(self: *const Result) []const u8 { for (self.name[0..self.namelen]) |c, i| { if (c == ':') { return self.name[0..i]; } } return self.name; } pub fn get_name(self: *const Result) []const u8 { for (self.name[0..self.namelen]) |c, i| { if (c == ':') { return self.name[i + 1 .. self.namelen]; } } return self.name; } }; const Iterator = struct { match: g.grok_match_t, grok: [*c]g.grok_t, pub fn init(match: g.grok_match_t, grok: [*c]g.grok_t) Iterator { return Iterator{ .match = match, .grok = grok, }; } pub fn next(self: *Iterator, type_buf: []u8, str_buf: []u8) !?Result { var t = type_buf; var s = str_buf; var name = @ptrCast([*c][*c]u8, &t); var str = @ptrCast([*c][*c]u8, &s); var strlen: c_int = 0; var namelen: c_int = 0; var res = g.grok_match_walk_next(&self.match, name, &namelen, str, &strlen); if (res == 1) { // EOF return null; } else if (res > 1) { return get_error(res); } return Result{ .name = t, .namelen = @intCast(usize, namelen), .str = s, .strlen = @intCast(usize, strlen), }; } pub fn nextAlloc(self: *Iterator, alloc: *std.mem.Allocator) !?Result { var name_ = try alloc.alloc(u8, 50); var str_ = try alloc.alloc(u8, 50); const name = @ptrCast([*c][*c]u8, &name_); const str = @ptrCast([*c][*c]u8, &str_); var strlen: c_int = 0; var namelen: c_int = 0; const res = g.grok_match_walk_next(&self.match, name, &namelen, str, &strlen); if (res == 1) { // EOF return null; } else if (res > 1) { return get_error(res); } return Result{ .name = name_, .namelen = @intCast(usize, namelen), .str = str_, .strlen = @intCast(usize, strlen), }; } pub fn deinit(self: *Iterator) void { g.free(self.grok); // match is freed by the library } }; fn getIterator(base_patterns: [*c]const u8, user_patterns: [*c]const u8, input_text: [*c]const u8) !Iterator { var mygrok = g.grok_new(); var res = g.grok_patterns_import_from_file(mygrok, base_patterns); if (res != 0) { return get_error(res); } res = g.grok_compile(mygrok, user_patterns); if (res != 0) { return get_error(res); } var match = g.grok_match_t{ .end = 0, .start = 0, .subject = "", .grok = mygrok, }; res = g.grok_exec(mygrok, input_text, &match); if (res != 0) { return get_error(res); } g.grok_match_walk_init(&match); return Iterator.init(match, mygrok); }
main.zig
const std = @import("std"); const mem = std.mem; const powci = @import("powci.zig").powci; const maxInt = std.math.maxInt; fn Hibitset(comptime Int: type, comptime layers: comptime_int) type { const bitc = comptime std.meta.bitCount(Int); comptime var layer_offsets: [layers]usize = [_]usize{0} ** layers; comptime var sum = 0; comptime var i = 0; while (i < layers) : (i += 1) { layer_offsets[i] = sum; comptime var p = powci(bitc, i); sum += p; } return struct { const Self = @This(); const Shift = std.math.Log2Int(Int); const bits = bitc; layer_data: [sum]Int = [_]Int{0} ** sum, pub fn init() Self { return Self{}; } fn index_to_end(self: *const Self, index: usize) usize { return switch (index) { comptime layers - 1 => self.layer_data.len, comptime layers...maxInt(usize) => @panic("layer out of bounds"), else => layer_offsets[index + 1], }; } pub fn layer(self: *Self, index: usize) []Int { const end = index_to_end(self, index); return self.layer_data[layer_offsets[index]..end]; } pub fn const_layer(self: *const Self, index: usize) []const Int { const end = index_to_end(self, index); return self.layer_data[layer_offsets[index]..end]; } pub fn set(self: *Self, index: usize) void { var lindex = index / bits; var bindex = index % bits; var current_layer: isize = layers - 1; if (self.get(index)) { return; // already set } else while (current_layer >= 0) : (current_layer -= 1) { self.layer(@intCast(usize, current_layer))[lindex] |= @as(Int, 1) << @intCast(Shift, bindex); bindex = lindex % bits; lindex /= bits; } } pub fn unset(self: *Self, index: usize) void { var lindex = index / bits; var bindex = index % bits; var current_layer: isize = layers - 1; if (!self.get(index)) { return; // already unset } else while (current_layer >= 0) : (current_layer -= 1) { var block = &self.layer(@intCast(usize, current_layer))[lindex]; block.* &= ~(@as(Int, 1) << @intCast(Shift, bindex)); if (block.* != 0) { break; } bindex = lindex % bits; lindex /= bits; } } pub fn get(self: *const Self, index: usize) bool { var lindex = index / bits; var bindex = index % bits; return (self.const_layer(layers - 1)[lindex] >> @intCast(Shift, bindex)) & 0x01 != 0; } pub fn clear(self: *Self) void { for (self.layer_data) |*l| { l.* = 0; } } pub fn is_empty(self: *const Self) bool { return self.const_layer(0)[0] == 0; } pub fn eq(self: *const Self, other: *const Self) bool { comptime var l = 0; return inline while (l < layers) : (l += 1) { if (!mem.eql(Int, self.const_layer(l), other.const_layer(l))) { break false; } } else true; } }; } test "f" { const Set = Hibitset(usize, 4); var set = Set.init(); std.debug.warn("{}\n", .{@typeInfo(Set.Shift)}); std.debug.warn("{}\n", .{Set.bits}); var l: usize = 0; while (l < 2) : (l += 1) { for (set.layer(l)) |i| { std.debug.warn("{b:0>4}|", .{i}); } std.debug.warn("\n", .{}); } } test "set check" { const Set = Hibitset(u4, 3); var set = Set.init(); var i: usize = 0; while (i < powci(4, 3)) : (i += 1) { set.set(i); std.debug.assert(set.get(i)); } } test "set unset check" { const Set = Hibitset(u4, 3); var set = Set.init(); var i: usize = 0; while (i < powci(4, 3)) : (i += 1) { set.set(i); set.unset(i); std.debug.assert(!set.get(i)); } } test "set all unset interleaved check" { const Set = Hibitset(u4, 3); var set = Set.init(); var i: usize = 0; while (i < powci(4, 3)) : (i += 1) { if (i % 2 == 0) { set.set(i); } } i = 0; while (i < powci(4, 3)) : (i += 1) { if (i % 4 == 0) { set.unset(i); } } for (set.layer(0)) |x| { std.debug.assert(x == 0b1111); } for (set.layer(1)) |x| { std.debug.assert(x == 0b1111); } for (set.layer(2)) |x| { std.debug.assert(x == 0b0100); } } test "clear" { const Set = Hibitset(u4, 3); var set = Set.init(); var i: usize = 0; while (i < powci(4, 3)) : (i += 1) { set.set(i); } set.clear(); for (set.layer_data) |l| { std.debug.assert(l == 0); } } test "is_empty" { const Set = Hibitset(u4, 3); var set = Set.init(); std.debug.assert(set.is_empty()); } test "eq" { const Set = Hibitset(u4, 3); var set = Set.init(); var set2 = Set.init(); const set3 = Set.init(); var i: usize = 0; while (i < powci(4, 3)) : (i += 1) { if (i % 4 == 0) { set.set(i); set2.set(i); } } std.debug.assert(set.eq(&set2)); std.debug.assert(!set.eq(&set3)); }
src/lib.zig
const std = @import("std"); pub const Rela = struct { offset: usize, info: usize, symbol_value: usize, reltype: Reltype, symbol_name: []const u8, section_index: u16, plt_addr: ?usize, }; pub const Syms = struct { num: u64, value: u64, size: u64, symtype: Symtype, bind: Bind, visibility: Visiblity, index: u16, name: []const u8, }; pub const Symtype = enum(c_int) { NOTYPE = 0, OBJECT = 1, FUNC = 2, SECTION = 3, FILE = 4, TLS = 6, NUM = 7, LOOS = 10, HIOS = 12, _, }; pub const Bind = enum(c_int) { LOCAL = 0, GLOBAL = 1, WEAK = 2, NUM = 3, UNIQUE = 10, HIOS = 12, LOPROC = 13, _, }; pub const Visiblity = enum(c_int) { DEFAULT = 0, INTERNAL = 1, HIDDEN = 2, PROTECTED = 3, _, }; pub const Reltype = enum(u32) { R_X86_64_OR_386_NONE = 0, R_X86_64_OR_386_64 = 1, R_X86_64_OR_386_PC32 = 2, R_X86_64_OR_386_GOT32 = 3, R_X86_64_OR_386_PLT32 = 4, R_X86_64_OR_386_COPY = 5, R_X86_64_OR_386_GLOB_DAT = 6, R_X86_64_OR_386_JUMP_SLOT = 7, R_X86_64_OR_386_RELATIVE = 8, R_X86_64_OR_386_GOTPCREL = 9, R_X86_64_OR_386_32 = 10, R_X86_64_OR_386_32S = 11, R_X86_64_OR_386_16 = 12, R_X86_64_OR_386_PC16 = 13, R_X86_64_OR_386_8 = 14, R_X86_64_OR_386_PC8 = 15, R_X86_64_OR_386_DTPMOD64 = 16, R_X86_64_OR_386_DTPOFF64 = 17, R_X86_64_OR_386_TPOFF64 = 18, R_X86_64_OR_386_TLSGD = 19, R_X86_64_OR_386_TLSLD = 20, R_X86_64_OR_386_DTPOFF32 = 21, R_X86_64_OR_386_GOTTPOFF = 22, R_X86_64_OR_386_TPOFF32 = 23, R_X86_64_OR_386_PC64 = 24, R_X86_64_OR_386_GOTOFF64 = 25, R_X86_64_OR_386_GOTPC32 = 26, R_X86_64_OR_386_GOT64 = 27, R_X86_64_OR_386_GOTPCREL64 = 28, R_X86_64_OR_386_GOTPC64 = 29, R_X86_64_OR_386_GOTPLT64 = 30, R_X86_64_OR_386_PLTOFF64 = 31, R_X86_64_OR_386_SIZE32 = 32, R_X86_64_OR_386_SIZE64 = 33, R_X86_64_OR_386_GOTPC32_TLSDESC = 34, R_X86_64_OR_386_TLSDESC_CALL = 35, R_X86_64_OR_386_TLSDESC = 36, R_X86_64_OR_386_IRELATIVE = 37, R_X86_64_OR_386_RELATIVE64 = 38, R_X86_64_OR_386_GOTPCRELX = 41, R_X86_64_OR_386_REX_GOTPCRELX = 42, R_X86_64_OR_386_NUM = 43, _, };
src/data-structures/sym-n-rela.zig
pub const VDMCONTEXT_i386 = @as(u32, 65536); pub const VDMCONTEXT_i486 = @as(u32, 65536); pub const VDM_KGDT_R3_CODE = @as(u32, 24); pub const VDM_MAXIMUM_SUPPORTED_EXTENSION = @as(u32, 512); pub const V86FLAGS_CARRY = @as(u32, 1); pub const V86FLAGS_PARITY = @as(u32, 4); pub const V86FLAGS_AUXCARRY = @as(u32, 16); pub const V86FLAGS_ZERO = @as(u32, 64); pub const V86FLAGS_SIGN = @as(u32, 128); pub const V86FLAGS_TRACE = @as(u32, 256); pub const V86FLAGS_INTERRUPT = @as(u32, 512); pub const V86FLAGS_DIRECTION = @as(u32, 1024); pub const V86FLAGS_OVERFLOW = @as(u32, 2048); pub const V86FLAGS_IOPL = @as(u32, 12288); pub const V86FLAGS_IOPL_BITS = @as(u32, 18); pub const V86FLAGS_RESUME = @as(u32, 65536); pub const V86FLAGS_V86 = @as(u32, 131072); pub const V86FLAGS_ALIGNMENT = @as(u32, 262144); pub const STATUS_VDM_EVENT = @as(i32, 1073741829); pub const DBG_SEGLOAD = @as(u32, 0); pub const DBG_SEGMOVE = @as(u32, 1); pub const DBG_SEGFREE = @as(u32, 2); pub const DBG_MODLOAD = @as(u32, 3); pub const DBG_MODFREE = @as(u32, 4); pub const DBG_SINGLESTEP = @as(u32, 5); pub const DBG_BREAK = @as(u32, 6); pub const DBG_GPFAULT = @as(u32, 7); pub const DBG_DIVOVERFLOW = @as(u32, 8); pub const DBG_INSTRFAULT = @as(u32, 9); pub const DBG_TASKSTART = @as(u32, 10); pub const DBG_TASKSTOP = @as(u32, 11); pub const DBG_DLLSTART = @as(u32, 12); pub const DBG_DLLSTOP = @as(u32, 13); pub const DBG_ATTACH = @as(u32, 14); pub const DBG_TOOLHELP = @as(u32, 15); pub const DBG_STACKFAULT = @as(u32, 16); pub const DBG_WOWINIT = @as(u32, 17); pub const DBG_TEMPBP = @as(u32, 18); pub const DBG_MODMOVE = @as(u32, 19); pub const DBG_INIT = @as(u32, 20); pub const DBG_GPFAULT2 = @as(u32, 21); pub const VDMEVENT_NEEDS_INTERACTIVE = @as(u32, 32768); pub const VDMEVENT_VERBOSE = @as(u32, 16384); pub const VDMEVENT_PE = @as(u32, 8192); pub const VDMEVENT_ALLFLAGS = @as(u32, 57344); pub const VDMEVENT_V86 = @as(u32, 1); pub const VDMEVENT_PM16 = @as(u32, 2); pub const MAX_MODULE_NAME = @as(u32, 9); pub const MAX_PATH16 = @as(u32, 255); pub const SN_CODE = @as(u32, 0); pub const SN_DATA = @as(u32, 1); pub const SN_V86 = @as(u32, 2); pub const GLOBAL_ALL = @as(u32, 0); pub const GLOBAL_LRU = @as(u32, 1); pub const GLOBAL_FREE = @as(u32, 2); pub const GT_UNKNOWN = @as(u32, 0); pub const GT_DGROUP = @as(u32, 1); pub const GT_DATA = @as(u32, 2); pub const GT_CODE = @as(u32, 3); pub const GT_TASK = @as(u32, 4); pub const GT_RESOURCE = @as(u32, 5); pub const GT_MODULE = @as(u32, 6); pub const GT_FREE = @as(u32, 7); pub const GT_INTERNAL = @as(u32, 8); pub const GT_SENTINEL = @as(u32, 9); pub const GT_BURGERMASTER = @as(u32, 10); pub const GD_USERDEFINED = @as(u32, 0); pub const GD_CURSORCOMPONENT = @as(u32, 1); pub const GD_BITMAP = @as(u32, 2); pub const GD_ICONCOMPONENT = @as(u32, 3); pub const GD_MENU = @as(u32, 4); pub const GD_DIALOG = @as(u32, 5); pub const GD_STRING = @as(u32, 6); pub const GD_FONTDIR = @as(u32, 7); pub const GD_FONT = @as(u32, 8); pub const GD_ACCELERATORS = @as(u32, 9); pub const GD_RCDATA = @as(u32, 10); pub const GD_ERRTABLE = @as(u32, 11); pub const GD_CURSOR = @as(u32, 12); pub const GD_ICON = @as(u32, 14); pub const GD_NAMETABLE = @as(u32, 15); pub const GD_MAX_RESOURCE = @as(u32, 15); pub const VDMDBG_BREAK_DOSTASK = @as(u32, 1); pub const VDMDBG_BREAK_WOWTASK = @as(u32, 2); pub const VDMDBG_BREAK_LOADDLL = @as(u32, 4); pub const VDMDBG_BREAK_EXCEPTIONS = @as(u32, 8); pub const VDMDBG_BREAK_DEBUGGER = @as(u32, 16); pub const VDMDBG_TRACE_HISTORY = @as(u32, 128); pub const VDMDBG_BREAK_DIVIDEBYZERO = @as(u32, 256); pub const VDMDBG_INITIAL_FLAGS = @as(u32, 256); pub const VDMDBG_MAX_SYMBOL_BUFFER = @as(u32, 256); pub const VDMADDR_V86 = @as(u32, 2); pub const VDMADDR_PM16 = @as(u32, 4); pub const VDMADDR_PM32 = @as(u32, 16); //-------------------------------------------------------------------------------- // Section: Types (41) //-------------------------------------------------------------------------------- pub const VDMCONTEXT_WITHOUT_XSAVE = extern struct { ContextFlags: u32, Dr0: u32, Dr1: u32, Dr2: u32, Dr3: u32, Dr6: u32, Dr7: u32, FloatSave: FLOATING_SAVE_AREA, SegGs: u32, SegFs: u32, SegEs: u32, SegDs: u32, Edi: u32, Esi: u32, Ebx: u32, Edx: u32, Ecx: u32, Eax: u32, Ebp: u32, Eip: u32, SegCs: u32, EFlags: u32, Esp: u32, SegSs: u32, }; pub const SEGMENT_NOTE = extern struct { Selector1: u16, Selector2: u16, Segment: u16, Module: [10]CHAR, FileName: [256]CHAR, Type: u16, Length: u32, }; pub const IMAGE_NOTE = extern struct { Module: [10]CHAR, FileName: [256]CHAR, hModule: u16, hTask: u16, }; pub const MODULEENTRY = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug dwSize: u32, szModule: [10]CHAR, hModule: ?HANDLE, wcUsage: u16, szExePath: [256]CHAR, wNext: u16, }; pub const TEMP_BP_NOTE = extern struct { Seg: u16, Offset: u32, bPM: BOOL, }; pub const VDM_SEGINFO = extern struct { Selector: u16, SegNumber: u16, Length: u32, Type: u16, ModuleName: [9]CHAR, FileName: [255]CHAR, }; pub const GLOBALENTRY = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug dwSize: u32, dwAddress: u32, dwBlockSize: u32, hBlock: ?HANDLE, wcLock: u16, wcPageLock: u16, wFlags: u16, wHeapPresent: BOOL, hOwner: ?HANDLE, wType: u16, wData: u16, dwNext: u32, dwNextAlt: u32, }; pub const DEBUGEVENTPROC = fn( param0: ?*DEBUG_EVENT, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PROCESSENUMPROC = fn( dwProcessId: u32, dwAttributes: u32, lpUserDefined: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const TASKENUMPROC = fn( dwThreadId: u32, hMod16: u16, hTask16: u16, lpUserDefined: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const TASKENUMPROCEX = fn( dwThreadId: u32, hMod16: u16, hTask16: u16, pszModName: ?*i8, pszFileName: ?*i8, lpUserDefined: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMPROCESSEXCEPTIONPROC = fn( param0: ?*DEBUG_EVENT, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETPOINTERPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: u16, param3: u32, param4: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub const VDMKILLWOWPROC = fn( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMDETECTWOWPROC = fn( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMBREAKTHREADPROC = fn( param0: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETSELECTORMODULEPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: u16, param3: ?*u32, param4: ?PSTR, param5: u32, param6: ?PSTR, param7: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETMODULESELECTORPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: u32, param3: ?PSTR, param4: ?*u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMMODULEFIRSTPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*MODULEENTRY, param3: ?DEBUGEVENTPROC, param4: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMMODULENEXTPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*MODULEENTRY, param3: ?DEBUGEVENTPROC, param4: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGLOBALFIRSTPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*GLOBALENTRY, param3: u16, param4: ?DEBUGEVENTPROC, param5: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGLOBALNEXTPROC = fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*GLOBALENTRY, param3: u16, param4: ?DEBUGEVENTPROC, param5: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMENUMPROCESSWOWPROC = fn( param0: ?PROCESSENUMPROC, param1: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const VDMENUMTASKWOWPROC = fn( param0: u32, param1: ?TASKENUMPROC, param2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const VDMENUMTASKWOWEXPROC = fn( param0: u32, param1: ?TASKENUMPROCEX, param2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const VDMTERMINATETASKINWOWPROC = fn( param0: u32, param1: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMSTARTTASKINWOWPROC = fn( param0: u32, param1: ?PSTR, param2: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETDBGFLAGSPROC = fn( param0: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub const VDMSETDBGFLAGSPROC = fn( param0: ?HANDLE, param1: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMISMODULELOADEDPROC = fn( param0: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETSEGMENTINFOPROC = fn( param0: u16, param1: u32, param2: BOOL, param3: VDM_SEGINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETSYMBOLPROC = fn( param0: ?PSTR, param1: u16, param2: u32, param3: BOOL, param4: BOOL, param5: *[256]u8, param6: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMGETADDREXPRESSIONPROC = fn( param0: ?PSTR, param1: ?PSTR, param2: ?*u16, param3: ?*u32, param4: ?*u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const VDMCONTEXT = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { ContextFlags: u32, Dr0: u32, Dr1: u32, Dr2: u32, Dr3: u32, Dr6: u32, Dr7: u32, FloatSave: FLOATING_SAVE_AREA, SegGs: u32, SegFs: u32, SegEs: u32, SegDs: u32, Edi: u32, Esi: u32, Ebx: u32, Edx: u32, Ecx: u32, Eax: u32, Ebp: u32, Eip: u32, SegCs: u32, EFlags: u32, Esp: u32, SegSs: u32, ExtendedRegisters: [512]u8, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const VDMLDT_ENTRY = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { LimitLow: u16, BaseLow: u16, HighWord: extern union { Bytes: extern struct { BaseMid: u8, Flags1: u8, Flags2: u8, BaseHi: u8, }, Bits: extern struct { _bitfield: u32, }, }, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const VDMGETTHREADSELECTORENTRYPROC = switch(@import("../zig.zig").arch) { .X64, .Arm64 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: u32, param3: ?*VDMLDT_ENTRY, ) callconv(@import("std").os.windows.WINAPI) BOOL, .X86 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: u32, param3: ?*LDT_ENTRY, ) callconv(@import("std").os.windows.WINAPI) BOOL, }; pub const VDMGETCONTEXTPROC = switch(@import("../zig.zig").arch) { .X64, .Arm64 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*VDMCONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL, .X86 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*CONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL, }; pub const VDMSETCONTEXTPROC = switch(@import("../zig.zig").arch) { .X64, .Arm64 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*VDMCONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL, .X86 => fn( param0: ?HANDLE, param1: ?HANDLE, param2: ?*CONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL, }; //-------------------------------------------------------------------------------- // 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 (9) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const CHAR = @import("../foundation.zig").CHAR; const DEBUG_EVENT = @import("../system/diagnostics/debug.zig").DEBUG_EVENT; const FLOATING_SAVE_AREA = @import("../system/kernel.zig").FLOATING_SAVE_AREA; const HANDLE = @import("../foundation.zig").HANDLE; const LPARAM = @import("../foundation.zig").LPARAM; const PSTR = @import("../foundation.zig").PSTR; // 2 arch-specific imports const CONTEXT = switch(@import("../zig.zig").arch) { .X86 => @import("../system/diagnostics/debug.zig").CONTEXT, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; const LDT_ENTRY = switch(@import("../zig.zig").arch) { .X86 => @import("../system/diagnostics/debug.zig").LDT_ENTRY, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "DEBUGEVENTPROC")) { _ = DEBUGEVENTPROC; } if (@hasDecl(@This(), "PROCESSENUMPROC")) { _ = PROCESSENUMPROC; } if (@hasDecl(@This(), "TASKENUMPROC")) { _ = TASKENUMPROC; } if (@hasDecl(@This(), "TASKENUMPROCEX")) { _ = TASKENUMPROCEX; } if (@hasDecl(@This(), "VDMPROCESSEXCEPTIONPROC")) { _ = VDMPROCESSEXCEPTIONPROC; } if (@hasDecl(@This(), "VDMGETPOINTERPROC")) { _ = VDMGETPOINTERPROC; } if (@hasDecl(@This(), "VDMKILLWOWPROC")) { _ = VDMKILLWOWPROC; } if (@hasDecl(@This(), "VDMDETECTWOWPROC")) { _ = VDMDETECTWOWPROC; } if (@hasDecl(@This(), "VDMBREAKTHREADPROC")) { _ = VDMBREAKTHREADPROC; } if (@hasDecl(@This(), "VDMGETSELECTORMODULEPROC")) { _ = VDMGETSELECTORMODULEPROC; } if (@hasDecl(@This(), "VDMGETMODULESELECTORPROC")) { _ = VDMGETMODULESELECTORPROC; } if (@hasDecl(@This(), "VDMMODULEFIRSTPROC")) { _ = VDMMODULEFIRSTPROC; } if (@hasDecl(@This(), "VDMMODULENEXTPROC")) { _ = VDMMODULENEXTPROC; } if (@hasDecl(@This(), "VDMGLOBALFIRSTPROC")) { _ = VDMGLOBALFIRSTPROC; } if (@hasDecl(@This(), "VDMGLOBALNEXTPROC")) { _ = VDMGLOBALNEXTPROC; } if (@hasDecl(@This(), "VDMENUMPROCESSWOWPROC")) { _ = VDMENUMPROCESSWOWPROC; } if (@hasDecl(@This(), "VDMENUMTASKWOWPROC")) { _ = VDMENUMTASKWOWPROC; } if (@hasDecl(@This(), "VDMENUMTASKWOWEXPROC")) { _ = VDMENUMTASKWOWEXPROC; } if (@hasDecl(@This(), "VDMTERMINATETASKINWOWPROC")) { _ = VDMTERMINATETASKINWOWPROC; } if (@hasDecl(@This(), "VDMSTARTTASKINWOWPROC")) { _ = VDMSTARTTASKINWOWPROC; } if (@hasDecl(@This(), "VDMGETDBGFLAGSPROC")) { _ = VDMGETDBGFLAGSPROC; } if (@hasDecl(@This(), "VDMSETDBGFLAGSPROC")) { _ = VDMSETDBGFLAGSPROC; } if (@hasDecl(@This(), "VDMISMODULELOADEDPROC")) { _ = VDMISMODULELOADEDPROC; } if (@hasDecl(@This(), "VDMGETSEGMENTINFOPROC")) { _ = VDMGETSEGMENTINFOPROC; } if (@hasDecl(@This(), "VDMGETSYMBOLPROC")) { _ = VDMGETSYMBOLPROC; } if (@hasDecl(@This(), "VDMGETADDREXPRESSIONPROC")) { _ = VDMGETADDREXPRESSIONPROC; } if (@hasDecl(@This(), "VDMGETTHREADSELECTORENTRYPROC")) { _ = VDMGETTHREADSELECTORENTRYPROC; } if (@hasDecl(@This(), "VDMGETTHREADSELECTORENTRYPROC")) { _ = VDMGETTHREADSELECTORENTRYPROC; } if (@hasDecl(@This(), "VDMGETCONTEXTPROC")) { _ = VDMGETCONTEXTPROC; } if (@hasDecl(@This(), "VDMGETCONTEXTPROC")) { _ = VDMGETCONTEXTPROC; } if (@hasDecl(@This(), "VDMSETCONTEXTPROC")) { _ = VDMSETCONTEXTPROC; } if (@hasDecl(@This(), "VDMSETCONTEXTPROC")) { _ = VDMSETCONTEXTPROC; } @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/system/virtual_dos_machines.zig
const std = @import("std"); const Company = struct { csv: []const u8, name: []const u8, se: []const u8, income_year: []const u8, company_type: []const u8, taxable_income: []const u8, deficit: []const u8, corporate_tax: []const u8, }; fn csvLineToCompany(line: []const u8) Company { var row_columns = std.mem.split(u8, line, ","); const csv = row_columns.next() orelse ""; const name = row_columns.next() orelse ""; const se = row_columns.next() orelse ""; const income_year = row_columns.next() orelse ""; _ = row_columns.next(); // Skip 5 const company_type = row_columns.next() orelse ""; _ = row_columns.next(); // Skip 7 _ = row_columns.next(); // Skip 8 const taxable_income = row_columns.next() orelse ""; const deficit = row_columns.next() orelse ""; const corporate_tax = row_columns.next() orelse ""; return Company{ .csv = csv, .name = name, .se = se, .income_year = income_year, .company_type = company_type, .taxable_income = taxable_income, .deficit = deficit, .corporate_tax = corporate_tax, }; } pub fn main() anyerror!void { const input_f_name = ""; const output_f_name = ""; const input_file = try std.fs.cwd().openFile(input_f_name, std.fs.File.OpenFlags{}); defer input_file.close(); var buf_reader = std.io.bufferedReader(input_file.reader()); var in_stream = buf_reader.reader(); const output_file = try std.fs.cwd().createFile(output_f_name, std.fs.File.CreateFlags{}); defer output_file.close(); var buf_writer = std.io.bufferedWriter(output_file.writer()); const out_stream = buf_writer.writer(); var buf_line_reader: [512]u8 = undefined; _ = try in_stream.readUntilDelimiterOrEof(&buf_line_reader, '\n'); // Skip first line while (try in_stream.readUntilDelimiterOrEof(&buf_line_reader, '\n')) |line| { try std.json.stringify(csvLineToCompany(line), .{}, out_stream); _ = try out_stream.write("\n"); } try buf_writer.flush(); }
src/main.zig
const std = @import("std"); const Instruction = @import("../common/ir.zig").Instruction; const InstructionName = @import("../common/ir.zig").InstructionName; /// A handle to a location in source code. /// This handle is created by a `CodeWriter` and only that code writer /// knows where this label is located in memory (or if it is yet to be defined). pub const Label = enum(u32) { _ }; /// A append-only data structure that allows emission of data and instructions to create /// LoLa byte code. pub const CodeWriter = struct { const Self = @This(); const Loop = struct { breakLabel: Label, continueLabel: Label }; const Patch = struct { label: Label, offset: u32 }; /// The bytecode that was already emitted. code: std.ArrayList(u8), /// Used as a stack of loops. Each loop has a break position and a continue position, /// which can be emitted by calling emitBreak or emitContinue. This allows nesting loops /// and emitting the right loop targets without passing the context around in code generation. loops: std.ArrayList(Loop), /// Stores a list of forward references for labels. This is required /// when a call to `emitLabel` happens before `defineLabel` is called. /// This list is empty when all emitted label references are well-defined. patches: std.ArrayList(Patch), /// Stores the offset for every defined label. labels: std.AutoHashMap(Label, u32), next_label: u32 = 0, pub fn init(allocator: std.mem.Allocator) Self { return Self{ .code = std.ArrayList(u8).init(allocator), .loops = std.ArrayList(Loop).init(allocator), .patches = std.ArrayList(Patch).init(allocator), .labels = std.AutoHashMap(Label, u32).init(allocator), }; } pub fn deinit(self: *Self) void { self.code.deinit(); self.loops.deinit(); self.patches.deinit(); self.labels.deinit(); self.* = undefined; } /// Finalizes the code generation process and returns the generated code. /// The returned memory is owned by the caller and was allocated with the allocator passed into `init`. pub fn finalize(self: *Self) ![]u8 { if (self.loops.items.len != 0) return error.InvalidCode; if (self.patches.items.len != 0) return error.InvalidCode; self.loops.shrinkAndFree(0); self.patches.shrinkAndFree(0); self.labels.clearAndFree(); return self.code.toOwnedSlice(); } /// Creates a new label identifier. This only returns a new handle, it does /// not emit any code or modify data structures. pub fn createLabel(self: *Self) !Label { if (self.next_label == std.math.maxInt(u32)) return error.TooManyLabels; const id = @intToEnum(Label, self.next_label); self.next_label += 1; return id; } /// Defines the location a label references. This must be called exactly once for a label. /// Calling it more than once is a error, the same as calling it never. /// Defining a label will patch all forward references in the `code`, removing the need to /// store patches for later. pub fn defineLabel(self: *Self, lbl: Label) !void { const item = try self.labels.getOrPut(lbl); if (item.found_existing) return error.LabelAlreadyDefined; item.value_ptr.* = @intCast(u32, self.code.items.len); // resolve all forward references to this label, so we // have a empty patch list when every referenced label was also defined. var i: usize = 0; while (i < self.patches.items.len) { const patch = self.patches.items[i]; if (patch.label == lbl) { std.mem.writeIntLittle(u32, self.code.items[patch.offset..][0..4], item.value_ptr.*); _ = self.patches.swapRemove(i); } else { i += 1; } } } /// Combination of createLabel and defineLabel, is provided as a convenience function. pub fn createAndDefineLabel(self: *Self) !Label { const lbl = try self.createLabel(); try self.defineLabel(lbl); return lbl; } /// Pushes a new loop construct. /// `breakLabel` is a label that is jumped to when a `break` instruction is emitted. This is usually the end of the loop. /// `continueLabel` is a label that is jumped to when a `continue` instruction is emitted. This is usually the start of the loop. pub fn pushLoop(self: *Self, breakLabel: Label, continueLabel: Label) !void { try self.loops.append(Loop{ .breakLabel = breakLabel, .continueLabel = continueLabel, }); } /// Pops a loop from the stack. pub fn popLoop(self: *Self) void { std.debug.assert(self.loops.items.len > 0); _ = self.loops.pop(); } /// emits raw data pub fn emitRaw(self: *Self, data: []const u8) !void { if (self.code.items.len + data.len > std.math.maxInt(u32)) return error.OutOfMemory; try self.code.writer().writeAll(data); } /// Emits a label and marks a patch position if necessary pub fn emitLabel(self: *Self, label: Label) !void { if (self.labels.get(label)) |offset| { try self.emitU32(offset); } else { try self.patches.append(Patch{ .label = label, .offset = @intCast(u32, self.code.items.len), }); try self.emitU32(0xFFFFFFFF); } } /// Emits a raw instruction name without the corresponding instruction arguments. pub fn emitInstructionName(self: *Self, name: InstructionName) !void { try self.emitU8(@enumToInt(name)); } pub fn emitInstruction(self: *Self, instr: Instruction) !void { try self.emitInstructionName(instr); inline for (std.meta.fields(Instruction)) |fld| { if (instr == @field(InstructionName, fld.name)) { const value = @field(instr, fld.name); if (fld.field_type == Instruction.Deprecated) { @panic("called emitInstruction with a deprecated instruction!"); // this is a API violation } else if (fld.field_type == Instruction.NoArg) { // It's enough to emit the instruction name return; } else if (fld.field_type == Instruction.CallArg) { try self.emitString(value.function); try self.emitU8(value.argc); return; } else { const ValType = std.meta.fieldInfo(fld.field_type, .value).field_type; switch (ValType) { []const u8 => try self.emitString(value.value), u8 => try self.emitU8(value.value), u16 => try self.emitU16(value.value), u32 => try self.emitU32(value.value), f64 => try self.emitNumber(value.value), else => @compileError("Unsupported encoding: " ++ @typeName(ValType)), } return; } } } unreachable; } fn emitNumber(self: *Self, val: f64) !void { try self.emitRaw(std.mem.asBytes(&val)); } /// Encodes a variable-length string with a max. length of 0 … 65535 characters. pub fn emitString(self: *Self, val: []const u8) !void { try self.emitU16(try std.math.cast(u16, val.len)); try self.emitRaw(val); } fn emitInteger(self: *Self, comptime T: type, val: T) !void { var buf: [@sizeOf(T)]u8 = undefined; std.mem.writeIntLittle(T, &buf, val); try self.emitRaw(&buf); } /// Emits a unsigned 32 bit integer, encoded little endian. pub fn emitU8(self: *Self, val: u8) !void { try self.emitInteger(u8, val); } /// Emits a unsigned 32 bit integer, encoded little endian. pub fn emitU16(self: *Self, val: u16) !void { try self.emitInteger(u16, val); } /// Emits a unsigned 32 bit integer, encoded little endian. pub fn emitU32(self: *Self, val: u32) !void { try self.emitInteger(u32, val); } pub fn emitBreak(self: *Self) !void { if (self.loops.items.len > 0) { const loop = self.loops.items[self.loops.items.len - 1]; try self.emitInstructionName(.jmp); try self.emitLabel(loop.breakLabel); } else { return error.NotInLoop; } } pub fn emitContinue(self: *Self) !void { if (self.loops.items.len > 0) { const loop = self.loops.items[self.loops.items.len - 1]; try self.emitInstructionName(.jmp); try self.emitLabel(loop.continueLabel); } else { return error.NotInLoop; } } }; test "empty code generation" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "", mem); } test "emitting primitive values" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); try writer.emitU32(0x44332211); try writer.emitU16(0x6655); try writer.emitU8(0x77); try writer.emitInstructionName(.jmp); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "\x11\x22\x33\x44\x55\x66\x77\x1B", mem); } test "emitting variable-width strings" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); try writer.emitString("Hello"); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "\x05\x00Hello", mem); } test "label handling" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); const label = try writer.createLabel(); try writer.emitLabel(label); // tests the patch path try writer.defineLabel(label); // tests label insertion try writer.emitLabel(label); // tests the fast-forward path const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "\x04\x00\x00\x00\x04\x00\x00\x00", mem); } test "label creation" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); const label1 = try writer.createLabel(); const label2 = try writer.createLabel(); const label3 = try writer.createLabel(); try std.testing.expect(label1 != label2); try std.testing.expect(label1 != label3); try std.testing.expect(label2 != label3); } test "loop creation, break and continue emission" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); const label_start = try writer.createLabel(); const label_end = try writer.createLabel(); try std.testing.expectError(error.NotInLoop, writer.emitBreak()); try std.testing.expectError(error.NotInLoop, writer.emitContinue()); try writer.emitRaw("A"); try writer.pushLoop(label_end, label_start); try writer.emitRaw("B"); try writer.defineLabel(label_start); try writer.emitRaw("C"); try writer.emitBreak(); try writer.emitRaw("D"); try writer.emitContinue(); try writer.emitRaw("E"); try writer.defineLabel(label_end); try writer.emitRaw("F"); writer.popLoop(); try std.testing.expectError(error.NotInLoop, writer.emitBreak()); try std.testing.expectError(error.NotInLoop, writer.emitContinue()); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "ABC\x1B\x0F\x00\x00\x00D\x1B\x02\x00\x00\x00EF", mem); } test "emitting numeric value" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); try writer.emitNumber(0.0); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices(u8, "\x00\x00\x00\x00\x00\x00\x00\x00", mem); } test "instruction emission" { var writer = CodeWriter.init(std.testing.allocator); defer writer.deinit(); // tests a NoArg instruction try writer.emitInstruction(Instruction{ .push_void = .{}, }); // tests a SingleArg([]const u8) instruction try writer.emitInstruction(Instruction{ .push_str = .{ .value = "abc" }, }); // tests a SingleArg(f64) instruction try writer.emitInstruction(Instruction{ .push_num = .{ .value = 0.0000 }, }); // tests a SingleArg(u32) instruction try writer.emitInstruction(Instruction{ .jmp = .{ .value = 0x44332211 }, }); // tests a SingleArg(u16) instruction try writer.emitInstruction(Instruction{ .store_local = .{ .value = 0xBEEF }, }); const mem = try writer.finalize(); defer std.testing.allocator.free(mem); try std.testing.expectEqualSlices( u8, "\x2B" ++ "\x06\x03\x00abc" ++ "\x07\x00\x00\x00\x00\x00\x00\x00\x00" ++ "\x1B\x11\x22\x33\x44" ++ "\x22\xEF\xBE", mem, ); }
src/library/compiler/code-writer.zig
const std = @import("std"); /// Makes all vector and matrix types generic against Real pub fn specializeOn(comptime Real: type) type { return struct { /// Helper for the swizzle operator. /// Returns the type fitting the number of swizzle elements fn SwizzleTypeByElements(comptime i: usize) type { return switch (i) { 1 => Real, 2 => Vec2, 3 => Vec3, 4 => Vec4, else => @compileError("Swizzle can take up to 4 elements!"), }; } /// Returns a type mixin for a vector type implementing all component-wise operations. /// Reduces the amount of duplicated code by a lot fn VectorMixin(comptime Self: type) type { return struct { /// adds all components from `a` with the components of `b`. pub fn add(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) + @field(b, fld.name); } return result; } pub fn hash(self: Self) u32 { return std.hash.Adler32.hash(&std.mem.toBytes(self)); } pub fn hash64(self: Self) u64 { return std.hash.Wyhash.hash(34837813, &std.mem.toBytes(self)); } /// subtracts all components from `a` with the components of `b`. pub fn sub(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) - @field(b, fld.name); } return result; } /// multiplies all components from `a` with the components of `b`. pub fn mul(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) * @field(b, fld.name); } return result; } /// divides all components from `a` by the components of `b`. pub fn div(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) / @field(b, fld.name); } return result; } /// multiplies all components by a scalar value. pub fn scale(a: Self, b: Real) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) * b; } return result; } pub fn scaleDiv(a: Self, b: Real) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = @field(a, fld.name) / b; } return result; } /// returns the dot product of two vectors. /// This is the sum of products of all components. pub fn dot(a: Self, b: Self) Real { var result: Real = 0; inline for (@typeInfo(Self).Struct.fields) |fld| { result += @field(a, fld.name) * @field(b, fld.name); } return result; } pub fn distanceTo(a: Self, b: Self) Real { return (a.sub(b).abs()).length(); } /// returns the magnitude of the vector. pub fn length(a: Self) Real { return std.math.sqrt(a.length2()); } /// returns the squared magnitude of the vector. pub fn length2(a: Self) Real { return Self.dot(a, a); } /// returns either a normalized vector (`length() = 1`) or `zero` if the vector /// has length 0. pub fn normalize(vec: Self) Self { var len = vec.length(); return if (len != 0.0) vec.scale(1.0 / vec.length()) else Self.zero; } /// applies component-wise absolute values pub fn abs(a: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = std.math.absFloat(@field(a, fld.name)); } return result; } /// swizzle vector fields into a new vector type. /// swizzle("xxx") will return a Vec3 with three times the x component. /// swizzle will return a vector or scalar type with the same number of components as the /// `components` string. /// `components` may be any sequence of `x`, `y`, `z`, `w`, `0` and `1`. /// The letters will be replaced by the corresponding component, the digits will be replaced /// by the corresponding literal value. /// /// Examples: /// - `vec4(1,2,3,4).swizzle("wzyx") == vec4(4, 3, 2, 1)` /// - `vec4(1,2,3,4).swizzle("xyx") == vec3(1,2,1)` /// - `vec2(1,2).swizzle("xyxy") == vec4(1,2,1,2)` /// - `vec2(3,4).swizzle("xy01") == vec4(3, 4, 0, 1)` /// pub fn swizzle(self: Self, comptime components: []const u8) SwizzleTypeByElements(components.len) { const T = SwizzleTypeByElements(components.len); var result: T = undefined; if (components.len > 1) { const fieldorder = "xyzw"; _ = fieldorder; inline for (components) |c, i| { _ = c; const slice = components[i .. i + 1]; const temp = if (comptime std.mem.eql(u8, slice, "0")) 0 else if (comptime std.mem.eql(u8, slice, "1")) 1 else @field(self, components[i .. i + 1]); @field(result, switch (i) { 0 => "x", 1 => "y", 2 => "z", 3 => "w", else => @compileError("this should not happen"), }) = temp; } } else if (components.len == 1) { result = @field(self, components); } else { @compileError("components must at least contain a single field!"); } return result; } /// returns a new vector where each component is the minimum of the components of the input vectors. pub fn componentMin(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = std.math.min(@field(a, fld.name), @field(b, fld.name)); } return result; } /// returns a new vector where each component is the maximum of the components of the input vectors. pub fn componentMax(a: Self, b: Self) Self { var result: Self = undefined; inline for (@typeInfo(Self).Struct.fields) |fld| { @field(result, fld.name) = std.math.max(@field(a, fld.name), @field(b, fld.name)); } return result; } }; } pub const Rect = extern struct { position: Vec2 = .{}, size: Vec2 = .{}, pub inline fn newVec(pos: Vec2, size: Vec2) Rect { return new(pos.x, pos.y, size.x, size.y); } pub fn new(x: Real, y: Real, width: Real, height: Real) Rect { return .{ .position = .{ .x = x, .y = y }, .size = .{ .x = width, .y = height } }; } pub fn containsPoint(self: Rect, point: Vec2) bool { return point.x >= self.position.x and point.y >= self.position.y and point.x <= self.position.x + self.size.x and point.y <= self.position.y + self.size.y; } pub fn containsRect(self: Rect, other: Rect) bool { return ((((self.position.x <= other.position.x) and ((other.position.x + other.size.x) <= (self.position.x + self.size.x))) and (self.position.y <= other.position.y)) and ((other.position.y + other.size.y) <= (self.position.y + self.size.y))); } pub fn intersectsRect(self: Rect, other: Rect) bool { return other.position.x <= self.position.x + self.size.x and self.position.x <= other.position.x + other.size.x and other.position.y <= self.position.y + self.size.y and self.position.y <= other.position.y + other.size.y; } }; /// 2-dimensional vector type. pub const Vec2 = extern struct { const Self = @This(); x: Real = 0, y: Real = 0, pub const zero = Self.new(0, 0); pub const one = Self.new(1, 1); pub const unitX = Self.new(1, 0); pub const unitY = Self.new(0, 1); usingnamespace VectorMixin(Self); pub fn new(x: Real, y: Real) Self { return Self{ .x = x, .y = y, }; } pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = options; _ = fmt; try stream.print("vec2({d:.2}, {d:.2})", .{ value.x, value.y }); } fn getField(vec: Self, comptime index: comptime_int) Real { switch (index) { 0 => return vec.x, 1 => return vec.y, else => @compileError("index out of bounds!"), } } /// multiplies the vector with a matrix. pub fn transform(vec: Self, mat: Mat2) Self { var result = zero; inline for ([_]comptime_int{ 0, 1 }) |i| { result.x += vec.getField(i) * mat.fields[0][i]; result.y += vec.getField(i) * mat.fields[1][i]; } return result; } /// multiplies the vector with a matrix4. pub fn transform4(vec: Self, mat: Mat4) Self { return Self.new( // (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41 (vec.x * mat.fields[0][0]) + (vec.y * mat.fields[1][0]) + mat.fields[3][0], // (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42 (vec.x * mat.fields[0][1]) + (vec.y * mat.fields[1][1]) + mat.fields[3][1], ); } }; /// 3-dimensional vector type. pub const Vec3 = extern struct { const Self = @This(); x: Real = 0, y: Real = 0, z: Real = 0, pub const zero = Self.new(0, 0, 0); pub const one = Self.new(1, 1, 1); pub const unitX = Self.new(1, 0, 0); pub const unitY = Self.new(0, 1, 0); pub const unitZ = Self.new(0, 0, 1); usingnamespace VectorMixin(Self); pub fn new(x: Real, y: Real, z: Real) Self { return Self{ .x = x, .y = y, .z = z, }; } pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = options; _ = fmt; try stream.print("vec3({d:.2}, {d:.2}, {d:.2})", .{ value.x, value.y, value.z }); } /// calculates the cross product. result will be perpendicular to a and b. pub fn cross(a: Self, b: Self) Self { return Self{ .x = a.y * b.z - a.z * b.y, .y = a.z * b.x - a.x * b.z, .z = a.x * b.y - a.y * b.x, }; } /// converts the vector from an homogeneous position (w=1). pub fn toAffinePosition(a: Self) Vec4 { return Vec4{ .x = a.x, .y = a.y, .z = a.z, .w = 1.0, }; } /// converts the vector from an homogeneous direction (w=0). pub fn toAffineDirection(a: Self) Vec4 { return Vec4{ .x = a.x, .y = a.y, .z = a.z, .w = 0.0, }; } pub fn fromAffinePosition(a: Vec4) Self { return Vec3{ .x = a.x / a.w, .y = a.y / a.w, .z = a.z / a.w, }; } pub fn fromAffineDirection(a: Vec4) Self { return Vec3{ .x = a.x, .y = a.y, .z = a.z, }; } /// multiplies the vector with a matrix. pub fn transform(vec: Self, mat: Mat3) Self { var result = zero; inline for ([_]comptime_int{ 0, 1, 2 }) |i| { result.x += vec.getField(i) * mat.fields[0][i]; result.y += vec.getField(i) * mat.fields[1][i]; result.z += vec.getField(i) * mat.fields[2][i]; } return result; } /// transforms a homogeneous position. pub fn transformPosition(vec: Self, mat: Mat4) Self { return fromAffinePosition(vec.toAffinePosition().transform(mat)); } /// transforms a homogeneous direction. pub fn transformDirection(vec: Self, mat: Mat4) Self { return fromAffineDirection(vec.toAffineDirection().transform(mat)); } fn getField(vec: Self, comptime index: comptime_int) Real { switch (index) { 0 => return vec.x, 1 => return vec.y, 2 => return vec.z, else => @compileError("index out of bounds!"), } } }; /// 4-dimensional vector type. pub const Vec4 = extern struct { const Self = @This(); x: Real = 0, y: Real = 0, z: Real = 0, w: Real = 0, pub const zero = Self.new(0, 0, 0, 0); pub const one = Self.new(1, 1, 1, 1); pub const unitX = Self.new(1, 0, 0, 0); pub const unitY = Self.new(0, 1, 0, 0); pub const unitZ = Self.new(0, 0, 1, 0); pub const unitW = Self.new(0, 0, 0, 1); pub const white = Self.new(1, 1, 1, 1); pub const black = Self.new(0, 0, 0, 1); pub const transparent = Self.new(0, 0, 0, 0); usingnamespace VectorMixin(Self); pub fn new(x: Real, y: Real, z: Real, w: Real) Self { return Self{ .x = x, .y = y, .z = z, .w = w, }; } pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = options; _ = fmt; try stream.print("vec4({d:.2}, {d:.2}, {d:.2}, {d:.2})", .{ value.x, value.y, value.z, value.w }); } /// multiplies the vector with a matrix. pub fn transform(vec: Self, mat: Mat4) Self { var result = zero; inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| { result.x += vec.getField(i) * mat.fields[i][0]; result.y += vec.getField(i) * mat.fields[i][1]; result.z += vec.getField(i) * mat.fields[i][2]; result.w += vec.getField(i) * mat.fields[i][3]; } return result; } fn getField(vec: Self, comptime index: comptime_int) Real { switch (index) { 0 => return vec.x, 1 => return vec.y, 2 => return vec.z, 3 => return vec.w, else => @compileError("index out of bounds!"), } } }; /// 2 by 2 matrix type. pub const Mat2 = extern struct { fields: [2][2]Real, // [row][col] /// identitiy matrix pub const identity = Self{ .fields = [2]Real{ [2]Real{ 1, 0 }, [2]Real{ 0, 1 }, }, }; }; /// 3 by 3 matrix type. pub const Mat3 = extern struct { fields: [3][3]Real, // [row][col] /// identitiy matrix pub const identity = Self{ .fields = [3]Real{ [3]Real{ 1, 0, 0 }, [3]Real{ 0, 1, 0 }, [3]Real{ 0, 0, 1 }, }, }; }; /// 4 by 4 matrix type. pub const Mat4 = extern struct { pub const Self = @This(); fields: [4][4]Real, // [row][col] /// zero matrix. pub const zero = Self{ .fields = [4][4]Real{ [4]Real{ 0, 0, 0, 0 }, [4]Real{ 0, 0, 0, 0 }, [4]Real{ 0, 0, 0, 0 }, [4]Real{ 0, 0, 0, 0 }, }, }; /// identitiy matrix pub const identity = Self{ .fields = [4][4]Real{ [4]Real{ 1, 0, 0, 0 }, [4]Real{ 0, 1, 0, 0 }, [4]Real{ 0, 0, 1, 0 }, [4]Real{ 0, 0, 0, 1 }, }, }; pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = options; _ = fmt; try stream.writeAll("mat4{"); inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| { const row = value.fields[i]; try stream.print(" ({d:.2} {d:.2} {d:.2} {d:.2})", .{ row[0], row[1], row[2], row[3] }); } try stream.writeAll(" }"); } /// performs matrix multiplication of a*b pub fn mul(a: Self, b: Self) Self { var result: Self = undefined; inline for ([_]comptime_int{ 0, 1, 2, 3 }) |row| { inline for ([_]comptime_int{ 0, 1, 2, 3 }) |col| { var sum: Real = 0.0; inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| { sum += a.fields[row][i] * b.fields[i][col]; } result.fields[row][col] = sum; } } return result; } /// transposes the matrix. /// this will swap columns with rows. pub fn transpose(a: Self) Self { var result: Self = undefined; inline for ([_]comptime_int{ 0, 1, 2, 3 }) |row| { inline for ([_]comptime_int{ 0, 1, 2, 3 }) |col| { result.fields[row][col] = a.fields[col][row]; } } return result; } // taken from GLM implementation /// Creates a look-at matrix. /// The matrix will create a transformation that can be used /// as a camera transform. /// the camera is located at `eye` and will look into `direction`. /// `up` is the direction from the screen center to the upper screen border. pub fn createLook(eye: Vec3, direction: Vec3, up: Vec3) Self { const f = direction.normalize(); const s = Vec3.cross(up, f).normalize(); const u = Vec3.cross(f, s); var result = Self.identity; result.fields[0][0] = s.x; result.fields[1][0] = s.y; result.fields[2][0] = s.z; result.fields[0][1] = u.x; result.fields[1][1] = u.y; result.fields[2][1] = u.z; result.fields[0][2] = f.x; result.fields[1][2] = f.y; result.fields[2][2] = f.z; result.fields[3][0] = -Vec3.dot(s, eye); result.fields[3][1] = -Vec3.dot(u, eye); result.fields[3][2] = -Vec3.dot(f, eye); return result; } /// Creates a look-at matrix. /// The matrix will create a transformation that can be used /// as a camera transform. /// the camera is located at `eye` and will look at `center`. /// `up` is the direction from the screen center to the upper screen border. pub fn createLookAt(eye: Vec3, center: Vec3, up: Vec3) Self { return createLook(eye, Vec3.sub(center, eye), up); } // taken from GLM implementation /// creates a perspective transformation matrix. /// `fov` is the field of view in radians, /// `aspect` is the screen aspect ratio (width / height) /// `near` is the distance of the near clip plane, whereas `far` is the distance to the far clip plane. pub fn createPerspective(fov: Real, aspect: Real, near: Real, far: Real) Self { std.debug.assert(std.math.fabs(aspect - 0.001) > 0); const tanHalfFovy = std.math.tan(fov / 2); var result = Self.zero; result.fields[0][0] = 1.0 / (aspect * tanHalfFovy); result.fields[1][1] = 1.0 / (tanHalfFovy); result.fields[2][2] = far / (far - near); result.fields[2][3] = 1; result.fields[3][2] = -(far * near) / (far - near); return result; } /// creates a rotation matrix around a certain axis. pub fn createAngleAxis(axis: Vec3, angle: Real) Self { var cos = std.math.cos(angle); var sin = std.math.sin(angle); var x = axis.x; var y = axis.y; var z = axis.z; return Self{ .fields = [4][4]Real{ [4]Real{ cos + x * x * (1 - cos), x * y * (1 - cos) - z * sin, x * z * (1 - cos) + y * sin, 0 }, [4]Real{ y * x * (1 - cos) + z * sin, cos + y * y * (1 - cos), y * z * (1 - cos) - x * sin, 0 }, [4]Real{ z * x * (1 * cos) - y * sin, z * y * (1 - cos) + x * sin, cos + z * z * (1 - cos), 0 }, [4]Real{ 0, 0, 0, 1 }, }, }; } pub fn createZRotation(radians: f32) Self { var result = Self.identity; var val1 = @cos(radians); var val2 = @sin(radians); result.fields[0][0] = val1; result.fields[0][1] = val2; result.fields[1][0] = -val2; result.fields[1][1] = val1; return result; } /// creates matrix that will scale a homogeneous matrix. pub fn createUniformScale(scale: Real) Self { return createScale(scale, scale, scale); } /// Creates a non-uniform scaling matrix pub fn createScale(x: Real, y: Real, z: Real) Self { return Self{ .fields = [4][4]Real{ [4]Real{ x, 0, 0, 0 }, [4]Real{ 0, y, 0, 0 }, [4]Real{ 0, 0, z, 0 }, [4]Real{ 0, 0, 0, 1 }, }, }; } /// creates matrix that will translate a homogeneous matrix. pub fn createTranslationXYZ(x: Real, y: Real, z: Real) Self { return Self{ .fields = [4][4]Real{ [4]Real{ 1, 0, 0, 0 }, [4]Real{ 0, 1, 0, 0 }, [4]Real{ 0, 0, 1, 0 }, [4]Real{ x, y, z, 1 }, }, }; } /// creates matrix that will scale a homogeneous matrix. pub fn createTranslation(v: Vec3) Self { return Self{ .fields = [4][4]Real{ [4]Real{ 1, 0, 0, 0 }, [4]Real{ 0, 1, 0, 0 }, [4]Real{ 0, 0, 1, 0 }, [4]Real{ v.x, v.y, v.z, 1 }, }, }; } /// creates an orthogonal projection matrix. /// `left`, `right`, `bottom` and `top` are the borders of the screen whereas `near` and `far` define the /// distance of the near and far clipping planes. pub fn createOrthogonal(left: Real, right: Real, bottom: Real, top: Real, near: Real, far: Real) Self { var result = Self.identity; result.fields[0][0] = 2 / (right - left); result.fields[1][1] = 2 / (top - bottom); result.fields[2][2] = 1 / (far - near); result.fields[3][0] = -(right + left) / (right - left); result.fields[3][1] = -(top + bottom) / (top - bottom); result.fields[3][2] = -near / (far - near); return result; } pub fn inlined(self: Self) [16]f32 { return @bitCast([16]f32, self.fields); } /// Batch matrix multiplication. Will multiply all matrices from "first" to "last". pub fn batchMul(items: []const Self) Self { if (items.len == 0) return Self.identity; if (items.len == 1) return items[0]; var value = items[0]; var i: usize = 1; while (i < items.len) : (i += 1) { value = value.mul(items[i]); } return value; } pub fn invert(src: Self) ?Self { // https://github.com/stackgl/gl-mat4/blob/master/invert.js const a = @bitCast([16]f32, src.fields); const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const a03 = a[3]; const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const a13 = a[7]; const a20 = a[8]; const a21 = a[9]; const a22 = a[10]; const a23 = a[11]; const a30 = a[12]; const a31 = a[13]; const a32 = a[14]; const a33 = a[15]; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (std.math.approxEqAbs(f32, det, 0, 1e-8)) { return null; } det = 1.0 / det; const out = [16]f32{ (a11 * b11 - a12 * b10 + a13 * b09) * det, // 0 (a02 * b10 - a01 * b11 - a03 * b09) * det, // 1 (a31 * b05 - a32 * b04 + a33 * b03) * det, // 2 (a22 * b04 - a21 * b05 - a23 * b03) * det, // 3 (a12 * b08 - a10 * b11 - a13 * b07) * det, // 4 (a00 * b11 - a02 * b08 + a03 * b07) * det, // 5 (a32 * b02 - a30 * b05 - a33 * b01) * det, // 6 (a20 * b05 - a22 * b02 + a23 * b01) * det, // 7 (a10 * b10 - a11 * b08 + a13 * b06) * det, // 8 (a01 * b08 - a00 * b10 - a03 * b06) * det, // 9 (a30 * b04 - a31 * b02 + a33 * b00) * det, // 10 (a21 * b02 - a20 * b04 - a23 * b00) * det, // 11 (a11 * b07 - a10 * b09 - a12 * b06) * det, // 12 (a00 * b09 - a01 * b07 + a02 * b06) * det, // 13 (a31 * b01 - a30 * b03 - a32 * b00) * det, // 14 (a20 * b03 - a21 * b01 + a22 * b00) * det, // 15 }; return Self{ .fields = @bitCast([4][4]f32, out), }; } }; /// constructs a new Vec2. pub fn vec2(x: Real, y: Real) Vec2 { return Vec2.new(x, y); } /// constructs a new Vec3. pub fn vec3(x: Real, y: Real, z: Real) Vec3 { return Vec3.new(x, y, z); } /// constructs a new Vec4. pub fn vec4(x: Real, y: Real, z: Real, w: Real) Vec4 { return Vec4.new(x, y, z, w); } /// constructs a new Rectangle. pub fn rect(x: Real, y: Real, w: Real, h: Real) Rect { return .{ .position = .{ .x = x, .y = y }, .size = .{ .x = w, .y = h }, }; } }; } comptime { @import("std").testing.refAllDecls(@This()); } /// Converts degrees to radian pub fn toRadians(deg: anytype) @TypeOf(deg) { return std.math.pi * deg / 180.0; } /// Converts radian to degree pub fn toDegrees(rad: anytype) @TypeOf(rad) { return 180.0 * rad / std.math.pi; } usingnamespace specializeOn(f32); const assert = @import("std").debug.assert; test "constructors" { const v2 = vec2(1, 2); assert(v2.x == 1); assert(v2.y == 2); const v3 = vec3(1, 2, 3); assert(v3.x == 1); assert(v3.y == 2); assert(v3.z == 3); const v4 = vec4(1, 2, 3, 4); assert(v4.x == 1); assert(v4.y == 2); assert(v4.z == 3); assert(v4.w == 4); } test "vec2 arithmetics" { const a = vec2(2, 1); const b = vec2(1, 2); assert(std.meta.eql(Vec2.add(a, b), vec2(3, 3))); assert(std.meta.eql(Vec2.sub(a, b), vec2(1, -1))); assert(std.meta.eql(Vec2.mul(a, b), vec2(2, 2))); assert(std.meta.eql(Vec2.div(a, b), vec2(2, 0.5))); assert(std.meta.eql(Vec2.scale(a, 2.0), vec2(4, 2))); assert(Vec2.dot(a, b) == 4.0); assert(Vec2.length2(a) == 5.0); assert(Vec2.length(a) == std.math.sqrt(5.0)); assert(Vec2.length(b) == std.math.sqrt(5.0)); } test "vec3 arithmetics" { const a = vec3(2, 1, 3); const b = vec3(1, 2, 3); assert(std.meta.eql(Vec3.add(a, b), vec3(3, 3, 6))); assert(std.meta.eql(Vec3.sub(a, b), vec3(1, -1, 0))); assert(std.meta.eql(Vec3.mul(a, b), vec3(2, 2, 9))); assert(std.meta.eql(Vec3.div(a, b), vec3(2, 0.5, 1))); assert(std.meta.eql(Vec3.scale(a, 2.0), vec3(4, 2, 6))); assert(Vec3.dot(a, b) == 13.0); assert(Vec3.length2(a) == 14.0); assert(Vec3.length(a) == std.math.sqrt(14.0)); assert(Vec3.length(b) == std.math.sqrt(14.0)); assert(std.meta.eql(Vec3.cross(vec3(1, 2, 3), vec3(-7, 8, 9)), vec3(-6, -30, 22))); } test "vec hashing" { const a = vec2(10, 10); const b = vec2(10, 10); const c = vec2(15, 10); assert(a.hash() == b.hash()); assert(a.hash() != c.hash()); } test "vector distance" { const a = vec2(0, 200); const b = vec2(0, 0); assert(a.distanceTo(b) == 200); } test "vec4 arithmetics" { const a = vec4(2, 1, 4, 3); const b = vec4(1, 2, 3, 4); assert(std.meta.eql(Vec4.add(a, b), vec4(3, 3, 7, 7))); assert(std.meta.eql(Vec4.sub(a, b), vec4(1, -1, 1, -1))); assert(std.meta.eql(Vec4.mul(a, b), vec4(2, 2, 12, 12))); assert(std.meta.eql(Vec4.div(a, b), vec4(2, 0.5, 4.0 / 3.0, 3.0 / 4.0))); assert(std.meta.eql(Vec4.scale(a, 2.0), vec4(4, 2, 8, 6))); assert(Vec4.dot(a, b) == 28.0); assert(Vec4.length2(a) == 30.0); assert(Vec4.length(a) == std.math.sqrt(30.0)); assert(Vec4.length(b) == std.math.sqrt(30.0)); } test "vec3 <-> vec4 interop" { const v = vec3(1, 2, 3); const pos = vec4(1, 2, 3, 1); const dir = vec4(1, 2, 3, 0); assert(std.meta.eql(Vec3.toAffinePosition(v), pos)); assert(std.meta.eql(Vec3.toAffineDirection(v), dir)); assert(std.meta.eql(Vec3.fromAffinePosition(pos), v)); assert(std.meta.eql(Vec3.fromAffineDirection(dir), v)); } // TODO: write tests for mat2, mat3 // zig fmt: off test "mat4 arithmetics" { const id = Mat4.identity; const mat = Mat4{ .fields = [4][4]f32{ // zig fmt: off [4]f32{ 1, 2, 3, 4 }, [4]f32{ 5, 6, 7, 8 }, [4]f32{ 9, 10, 11, 12 }, [4]f32{ 13, 14, 15, 16 }, // zig-fmt: on }, }; const mat_mult_by_mat_by_hand = Mat4{ .fields = [4][4]f32{ // zig fmt: off [4]f32{ 90, 100, 110, 120 }, [4]f32{ 202, 228, 254, 280 }, [4]f32{ 314, 356, 398, 440 }, [4]f32{ 426, 484, 542, 600 }, // zig-fmt: on }, }; const mat_transposed = Mat4{ .fields = [4][4]f32{ [4]f32{ 1, 5, 9, 13 }, [4]f32{ 2, 6, 10, 14 }, [4]f32{ 3, 7, 11, 15 }, [4]f32{ 4, 8, 12, 16 }, }, }; const mat_a = Mat4{ .fields = [4][4]f32{ [4]f32{ 1, 2, 3, 1 }, [4]f32{ 2, 3, 1, 2 }, [4]f32{ 3, 1, 2, 3 }, [4]f32{ 1, 2, 3, 1 }, }, }; const mat_b = Mat4{ .fields = [4][4]f32{ [4]f32{ 3, 2, 1, 3 }, [4]f32{ 2, 1, 3, 2 }, [4]f32{ 1, 3, 2, 1 }, [4]f32{ 3, 2, 1, 3 }, }, }; const mat_a_times_b = Mat4{ .fields = [4][4]f32{ [4]f32{ 13, 15, 14, 13 }, [4]f32{ 19, 14, 15, 19 }, [4]f32{ 22, 19, 13, 22 }, [4]f32{ 13, 15, 14, 13 }, }, }; const mat_b_times_a = Mat4{ .fields = [4][4]f32{ [4]f32{ 13, 19, 22, 13 }, [4]f32{ 15, 14, 19, 15 }, [4]f32{ 14, 15, 13, 14 }, [4]f32{ 13, 19, 22, 13 }, }, }; // make sure basic properties are not messed up assert(std.meta.eql(Mat4.mul(id, id), id)); assert(std.meta.eql(Mat4.mul(mat, id), mat)); assert(std.meta.eql(Mat4.mul(id, mat), mat)); assert(std.meta.eql(Mat4.mul(mat, mat), mat_mult_by_mat_by_hand)); assert(std.meta.eql(Mat4.mul(mat_a, mat_b), mat_a_times_b)); assert(std.meta.eql(Mat4.mul(mat_b, mat_a), mat_b_times_a)); assert(std.meta.eql(Mat4.transpose(mat), mat_transposed)); } // zig fmt: on test "vec4 transform" { //const id = Mat4.identity; const mat = Mat4{ .fields = [4][4]f32{ // zig fmt: off [4]f32{ 1, 2, 3, 4 }, [4]f32{ 5, 6, 7, 8 }, [4]f32{ 9, 10, 11, 12 }, [4]f32{ 13, 14, 15, 16 }, // zig-fmt: on }, }; const transform = Mat4{ .fields = [4][4]f32{ // zig fmt: off [4]f32{ 2, 0, 0, 0 }, [4]f32{ 0, 2, 0, 0 }, [4]f32{ 0, 0, 2, 0 }, [4]f32{ 10, 20, 30, 1 }, // zig-fmt: on }, }; const vec = vec4(1, 2, 3, 4); assert(std.meta.eql(Vec4.transform(vec, mat), vec4(90, 100, 110, 120))); assert(std.meta.eql(Vec4.transform(vec4(1, 2, 3, 1), transform), vec4(12, 24, 36, 1))); assert(std.meta.eql(Vec4.transform(vec4(1, 2, 3, 0), transform), vec4(2, 4, 6, 0))); } test "vec2 swizzle" { assert(std.meta.eql(vec4(0, 1, 1, 2), vec2(1, 2).swizzle("0x1y"))); assert(std.meta.eql(vec2(2, 1), vec2(1, 2).swizzle("yx"))); } test "vec3 swizzle" { assert(std.meta.eql(vec4(1, 1, 2, 3), vec3(1, 2, 3).swizzle("xxyz"))); assert(std.meta.eql(vec2(3, 3), vec3(1, 2, 3).swizzle("zz"))); } test "vec4 swizzle" { assert(std.meta.eql(vec4(3, 4, 2, 1), vec4(1, 2, 3, 4).swizzle("zwyx"))); assert(std.meta.eql(@as(f32, 3), vec4(1, 2, 3, 4).swizzle("z"))); }
src/pkg/zlm.zig
const std = @import("std"); const fs = std.fs; const constants = @import("../constants.zig"); const logger = std.log.scoped(.dx_data); const DXHeader = @import("dx_header.zig").DXHeader; const DXRecord = @import("dx_record.zig").DXRecord; /// DX Data /// See section 2.3.3 [here](https://isccp.giss.nasa.gov/pub/documents/d-doc.pdf) /// for a full description of this data format. pub const DXData = struct { header: DXHeader, records: std.ArrayList(DXRecord), pub fn readFromFile( filename: []const u8, allocator: std.mem.Allocator, ) !DXData { var filepath_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var real_filename = try std.fs.realpath(filename, &filepath_buffer); var file = try std.fs.openFileAbsolute(real_filename, .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()).reader(); return DXData.readFromReader(allocator, buf_reader); } pub fn readFromReader( allocator: std.mem.Allocator, file_reader: constants.FileReader, ) !DXData { var record_buffer = try file_reader.readBytesNoEof(constants.RECORD_SIZE); var header = try DXHeader.fromBuffer(record_buffer); var numRecords: u64 = 0; var records = std.ArrayList(DXRecord).init(allocator); while (true) { record_buffer = file_reader.readBytesNoEof(constants.RECORD_SIZE) catch break; var record = try DXRecord.fromBuffer(allocator, &record_buffer, header); try records.append(record); numRecords += 1; } logger.debug("number records: {d}", .{numRecords}); logger.debug(" value: {}", .{header}); return DXData{ .header = header, .records = records, }; } pub fn deinit(self: *DXData) void { self.header.deinit(); for (self.records) |record| { record.deinit(); } self.records.deinit(); self.* = undefined; } };
zig-dxread/src/models/dx_data.zig
const std = @import("std"); const regs = @import("../types/regs.zig"); const mmio = @import("mmio.zig"); const gpio = @import("gpio.zig"); const mbox = @import("mbox.zig"); const Register = regs.Register; //const NoError = types.errorTypes.NoError; // See page 90 of the BCM2835 manual for information about most of these. // Constants for UART0 addresses. const UART_DR = Register { .ReadWrite = mmio.MMIO_BASE + 0x00201000 }; const UART_FR = Register { .ReadOnly = mmio.MMIO_BASE + 0x00201018 }; const UART_IBRD = Register { .WriteOnly = mmio.MMIO_BASE + 0x00201024 }; const UART_FBRD = Register { .WriteOnly = mmio.MMIO_BASE + 0x00201028 }; const UART_LCRH = Register { .WriteOnly = mmio.MMIO_BASE + 0x0020102C }; const UART_CR = Register { .WriteOnly = mmio.MMIO_BASE + 0x00201030 }; const UART_IMSC = Register { .ReadOnly = mmio.MMIO_BASE + 0x00201038 }; const UART_ICR = Register { .WriteOnly = mmio.MMIO_BASE + 0x00201044 }; pub fn init() void { // Temporarily disable UART0 for config mmio.write(UART_CR, 0).?; // Setup clock mailbox call mbox.mbox[0] = 9*4; mbox.mbox[1] = mbox.MBOX_REQUEST; mbox.mbox[2] = mbox.MBOX_TAG_SETCLKRATE; mbox.mbox[3] = 12; mbox.mbox[4] = 8; mbox.mbox[5] = 2; mbox.mbox[6] = 4000000; mbox.mbox[7] = 0; mbox.mbox[8] = mbox.MBOX_TAG_LAST; mbox.mboxCall(mbox.MBOX_CH_PROP).?; var r: u32 = mmio.read(gpio.GPFSEL1).?; // Clean gpio pins 14 and 15 const val : u32 =((7 << 12) | (7 << 15)); r &=~val; // Set alt0 for pins 14 and 15. alt0 functionality on these pins is Tx/Rx // respectively for UART0. Note that alt5 on these pins is Tx/Rx for UART1. r |= (4 << 12) | (4 << 15); mmio.write(gpio.GPFSEL1, r).?; // Write zero to GPPUD to set the pull up/down state to 'neither' mmio.write(gpio.GPPUD, 0).?; mmio.wait(150); // Mark the pins that are going to be modified by writing them into GPPUDCLK0 // This makes sure that only pins 14 and 15 are set to the 'neither' state. mmio.write(gpio.GPPUDCLK0, (1 << 14) | (1 << 15)).?; mmio.wait(150); // Remove above clock for any future GPPUDCLK0 operations so they don't get // the wrong pins to modify mmio.write(gpio.GPPUDCLK0, 0).?; // Clear interrupts mmio.write(UART_ICR, 0x7FF).?; // 115200 baud mmio.write(UART_IBRD, 2).?; mmio.write(UART_FBRD, 0xB).?; mmio.write(UART_LCRH, 0b11 << 15).?; mmio.write(UART_CR, 0x301).?; } pub fn put(c: u8) void { while ((mmio.read(UART_FR).? & 0x20) != 0) {} switch (c) { '\n' => { mmio.write(UART_DR, '\n').?; mmio.write(UART_DR, '\r').?; }, '\r' => { mmio.write(UART_DR, '\n').?; mmio.write(UART_DR, '\r').?; }, else => { mmio.write(UART_DR, c).?; }, } } pub fn get() u8 { while ((mmio.read(UART_FR).? & 0x10) != 0) {} return @truncate(u8, mmio.read(UART_DR).?); } pub fn writeBytes(data: []const u8) void { for (data) |c| { put(c); } } fn uartWrite(context: void, data: []const u8) error{}!usize { _ = context; writeBytes(data); return data.len; } const UartWriter = std.io.Writer(void, error{}, uartWrite); pub const uart_writer = @as(UartWriter, .{ .context = {} }); pub fn write(comptime data: []const u8, args: anytype,) void { std.fmt.format(uart_writer, data, args) catch |e| switch (e) {}; }
kernel/src/arch/aarch64/io/uart.zig
const std = @import("std"); const Value = std.json.Value; pub const Account = struct { /// A user-friendly string to show when presenting content from this /// account. name: []const u8, /// This is true if the account belongs to the authenticated user rather /// than a group account or a personal account of another user that has /// been shared with them. is_personal: bool, /// This is true if the entire account is read-only. is_read_only: bool, // TODO see if there's a way to make this a better type. We have // types for each of the different Capabilities, but how do we get a // string hashmap to *different* capabilities? account_capabilities: std.StringHashMap(Value), }; pub const Session = struct { // TODO figure out if there is a better way of doing this /// An object specifying the capabilities of this server. Each key is /// a URI for a capability supported by the server. The value for /// each of these keys is an object with further information about the /// server's capabilities in relation to that capability. capabilities: std.StringHashMap(Value), /// A map of an account id to an Account object for each account the user /// has access to. accounts: std.AutoHashMap(types.Id, Account), /// A map of capability URIs (as found in accountCapabilities) to the /// account id that is considered to be the user's main or default account /// for data pertaining to that capability. primary_accounts: std.StringHashMap(types.Id), /// The username associated with the given credentials, or the empty string /// if none. username: []const u8, /// The URL to use for JMAP API requests. api_url: []const u8, /// The URL endpoint to use when downloading files, in URI Template /// (level 1) format [RFC 6570]. download_url: []const u8, /// The URL endpoint to use when uploading files, in URI Template (level 1) /// format [RFC 6570]. upload_url: []const u8, /// The URL to connect to for push events, as described in Section 7.3, /// in URI Template (level 1) format [RFC 6570]. event_source_url: []const u8, /// A (preferably short) string representing the state of this object on /// the server. state: []const u8, };
session.zig
usingnamespace @import("deque"); const std = @import("std"); const Thread = std.Thread; const AMOUNT: usize = 10000; test "single-threaded" { const S = struct { fn task(stealer: Stealer(usize, 32)) void { var left: usize = AMOUNT; while (stealer.steal()) |i| { std.testing.expectEqual(i + left, AMOUNT); std.testing.expectEqual(AMOUNT - i, left); left -= 1; } std.testing.expectEqual(@as(usize, 0), left); } }; var slice = try std.heap.page_allocator.alloc(u8, 1 << 24); defer std.heap.page_allocator.free(slice); var fba = std.heap.ThreadSafeFixedBufferAllocator.init(slice); var alloc = &fba.allocator; var deque = try Deque(usize, 32).new(alloc); defer deque.deinit(); var i: usize = 0; const worker = deque.worker(); while (i < AMOUNT) : (i += 1) { try worker.push(i); } const thread = try Thread.spawn(deque.stealer(), S.task); thread.wait(); } test "single-threaded-no-prealloc" { const S = struct { fn task(stealer: Stealer(usize, 0)) void { var left: usize = AMOUNT; while (stealer.steal()) |i| { std.testing.expectEqual(i + left, AMOUNT); std.testing.expectEqual(AMOUNT - i, left); left -= 1; } std.testing.expectEqual(@as(usize, 0), left); } }; var slice = try std.heap.page_allocator.alloc(u8, 1 << 24); defer std.heap.page_allocator.free(slice); var fba = std.heap.ThreadSafeFixedBufferAllocator.init(slice); var alloc = &fba.allocator; var deque = try Deque(usize, 0).new(alloc); defer deque.deinit(); var i: usize = 0; const worker = deque.worker(); while (i < AMOUNT) : (i += 1) { try worker.push(i); } const thread = try Thread.spawn(deque.stealer(), S.task); thread.wait(); } test "multiple-threads" { const S = struct { const Self = @This(); stealer: Stealer(usize, 32), data: [AMOUNT]usize = [_]usize{0} ** AMOUNT, fn task(self: *Self) void { while (self.stealer.steal()) |i| { defer std.testing.expectEqual(i, self.data[i]); self.data[i] += i; } } fn verify(self: Self) void { for (self.data[0..]) |*i, idx| { std.testing.expectEqual(idx, i.*); } } }; var slice = try std.heap.page_allocator.alloc(u8, 1 << 24); defer std.heap.page_allocator.free(slice); var fba = std.heap.ThreadSafeFixedBufferAllocator.init(slice); var alloc = &fba.allocator; var deque = try Deque(usize, 32).new(alloc); defer deque.deinit(); var i: usize = 0; const worker = deque.worker(); while (i < AMOUNT) : (i += 1) { try worker.push(i); } var threads: [4]*std.Thread = undefined; var ctx = S{ .stealer = deque.stealer(), }; for (threads) |*t| { t.* = try Thread.spawn(&ctx, S.task); } for (threads) |t| t.wait(); ctx.verify(); } test "multiple-threads-no-prealloc" { const S = struct { const Self = @This(); stealer: Stealer(usize, 0), data: [AMOUNT]usize = [_]usize{0} ** AMOUNT, fn task(self: *Self) void { while (self.stealer.steal()) |i| { defer std.testing.expectEqual(i, self.data[i]); self.data[i] += i; } } fn verify(self: Self) void { for (self.data[0..]) |*i, idx| { std.testing.expectEqual(idx, i.*); } } }; var slice = try std.heap.page_allocator.alloc(u8, 1 << 24); defer std.heap.page_allocator.free(slice); var fba = std.heap.ThreadSafeFixedBufferAllocator.init(slice); var alloc = &fba.allocator; var deque = try Deque(usize, 0).new(alloc); defer deque.deinit(); var i: usize = 0; const worker = deque.worker(); while (i < AMOUNT) : (i += 1) { try worker.push(i); } var threads: [4]*std.Thread = undefined; var ctx = S{ .stealer = deque.stealer(), }; for (threads) |*t| { t.* = try Thread.spawn(&ctx, S.task); } for (threads) |t| t.wait(); ctx.verify(); }
test/test.zig
const std = @import("std"); test "example" { const data = @embedFile("4_example.txt"); const result = try run(data); try std.testing.expectEqual(@as(u32, 1924), result); } pub fn main() !void { const data = @embedFile("4.txt"); const result = try run(data); std.debug.print("{}\n", .{result}); } fn eventualWinnerScore(bingos: []Bingo, numbers: []u8) !u32 { var remaining: usize = bingos.len; for (numbers) |n| { for (bingos) |*b| { if (b.hasWon()) continue; if (b.mark(n) and b.hasWon()) { remaining -= 1; if (remaining == 0) { return n * b.countUnmarked(); } } } } else return error.NoEventualWinnerError; } const Bingo = struct { numbers: [25]u8 = undefined, marked: u25 = 0, fn mark(self: *Bingo, number: u8) bool { for (self.numbers) |n, i| { if (n == number) { self.marked |= @as(u25, 1) << @intCast(u5, i); return true; } } else return false; } inline fn isMarked(self: Bingo, n: usize) bool { const mask = @as(u25, 1) << @intCast(u5, n); return self.marked & mask != 0; } fn hasWon(self: Bingo) bool { var rowMask = @as(u25, 0b11111); var colMask = @as(u25, 0b00001_00001_00001_00001_00001); var i: usize = 0; while (i < 5) : (i += 1) { if (self.marked & rowMask == rowMask) return true; if (self.marked & colMask == colMask) return true; rowMask <<= 5; colMask <<= 1; } else return false; } fn countUnmarked(self: Bingo) u16 { var total: u16 = 0; for (self.numbers) |n, i| { if (!self.isMarked(i)) total += n; } return total; } fn debug(self: Bingo) void { std.debug.print("== {} {}\n", .{ self.hasWon(), self.countUnmarked() }); for (self.numbers) |n, i| { if (i % 5 == 0) std.debug.print("\n", .{}); if (self.isMarked(i)) { std.debug.print("\t\x1B[4m{}\x1B[0m", .{n}); // ANSI underline } else std.debug.print("\t{}", .{n}); } std.debug.print("==\n", .{}); } }; fn run(input: []const u8) !u32 { var numbers: [100]u8 = undefined; var count: usize = 0; const newline = std.mem.indexOfScalar(u8, input, '\n') orelse return error.NumbersReadError; var ns = std.mem.split(u8, input[0..newline], ","); while (ns.next()) |n| { numbers[count] = try std.fmt.parseInt(u8, n, 10); count += 1; } var bingos: [100]Bingo = .{Bingo{}} ** 100; var bingo_count: usize = 0; var tokens = std.mem.tokenize(u8, input[newline..], "\n "); var number_count: usize = 0; while (tokens.next()) |n| { bingos[bingo_count].numbers[number_count] = try std.fmt.parseInt(u8, n, 10); number_count += 1; if (number_count == 25) { bingo_count += 1; number_count = 0; } } else if (number_count != 0) return error.IncompleteBoardError; return eventualWinnerScore(bingos[0..bingo_count], numbers[0..count]); }
shritesh+zig/4b.zig
const std = @import("std"); const mem = std.mem; const uefi = std.os.uefi; const Allocator = mem.Allocator; const Guid = uefi.Guid; pub const DevicePathProtocol = packed struct { type: DevicePathType, subtype: u8, length: u16, pub const guid align(8) = Guid{ .time_low = 0x09576e91, .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 }, }; /// Returns the next DevicePathProtocol node in the sequence, if any. pub fn next(self: *DevicePathProtocol) ?*DevicePathProtocol { if (self.type == .End and @intToEnum(EndDevicePath.Subtype, self.subtype) == .EndEntire) return null; return @ptrCast(*DevicePathProtocol, @ptrCast([*]u8, self) + self.length); } /// Calculates the total length of the device path structure in bytes, including the end of device path node. pub fn size(self: *DevicePathProtocol) usize { var node = self; while (node.next()) |next_node| { node = next_node; } return (@ptrToInt(node) + node.length) - @ptrToInt(self); } /// Creates a file device path from the existing device path and a file path. pub fn create_file_device_path(self: *DevicePathProtocol, allocator: Allocator, path: [:0]const u16) !*DevicePathProtocol { var path_size = self.size(); // 2 * (path.len + 1) for the path and its null terminator, which are u16s // DevicePathProtocol for the extra node before the end var buf = try allocator.alloc(u8, path_size + 2 * (path.len + 1) + @sizeOf(DevicePathProtocol)); mem.copy(u8, buf, @ptrCast([*]const u8, self)[0..path_size]); // Pointer to the copy of the end node of the current chain, which is - 4 from the buffer // as the end node itself is 4 bytes (type: u8 + subtype: u8 + length: u16). var new = @ptrCast(*MediaDevicePath.FilePathDevicePath, buf.ptr + path_size - 4); new.type = .Media; new.subtype = .FilePath; new.length = @sizeOf(MediaDevicePath.FilePathDevicePath) + 2 * (@intCast(u16, path.len) + 1); // The same as new.getPath(), but not const as we're filling it in. var ptr = @ptrCast([*:0]u16, @alignCast(2, @ptrCast([*]u8, new)) + @sizeOf(MediaDevicePath.FilePathDevicePath)); for (path) |s, i| ptr[i] = s; ptr[path.len] = 0; var end = @ptrCast(*EndDevicePath.EndEntireDevicePath, @ptrCast(*DevicePathProtocol, new).next().?); end.type = .End; end.subtype = .EndEntire; end.length = @sizeOf(EndDevicePath.EndEntireDevicePath); return @ptrCast(*DevicePathProtocol, buf.ptr); } pub fn getDevicePath(self: *const DevicePathProtocol) ?DevicePath { return switch (self.type) { .Hardware => blk: { const hardware: ?HardwareDevicePath = switch (@intToEnum(HardwareDevicePath.Subtype, self.subtype)) { .Pci => .{ .Pci = @ptrCast(*const HardwareDevicePath.PciDevicePath, self) }, .PcCard => .{ .PcCard = @ptrCast(*const HardwareDevicePath.PcCardDevicePath, self) }, .MemoryMapped => .{ .MemoryMapped = @ptrCast(*const HardwareDevicePath.MemoryMappedDevicePath, self) }, .Vendor => .{ .Vendor = @ptrCast(*const HardwareDevicePath.VendorDevicePath, self) }, .Controller => .{ .Controller = @ptrCast(*const HardwareDevicePath.ControllerDevicePath, self) }, .Bmc => .{ .Bmc = @ptrCast(*const HardwareDevicePath.BmcDevicePath, self) }, _ => null, }; break :blk if (hardware) |h| .{ .Hardware = h } else null; }, .Acpi => blk: { const acpi: ?AcpiDevicePath = switch (@intToEnum(AcpiDevicePath.Subtype, self.subtype)) { else => null, // TODO }; break :blk if (acpi) |a| .{ .Acpi = a } else null; }, .Messaging => blk: { const messaging: ?MessagingDevicePath = switch (@intToEnum(MessagingDevicePath.Subtype, self.subtype)) { else => null, // TODO }; break :blk if (messaging) |m| .{ .Messaging = m } else null; }, .Media => blk: { const media: ?MediaDevicePath = switch (@intToEnum(MediaDevicePath.Subtype, self.subtype)) { .HardDrive => .{ .HardDrive = @ptrCast(*const MediaDevicePath.HardDriveDevicePath, self) }, .Cdrom => .{ .Cdrom = @ptrCast(*const MediaDevicePath.CdromDevicePath, self) }, .Vendor => .{ .Vendor = @ptrCast(*const MediaDevicePath.VendorDevicePath, self) }, .FilePath => .{ .FilePath = @ptrCast(*const MediaDevicePath.FilePathDevicePath, self) }, .MediaProtocol => .{ .MediaProtocol = @ptrCast(*const MediaDevicePath.MediaProtocolDevicePath, self) }, .PiwgFirmwareFile => .{ .PiwgFirmwareFile = @ptrCast(*const MediaDevicePath.PiwgFirmwareFileDevicePath, self) }, .PiwgFirmwareVolume => .{ .PiwgFirmwareVolume = @ptrCast(*const MediaDevicePath.PiwgFirmwareVolumeDevicePath, self) }, .RelativeOffsetRange => .{ .RelativeOffsetRange = @ptrCast(*const MediaDevicePath.RelativeOffsetRangeDevicePath, self) }, .RamDisk => .{ .RamDisk = @ptrCast(*const MediaDevicePath.RamDiskDevicePath, self) }, _ => null, }; break :blk if (media) |m| .{ .Media = m } else null; }, .BiosBootSpecification => blk: { const bbs: ?BiosBootSpecificationDevicePath = switch (@intToEnum(BiosBootSpecificationDevicePath.Subtype, self.subtype)) { .BBS101 => .{ .BBS101 = @ptrCast(*const BiosBootSpecificationDevicePath.BBS101DevicePath, self) }, _ => null, }; break :blk if (bbs) |b| .{ .BiosBootSpecification = b } else null; }, .End => blk: { const end: ?EndDevicePath = switch (@intToEnum(EndDevicePath.Subtype, self.subtype)) { .EndEntire => .{ .EndEntire = @ptrCast(*const EndDevicePath.EndEntireDevicePath, self) }, .EndThisInstance => .{ .EndThisInstance = @ptrCast(*const EndDevicePath.EndThisInstanceDevicePath, self) }, _ => null, }; break :blk if (end) |e| .{ .End = e } else null; }, _ => null, }; } }; pub const DevicePath = union(DevicePathType) { Hardware: HardwareDevicePath, Acpi: AcpiDevicePath, Messaging: MessagingDevicePath, Media: MediaDevicePath, BiosBootSpecification: BiosBootSpecificationDevicePath, End: EndDevicePath, }; pub const DevicePathType = enum(u8) { Hardware = 0x01, Acpi = 0x02, Messaging = 0x03, Media = 0x04, BiosBootSpecification = 0x05, End = 0x7f, _, }; pub const HardwareDevicePath = union(Subtype) { Pci: *const PciDevicePath, PcCard: *const PcCardDevicePath, MemoryMapped: *const MemoryMappedDevicePath, Vendor: *const VendorDevicePath, Controller: *const ControllerDevicePath, Bmc: *const BmcDevicePath, pub const Subtype = enum(u8) { Pci = 1, PcCard = 2, MemoryMapped = 3, Vendor = 4, Controller = 5, Bmc = 6, _, }; pub const PciDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const PcCardDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const MemoryMappedDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const VendorDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const ControllerDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const BmcDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; }; pub const AcpiDevicePath = union(Subtype) { Acpi: void, // TODO ExpandedAcpi: void, // TODO Adr: void, // TODO Nvdimm: void, // TODO pub const Subtype = enum(u8) { Acpi = 1, ExpandedAcpi = 2, Adr = 3, Nvdimm = 4, _, }; }; pub const MessagingDevicePath = union(Subtype) { Atapi: void, // TODO Scsi: void, // TODO FibreChannel: void, // TODO FibreChannelEx: void, // TODO @"1394": void, // TODO Usb: void, // TODO Sata: void, // TODO UsbWwid: void, // TODO Lun: void, // TODO UsbClass: void, // TODO I2o: void, // TODO MacAddress: void, // TODO Ipv4: void, // TODO Ipv6: void, // TODO Vlan: void, // TODO InfiniBand: void, // TODO Uart: void, // TODO Vendor: void, // TODO pub const Subtype = enum(u8) { Atapi = 1, Scsi = 2, FibreChannel = 3, FibreChannelEx = 21, @"1394" = 4, Usb = 5, Sata = 18, UsbWwid = 16, Lun = 17, UsbClass = 15, I2o = 6, MacAddress = 11, Ipv4 = 12, Ipv6 = 13, Vlan = 20, InfiniBand = 9, Uart = 14, Vendor = 10, _, }; }; pub const MediaDevicePath = union(Subtype) { HardDrive: *const HardDriveDevicePath, Cdrom: *const CdromDevicePath, Vendor: *const VendorDevicePath, FilePath: *const FilePathDevicePath, MediaProtocol: *const MediaProtocolDevicePath, PiwgFirmwareFile: *const PiwgFirmwareFileDevicePath, PiwgFirmwareVolume: *const PiwgFirmwareVolumeDevicePath, RelativeOffsetRange: *const RelativeOffsetRangeDevicePath, RamDisk: *const RamDiskDevicePath, pub const Subtype = enum(u8) { HardDrive = 1, Cdrom = 2, Vendor = 3, FilePath = 4, MediaProtocol = 5, PiwgFirmwareFile = 6, PiwgFirmwareVolume = 7, RelativeOffsetRange = 8, RamDisk = 9, _, }; pub const HardDriveDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const CdromDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const VendorDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const FilePathDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, pub fn getPath(self: *const FilePathDevicePath) [*:0]const u16 { return @ptrCast([*:0]const u16, @alignCast(2, @ptrCast([*]const u8, self)) + @sizeOf(FilePathDevicePath)); } }; pub const MediaProtocolDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, // TODO }; pub const PiwgFirmwareFileDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; pub const PiwgFirmwareVolumeDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; pub const RelativeOffsetRangeDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, reserved: u32, start: u64, end: u64, }; pub const RamDiskDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, start: u64, end: u64, disk_type: uefi.Guid, instance: u16, }; }; pub const BiosBootSpecificationDevicePath = union(Subtype) { BBS101: *const BBS101DevicePath, pub const Subtype = enum(u8) { BBS101 = 1, _, }; pub const BBS101DevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, device_type: u16, status_flag: u16, pub fn getDescription(self: *const BBS101DevicePath) [*:0]const u8 { return @ptrCast([*:0]const u8, self) + @sizeOf(BBS101DevicePath); } }; }; pub const EndDevicePath = union(Subtype) { EndEntire: *const EndEntireDevicePath, EndThisInstance: *const EndThisInstanceDevicePath, pub const Subtype = enum(u8) { EndEntire = 0xff, EndThisInstance = 0x01, _, }; pub const EndEntireDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; pub const EndThisInstanceDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; };
lib/std/os/uefi/protocols/device_path_protocol.zig
const std = @import("std"); const ascii = std.ascii; const fmt = std.fmt; const mem = std.mem; const assert = std.debug.assert; usingnamespace @import("common.zig"); pub fn create(buffer: []u8, reader: anytype, writer: anytype) Client(@TypeOf(reader), @TypeOf(writer)) { assert(buffer.len >= 32); return Client(@TypeOf(reader), @TypeOf(writer)).init(buffer, reader, writer); } pub fn Client(comptime Reader: type, comptime Writer: type) type { const ReaderError = if (@typeInfo(Reader) == .Pointer) @typeInfo(Reader).Pointer.child.Error else Reader.Error; const WriterError = if (@typeInfo(Writer) == .Pointer) @typeInfo(Writer).Pointer.child.Error else Writer.Error; return struct { const Self = @This(); read_buffer: []u8, send_encoding: TransferEncoding = .unknown, recv_encoding: TransferEncoding = .unknown, enc_need: usize = 0, enc_read: usize = 0, reader: Reader, writer: Writer, done: bool = false, head_sent: bool = false, state: ParserState = .initial, pub fn init(buffer: []u8, reader: Reader, writer: Writer) Self { return .{ .read_buffer = buffer, .reader = reader, .writer = writer, }; } pub fn reset(self: *Self) void { self.send_encoding = .unknown; self.recv_encoding = .unknown; self.enc_need = 0; self.enc_read = 0; self.done = false; self.head_sent = false; self.state = .initial; } pub fn writeHead(self: *Self, method: []const u8, path: []const u8) WriterError!void { try self.writer.writeAll(method); try self.writer.writeAll(" "); try self.writer.writeAll(path); try self.writer.writeAll(" HTTP/1.1\r\n"); } pub fn writeHeaderValue(self: *Self, name: []const u8, value: []const u8) WriterError!void { if (ascii.eqlIgnoreCase(name, "transfer-encoding")) { self.send_encoding = .chunked; } else if (ascii.eqlIgnoreCase(name, "content-length")) { self.send_encoding = .length; } try self.writer.writeAll(name); try self.writer.writeAll(": "); try self.writer.writeAll(value); try self.writer.writeAll("\r\n"); } pub fn writeHeaderValueFormat(self: *Self, name: []const u8, comptime format: []const u8, args: anytype) WriterError!void { if (ascii.eqlIgnoreCase(name, "transfer-encoding")) { self.send_encoding = .chunked; } else if (ascii.eqlIgnoreCase(name, "content-length")) { self.send_encoding = .length; } try self.writer.print("{s}: " ++ format ++ "\r\n", .{name} ++ args); } pub fn writeHeader(self: *Self, header: Header) WriterError!void { return self.writeHeaderValue(header.name, header.value); } pub fn writeHeaders(self: *Self, array: Headers) WriterError!void { for (array) |header| { try writeHeaderValue(header.name, header.value); } } pub fn writeHeadComplete(self: *Self) WriterError!void { if (!self.head_sent) { try self.writer.writeAll("\r\n"); self.head_sent = true; } } pub fn writeChunk(self: *Self, data: ?[]const u8) WriterError!void { try self.writeHeadComplete(); switch (self.send_encoding) { .chunked => { if (data) |payload| { try fmt.formatInt(payload.len, 16, true, .{}, self.writer); try self.writer.writeAll("\r\n"); try self.writer.writeAll(payload); try self.writer.writeAll("\r\n"); } else { try self.writer.writeAll("0\r\n"); } }, .length, .unknown => { if (data) |payload| { try self.writer.writeAll(payload); } }, } } const ReadUntilError = ReaderError || error{BufferOverflow}; fn readUntilDelimiterOrEof(self: *Self, buffer: []u8, comptime delimiter: []const u8) ReadUntilError!?[]u8 { var index: usize = 0; var read_byte: [1]u8 = undefined; while (index < buffer.len) { const read_len = try self.reader.read(&read_byte); if (read_len < 1) { if (index == 0) return null; // reached end of stream but never got any data, connection closed? return buffer[0..index]; // reached end of stream but got some data. } buffer[index] = read_byte[0]; index += 1; if (index >= delimiter.len and std.mem.eql(u8, buffer[index - delimiter.len .. index], delimiter)) { return buffer[0 .. index - delimiter.len]; // found the delimiter } } return error.BufferOverflow; } fn skipUntilDelimiterOrEof(self: *Self, delimiter: u8) ReaderError!void { var read_byte: [1]u8 = undefined; while (true) { const read_len = try self.reader.read(&read_byte); if (read_len < 1) return; if (read_byte[0] == delimiter) return; } } pub const ReadError = ReadUntilError || fmt.ParseIntError; pub fn readEvent(self: *Self) ReadError!?ClientEvent { if (self.done) return null; switch (self.state) { .initial => { if (try self.readUntilDelimiterOrEof(self.read_buffer, " ")) |buffer| { if (!mem.eql(u8, buffer, "HTTP/1.1") and !mem.eql(u8, buffer, "HTTP/1.0")) { log.err("found invalid HTTP version: {s}, expected HTTP/1.1 or HTTP/1.0", .{buffer}); self.done = true; return ClientEvent{ .invalid = .{ .buffer = buffer, .message = "expected HTTP/1.1 or HTTP/1.0", .state = self.state, }, }; } } else { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } var code: u16 = 0; if (try self.readUntilDelimiterOrEof(self.read_buffer, " ")) |buffer| { if (buffer.len != 3) { log.err("found invalid HTTP response code: {s}, expected 3 digit integer", .{buffer}); self.done = true; return ClientEvent{ .invalid = .{ .buffer = buffer, .message = "expected response code to be 3 digits", .state = self.state, }, }; } code = try fmt.parseUnsigned(u16, buffer, 10); if (code < 100 or code >= 600) { log.err("found invalid HTTP response code: {s}, not in range 100 -> 599 (inclusive)", .{buffer}); self.done = true; return ClientEvent{ .invalid = .{ .buffer = buffer, .message = "expected response code to be in range 100 -> 599 (inclusive)", .state = self.state, }, }; } } else { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } if (try self.readUntilDelimiterOrEof(self.read_buffer, "\r\n")) |buffer| { self.state = .headers; return ClientEvent{ .status = .{ .code = code, .reason = buffer, }, }; } else { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } }, .headers => { if (try self.readUntilDelimiterOrEof(self.read_buffer, "\r\n")) |buffer| { if (buffer.len == 0) { self.state = .payload; return ClientEvent.head_complete; } const separator = blk: { if (mem.indexOfScalar(u8, buffer, ':')) |pos| { break :blk pos; } else { log.err("found invalid HTTP header: '{s}', missing ':' separator", .{buffer}); self.done = true; return ClientEvent{ .invalid = .{ .buffer = buffer, .message = "expected header to be separated with a ':' (colon)", .state = self.state, }, }; } }; var index = separator + 1; while (true) : (index += 1) { if (buffer[index] != ' ') break; if (index >= buffer.len) { log.err("found invalid HTTP header: '{s}', missing value after separator", .{buffer}); self.done = true; return ClientEvent{ .invalid = .{ .buffer = buffer, .message = "no header value provided", .state = self.state, }, }; } } const name = buffer[0..separator]; const value = buffer[index..]; if (ascii.eqlIgnoreCase(name, "content-length")) { self.recv_encoding = .length; self.enc_need = try fmt.parseUnsigned(usize, value, 10); } else if (ascii.eqlIgnoreCase(name, "transfer-encoding")) { if (ascii.eqlIgnoreCase(value, "chunked")) { self.recv_encoding = .chunked; } } return ClientEvent{ .header = .{ .name = name, .value = value, }, }; } else { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } }, .payload => { switch (self.recv_encoding) { .unknown => { self.done = true; return ClientEvent.end; }, .length => { const left = self.enc_need - self.enc_read; if (left <= self.read_buffer.len) { const read_len = try self.reader.readAll(self.read_buffer[0..left]); if (read_len != left) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } self.recv_encoding = .unknown; return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], .final = true, }, }; } else { const read_len = try self.reader.read(self.read_buffer); if (read_len == 0) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } self.enc_read += read_len; return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], }, }; } }, .chunked => { if (self.enc_need == 0) { if (try self.readUntilDelimiterOrEof(self.read_buffer, "\r\n")) |buffer| { const chunk_len = try fmt.parseInt(usize, buffer, 16); if (chunk_len == 0) { try self.skipUntilDelimiterOrEof('\n'); self.done = true; return ClientEvent.end; } else if (chunk_len <= self.read_buffer.len) { const read_len = try self.reader.readAll(self.read_buffer[0..chunk_len]); if (read_len != chunk_len) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } try self.skipUntilDelimiterOrEof('\n'); return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], .final = true, }, }; } else { self.enc_need = chunk_len; self.enc_read = 0; const read_len = try self.reader.read(self.read_buffer); if (read_len != 0) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } self.enc_read += read_len; return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], }, }; } } else { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } } else { const left = self.enc_need - self.enc_read; if (left <= self.read_buffer.len) { const read_len = try self.reader.readAll(self.read_buffer[0..left]); if (read_len != left) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } try self.skipUntilDelimiterOrEof('\n'); self.enc_need = 0; self.enc_read = 0; return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], .final = true, }, }; } else { const read_len = try self.reader.read(self.read_buffer); if (read_len == 0) { log.warn("connection closed abruptly while reading message", .{}); return ClientEvent.closed; } self.enc_read += read_len; return ClientEvent{ .chunk = .{ .data = self.read_buffer[0..read_len], }, }; } } }, } }, } } }; } const testing = std.testing; const io = std.io; test "decodes a simple response" { var read_buffer: [32]u8 = undefined; var the_void: [1024]u8 = undefined; var response = "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ngood"; var reader = io.fixedBufferStream(response).reader(); var writer = io.fixedBufferStream(&the_void).writer(); var client = create(&read_buffer, reader, writer); try client.writeHead("GET", "/"); try client.writeHeaderValue("Host", "localhost"); try client.writeHeaderValueFormat("Content-Length", "{d}", .{9}); try client.writeChunk("aaabbbccc"); var status = (try client.readEvent()).?; testing.expect(status == .status and status.status.code == 200); var header = (try client.readEvent()).?; testing.expect(header == .header and mem.eql(u8, header.header.name, "Content-Length") and mem.eql(u8, header.header.value, "4")); var complete = (try client.readEvent()).?; testing.expect(complete == .head_complete); var body = (try client.readEvent()).?; testing.expect(body == .chunk and mem.eql(u8, body.chunk.data, "good") and body.chunk.final); var end = (try client.readEvent()).?; testing.expect(end == .end); } test "decodes a chunked response" { var read_buffer: [32]u8 = undefined; var the_void: [1024]u8 = undefined; var response = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n0\r\n"; var reader = io.fixedBufferStream(response).reader(); var writer = io.fixedBufferStream(&the_void).writer(); var client = create(&read_buffer, reader, writer); try client.writeHead("GET", "/"); try client.writeHeader(.{ .name = "Host", .value = "localhost" }); try client.writeChunk("aaabbbccc"); var status = (try client.readEvent()).?; testing.expect(status == .status and status.status.code == 200); var header = (try client.readEvent()).?; testing.expect(header == .header and mem.eql(u8, header.header.name, "Transfer-Encoding") and mem.eql(u8, header.header.value, "chunked")); var complete = (try client.readEvent()).?; testing.expect(complete == .head_complete); var body = (try client.readEvent()).?; testing.expect(body == .chunk and mem.eql(u8, body.chunk.data, "good") and body.chunk.final); var end = (try client.readEvent()).?; testing.expect(end == .end); } test "refAllDecls" { std.meta.refAllDecls(@This()); }
lib/hzzp/src/base/client.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const test_step = b.step("test", "Runs the test suite"); const run_step = b.step("run", "Runs the linker"); const test_runner = b.addTest("src/slf.zig"); test_step.dependOn(&test_runner.step); const objdump = b.addExecutable("slf-objdump", "src/objdump.zig"); objdump.setTarget(target); objdump.setBuildMode(mode); objdump.addPackage(.{ .name = "args", .path = .{ .path = "vendor/zig-args/args.zig" }, }); objdump.install(); const ld = b.addExecutable("slf-ld", "src/ld.zig"); ld.setTarget(target); ld.setBuildMode(mode); ld.addPackage(.{ .name = "args", .path = .{ .path = "vendor/zig-args/args.zig" }, }); ld.install(); const link_run = ld.run(); if (b.args) |args| { link_run.addArgs(args); } run_step.dependOn(&link_run.step); addRunTest(test_step, ld, 1, &[_][]const u8{}); addRunTest(test_step, ld, 0, &[_][]const u8{"--help"}); addRunTest(test_step, ld, 1, &[_][]const u8{"zig-out/nonexisting.slf"}); addRunTest(test_step, ld, 1, &[_][]const u8{ "--symsize", "4", "zig-out/nonexisting.slf" }); addRunTest(test_step, ld, 1, &[_][]const u8{ "--align", "2", "zig-out/nonexisting.slf" }); addRunTest(test_step, ld, 1, &[_][]const u8{ "--base", "5", "zig-out/nonexisting.slf" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-x" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-x" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-i" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-e" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-s" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-r" }); addRunTest(test_step, objdump, 1, &[_][]const u8{ "--raw", "-d" }); addRunTest(test_step, objdump, 0, &[_][]const u8{"data/crt0.slf"}); addRunTest(test_step, objdump, 0, &[_][]const u8{ "-x", "data/crt0.slf" }); addRunTest(test_step, objdump, 0, &[_][]const u8{ "-x", "data/crt0.slf", "data/library.slf" }); } fn addRunTest(test_step: *std.build.Step, exe: *std.build.LibExeObjStep, exit_code: u8, argv: []const []const u8) void { const run = exe.run(); run.addArgs(argv); run.expected_exit_code = exit_code; if (@import("builtin").os.tag != .windows) { run.stdout_action = .ignore; run.stderr_action = .ignore; } test_step.dependOn(&run.step); }
build.zig
const std = @import("std"); pub usingnamespace std.os.windows.user32; pub usingnamespace std.os.windows.kernel32; pub const HINSTANCE = std.os.windows.HINSTANCE; pub const HWND = std.os.windows.HWND; pub const WPARAM = std.os.windows.WPARAM; pub const LPARAM = std.os.windows.LPARAM; pub const LRESULT = std.os.windows.LRESULT; pub const RECT = std.os.windows.RECT; pub const LPRECT = *RECT; pub const WINAPI = std.os.windows.WINAPI; pub const HDC = std.os.windows.HDC; pub const HBRUSH = std.os.windows.HBRUSH; pub const HFONT = *opaque {}; pub const COLORREF = std.os.windows.DWORD; pub const BOOL = std.os.windows.BOOL; pub const BYTE = std.os.windows.BYTE; pub const LONG = std.os.windows.LONG; pub const ULONG = std.os.windows.ULONG; pub const UINT = std.os.windows.UINT; pub const INT = std.os.windows.INT; pub const DWORD = std.os.windows.DWORD; pub const HGDIOBJ = *opaque {}; pub const BS_DEFPUSHBUTTON = 1; pub const BS_FLAT = 0x00008000; pub const SWP_NOACTIVATE = 0x0010; pub const SWP_NOOWNERZORDER = 0x0200; pub const SWP_NOZORDER = 0x0004; pub const BN_CLICKED = 0; pub const WNDENUMPROC = fn (hwnd: HWND, lParam: LPARAM) callconv(WINAPI) c_int; pub extern "user32" fn SetParent(child: HWND, newParent: HWND) callconv(WINAPI) HWND; pub extern "user32" fn SetWindowTextW(hWnd: HWND, lpString: [*:0]const u16) callconv(WINAPI) c_int; pub extern "user32" fn GetWindowTextW(hWnd: HWND, lpString: [*:0]const u16, nMaxCount: c_int) callconv(WINAPI) c_int; pub extern "user32" fn GetWindowTextLengthW(hWnd: HWND) callconv(WINAPI) c_int; pub extern "user32" fn EnumChildWindows(hWndParent: HWND, lpEnumFunc: WNDENUMPROC, lParam: LPARAM) callconv(WINAPI) c_int; pub extern "user32" fn GetParent(hWnd: HWND) callconv(WINAPI) HWND; pub extern "user32" fn GetWindowRect(hWnd: HWND, lpRect: LPRECT) callconv(WINAPI) c_int; pub extern "user32" fn GetClientRect(hWnd: HWND, lpRect: LPRECT) callconv(WINAPI) c_int; pub extern "user32" fn SetWindowPos(hWnd: HWND, hWndInsertAfter: HWND, X: c_int, Y: c_int, cx: c_int, cy: c_int, uFlags: c_uint) callconv(WINAPI) c_int; pub extern "user32" fn MoveWindow(hWnd: HWND, X: c_int, Y: c_int, nWidth: c_int, nHeight: c_int, repaint: c_int) callconv(WINAPI) c_int; pub extern "user32" fn BeginPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) callconv(WINAPI) HDC; pub extern "user32" fn EndPaint(hWnd: HWND, lpPaint: *const PAINTSTRUCT) callconv(WINAPI) BOOL; pub extern "gdi32" fn CreateSolidBrush(color: COLORREF) callconv(WINAPI) ?HBRUSH; pub extern "gdi32" fn DeleteObject(ho: HGDIOBJ) callconv(WINAPI) BOOL; pub extern "gdi32" fn SelectObject(hdc: HDC, h: HGDIOBJ) callconv(WINAPI) void; pub extern "gdi32" fn Rectangle(hdc: HDC, left: c_int, top: c_int, right: c_int, bottom: c_int) callconv(WINAPI) BOOL; pub extern "gdi32" fn Ellipse(hdc: HDC, left: c_int, top: c_int, right: c_int, bottom: c_int) callconv(WINAPI) BOOL; pub extern "gdi32" fn ExtTextOutA(hdc: HDC, x: c_int, y: c_int, options: UINT, lprect: ?*const RECT, lpString: [*]const u8, c: UINT, lpDx: ?*const INT) callconv(WINAPI) BOOL; pub extern "gdi32" fn GetTextExtentPoint32A(hdc: HDC, lpString: [*]const u8, c: c_int, psizl: *SIZE) callconv(WINAPI) BOOL; pub extern "gdi32" fn CreateFontA(cHeight: c_int, cWidth: c_int, cEscapement: c_int, cOrientation: c_int, cWeight: c_int, bItalic: DWORD, bUnderline: DWORD, bStrikeOut: DWORD, iCharSet: DWORD, iOutPrecision: DWORD, iClipPrecision: DWORD, iQuality: DWORD, iPitchAndFamily: DWORD, pszFaceName: std.os.windows.LPCSTR) callconv(WINAPI) ?HFONT; pub extern "gdi32" fn GetStockObject(i: c_int) callconv(WINAPI) HGDIOBJ; pub extern "gdi32" fn CreateCompatibleDC(hdc: ?HDC) callconv(WINAPI) ?HDC; pub extern "gdi32" fn SetDCBrushColor(hdc: HDC, color: COLORREF) callconv(WINAPI) COLORREF; pub extern "gdi32" fn GetDCBrushColor(hdc: HDC) callconv(WINAPI) COLORREF; pub extern "gdi32" fn SetTextColor(hdc: HDC, color: COLORREF) callconv(WINAPI) COLORREF; pub extern "gdi32" fn GetSysColorBrush(nIndex: c_int) callconv(WINAPI) ?HBRUSH; pub extern "gdi32" fn MoveToEx(hdc: HDC, x: c_int, y: c_int, lppt: ?*POINT) callconv(WINAPI) BOOL; pub extern "gdi32" fn LineTo(hdc: HDC, x: c_int, y: c_int) callconv(WINAPI) BOOL; pub extern "user32" fn GetWindowRgnBox(hWnd: HWND, lprc: LPRECT) callconv(WINAPI) c_int; pub extern "user32" fn InvalidateRect(hWnd: HWND, lpRect: *const RECT, bErase: BOOL) callconv(WINAPI) BOOL; pub extern "user32" fn GetWindowExtEx(hdc: HDC, lpsize: *SIZE) callconv(WINAPI) BOOL; // stock objects constants pub const WHITE_BRUSH = 0; pub const LTGRAY_BRUSH = 1; pub const GRAY_BRUSH = 2; pub const DKGRAY_BRUSH = 3; pub const BLACK_BRUSH = 4; pub const NULL_BRUSH = 5; pub const WHITE_PEN = 6; pub const BLACK_PEN = 7; pub const NULL_PEN = 8; pub const OEM_FIXED_FONT = 10; pub const ANSI_FIXED_FONT = 11; pub const ANSI_VAR_FONT = 12; pub const SYSTEM_FONT = 13; pub const DEVICE_DEFAULT_FONT = 14; pub const DEFAULT_PALETTE = 15; pub const SYSTEM_FIXED_FONT = 16; pub const DEFAULT_GUI_FONT = 17; pub const DC_BRUSH = 18; pub const DC_PEN = 19; // font weights pub const FW_DONTCARE = 0; pub const FW_THIN = 100; pub const FW_LIGHT = 300; pub const FW_NORMAL = 400; pub const FW_BOLD = 700; // system colors constants (only those that are also supported on Windows 10 are present) pub const COLOR_WINDOW = 5; pub const COLOR_WINDOWTEXT = 6; pub const COLOR_HIGHLIGHT = 13; pub const COLOR_HIGHLIGHTTEXT = 14; pub const COLOR_3DFACE = 15; pub const COLOR_GRAYTEXT = 17; pub const COLOR_BTNTEXT = 18; pub const COLOR_HOTLIGHT = 26; // Common Controls pub extern "comctl32" fn InitCommonControlsEx(picce: [*c]const INITCOMMONCONTROLSEX) callconv(WINAPI) c_int; pub const INITCOMMONCONTROLSEX = extern struct { dwSize: c_uint, dwICC: c_uint }; // zig fmt: off pub const PAINTSTRUCT = extern struct { hdc: HDC, fErase: BOOL, rcPaint: RECT, fRestore: BOOL, fIncUpdate: BOOL, rgbReserved: [32]BYTE }; // zig fmt: on pub const POINT = extern struct { x: LONG, y: LONG }; pub const SIZE = extern struct { cx: std.os.windows.LONG, cy: std.os.windows.LONG }; pub fn GetWindowLongPtr(hWnd: HWND, nIndex: c_int) usize { switch (@import("builtin").cpu.arch) { .x86_64 => return @bitCast(usize, std.os.windows.user32.GetWindowLongPtrA(hWnd, nIndex)), .i386 => return @bitCast(usize, std.os.windows.user32.GetWindowLongA(hWnd, nIndex)), else => @compileError("Unsupported architecture."), } } pub fn SetWindowLongPtr(hWnd: HWND, nIndex: c_int, dwNewLong: usize) void { switch (@import("builtin").cpu.arch) { .x86_64 => _ = std.os.windows.user32.SetWindowLongPtrA(hWnd, nIndex, @bitCast(isize, dwNewLong)), .i386 => _ = std.os.windows.user32.SetWindowLongA(hWnd, nIndex, @bitCast(isize, dwNewLong)), else => @compileError("Unsupported architecture."), } } pub const ICC_STANDARD_CLASSES = 0x00004000; // GDI+ part, based on https://docs.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-flatapi-flat pub const GpGraphics = *opaque {}; pub const GpStatus = enum(c_int) { Ok, GenericError, InvalidParameter, OutOfMemory, ObjectBusy, InsufficientBuffer, NotImplemented, Win32Error, WrongState, Aborted, FileNotFound, ValueOverflow, AccessDenied, UnknownImageFormat, FontFamilyNotFound, FontStyleNotFound, NotTrueTypeFont, UnsupportedGdiplusVersion, GdiplusNotInitialized, PropertyNotFound, PropertyNotSupported, ProfileNotFound }; pub const DebugEventLevel = enum(c_int) { DebugEventLevelFatal, DebugEventLevelWarning }; pub const DebugEventProc = fn (level: DebugEventLevel, message: [*]const u8) callconv(.C) void; pub const GdiplusStartupInput = extern struct { GdiplusVersion: u32 = 1, DebugEventCallback: ?DebugEventProc = null, SuppressBackgroundThread: BOOL = 0, SuppressExternalCodecs: BOOL = 0, GdiplusStartupInput: ?fn (debugEventCallback: DebugEventProc, suppressBackgroundThread: BOOL, supressExternalCodecs: BOOL) callconv(.C) void = null }; pub const GdiplusStartupOutput = extern struct { NotificationHookProc: fn () callconv(.C) void, // TODO NotificationUnhookProc: fn () callconv(.C) void, // TODO }; pub extern "gdiplus" fn GdipCreateFromHDC(hdc: HDC, graphics: *GpGraphics) GpStatus; pub extern "gdiplus" fn GdiplusStartup(token: *ULONG, input: ?*GdiplusStartupInput, output: ?*GdiplusStartupOutput) GpStatus; pub extern "gdiplus" fn GdiplusShutdown(token: *ULONG) void;
src/backends/win32/win32.zig
pub const SYS_syscall = 0; pub const SYS_exit = 1; pub const SYS_fork = 2; pub const SYS_read = 3; pub const SYS_write = 4; pub const SYS_open = 5; pub const SYS_close = 6; pub const SYS_wait4 = 7; // 8 is old creat pub const SYS_link = 9; pub const SYS_unlink = 10; // 11 is obsolete execv pub const SYS_chdir = 12; pub const SYS_fchdir = 13; pub const SYS_freebsd11_mknod = 14; pub const SYS_chmod = 15; pub const SYS_chown = 16; pub const SYS_break = 17; // 18 is freebsd4 getfsstat // 19 is old lseek pub const SYS_getpid = 20; pub const SYS_mount = 21; pub const SYS_unmount = 22; pub const SYS_setuid = 23; pub const SYS_getuid = 24; pub const SYS_geteuid = 25; pub const SYS_ptrace = 26; pub const SYS_recvmsg = 27; pub const SYS_sendmsg = 28; pub const SYS_recvfrom = 29; pub const SYS_accept = 30; pub const SYS_getpeername = 31; pub const SYS_getsockname = 32; pub const SYS_access = 33; pub const SYS_chflags = 34; pub const SYS_fchflags = 35; pub const SYS_sync = 36; pub const SYS_kill = 37; // 38 is old stat pub const SYS_getppid = 39; // 40 is old lstat pub const SYS_dup = 41; pub const SYS_freebsd10_pipe = 42; pub const SYS_getegid = 43; pub const SYS_profil = 44; pub const SYS_ktrace = 45; // 46 is old sigaction pub const SYS_getgid = 47; // 48 is old sigprocmask pub const SYS_getlogin = 49; pub const SYS_setlogin = 50; pub const SYS_acct = 51; // 52 is old sigpending pub const SYS_sigaltstack = 53; pub const SYS_ioctl = 54; pub const SYS_reboot = 55; pub const SYS_revoke = 56; pub const SYS_symlink = 57; pub const SYS_readlink = 58; pub const SYS_execve = 59; pub const SYS_umask = 60; pub const SYS_chroot = 61; // 62 is old fstat // 63 is old getkerninfo // 64 is old getpagesize pub const SYS_msync = 65; pub const SYS_vfork = 66; // 67 is obsolete vread // 68 is obsolete vwrite // 69 is obsolete sbrk (still present on some platforms) pub const SYS_sstk = 70; // 71 is old mmap pub const SYS_vadvise = 72; pub const SYS_munmap = 73; pub const SYS_mprotect = 74; pub const SYS_madvise = 75; // 76 is obsolete vhangup // 77 is obsolete vlimit pub const SYS_mincore = 78; pub const SYS_getgroups = 79; pub const SYS_setgroups = 80; pub const SYS_getpgrp = 81; pub const SYS_setpgid = 82; pub const SYS_setitimer = 83; // 84 is old wait pub const SYS_swapon = 85; pub const SYS_getitimer = 86; // 87 is old gethostname // 88 is old sethostname pub const SYS_getdtablesize = 89; pub const SYS_dup2 = 90; pub const SYS_fcntl = 92; pub const SYS_select = 93; pub const SYS_fsync = 95; pub const SYS_setpriority = 96; pub const SYS_socket = 97; pub const SYS_connect = 98; // 99 is old accept pub const SYS_getpriority = 100; // 101 is old send // 102 is old recv // 103 is old sigreturn pub const SYS_bind = 104; pub const SYS_setsockopt = 105; pub const SYS_listen = 106; // 107 is obsolete vtimes // 108 is old sigvec // 109 is old sigblock // 110 is old sigsetmask // 111 is old sigsuspend // 112 is old sigstack // 113 is old recvmsg // 114 is old sendmsg // 115 is obsolete vtrace pub const SYS_gettimeofday = 116; pub const SYS_getrusage = 117; pub const SYS_getsockopt = 118; pub const SYS_readv = 120; pub const SYS_writev = 121; pub const SYS_settimeofday = 122; pub const SYS_fchown = 123; pub const SYS_fchmod = 124; // 125 is old recvfrom pub const SYS_setreuid = 126; pub const SYS_setregid = 127; pub const SYS_rename = 128; // 129 is old truncate // 130 is old ftruncate pub const SYS_flock = 131; pub const SYS_mkfifo = 132; pub const SYS_sendto = 133; pub const SYS_shutdown = 134; pub const SYS_socketpair = 135; pub const SYS_mkdir = 136; pub const SYS_rmdir = 137; pub const SYS_utimes = 138; // 139 is obsolete 4.2 sigreturn pub const SYS_adjtime = 140; // 141 is old getpeername // 142 is old gethostid // 143 is old sethostid // 144 is old getrlimit // 145 is old setrlimit // 146 is old killpg pub const SYS_setsid = 147; pub const SYS_quotactl = 148; // 149 is old quota // 150 is old getsockname pub const SYS_nlm_syscall = 154; pub const SYS_nfssvc = 155; // 156 is old getdirentries // 157 is freebsd4 statfs // 158 is freebsd4 fstatfs pub const SYS_lgetfh = 160; pub const SYS_getfh = 161; // 162 is freebsd4 getdomainname // 163 is freebsd4 setdomainname // 164 is freebsd4 uname pub const SYS_sysarch = 165; pub const SYS_rtprio = 166; pub const SYS_semsys = 169; pub const SYS_msgsys = 170; pub const SYS_shmsys = 171; // 173 is freebsd6 pread // 174 is freebsd6 pwrite pub const SYS_setfib = 175; pub const SYS_ntp_adjtime = 176; pub const SYS_setgid = 181; pub const SYS_setegid = 182; pub const SYS_seteuid = 183; // 184 is obsolete lfs_bmapv // 185 is obsolete lfs_markv // 186 is obsolete lfs_segclean // 187 is obsolete lfs_segwait pub const SYS_freebsd11_stat = 188; pub const SYS_freebsd11_fstat = 189; pub const SYS_freebsd11_lstat = 190; pub const SYS_pathconf = 191; pub const SYS_fpathconf = 192; pub const SYS_getrlimit = 194; pub const SYS_setrlimit = 195; pub const SYS_freebsd11_getdirentries = 196; // 197 is freebsd6 mmap pub const SYS___syscall = 198; // 199 is freebsd6 lseek // 200 is freebsd6 truncate // 201 is freebsd6 ftruncate pub const SYS___sysctl = 202; pub const SYS_mlock = 203; pub const SYS_munlock = 204; pub const SYS_undelete = 205; pub const SYS_futimes = 206; pub const SYS_getpgid = 207; pub const SYS_poll = 209; pub const SYS_freebsd7___semctl = 220; pub const SYS_semget = 221; pub const SYS_semop = 222; pub const SYS_freebsd7_msgctl = 224; pub const SYS_msgget = 225; pub const SYS_msgsnd = 226; pub const SYS_msgrcv = 227; pub const SYS_shmat = 228; pub const SYS_freebsd7_shmctl = 229; pub const SYS_shmdt = 230; pub const SYS_shmget = 231; pub const SYS_clock_gettime = 232; pub const SYS_clock_settime = 233; pub const SYS_clock_getres = 234; pub const SYS_ktimer_create = 235; pub const SYS_ktimer_delete = 236; pub const SYS_ktimer_settime = 237; pub const SYS_ktimer_gettime = 238; pub const SYS_ktimer_getoverrun = 239; pub const SYS_nanosleep = 240; pub const SYS_ffclock_getcounter = 241; pub const SYS_ffclock_setestimate = 242; pub const SYS_ffclock_getestimate = 243; pub const SYS_clock_nanosleep = 244; pub const SYS_clock_getcpuclockid2 = 247; pub const SYS_ntp_gettime = 248; pub const SYS_minherit = 250; pub const SYS_rfork = 251; // 252 is obsolete openbsd_poll pub const SYS_issetugid = 253; pub const SYS_lchown = 254; pub const SYS_aio_read = 255; pub const SYS_aio_write = 256; pub const SYS_lio_listio = 257; pub const SYS_freebsd11_getdents = 272; pub const SYS_lchmod = 274; // 275 is obsolete netbsd_lchown pub const SYS_lutimes = 276; // 277 is obsolete netbsd_msync pub const SYS_freebsd11_nstat = 278; pub const SYS_freebsd11_nfstat = 279; pub const SYS_freebsd11_nlstat = 280; pub const SYS_preadv = 289; pub const SYS_pwritev = 290; // 297 is freebsd4 fhstatfs pub const SYS_fhopen = 298; pub const SYS_freebsd11_fhstat = 299; pub const SYS_modnext = 300; pub const SYS_modstat = 301; pub const SYS_modfnext = 302; pub const SYS_modfind = 303; pub const SYS_kldload = 304; pub const SYS_kldunload = 305; pub const SYS_kldfind = 306; pub const SYS_kldnext = 307; pub const SYS_kldstat = 308; pub const SYS_kldfirstmod = 309; pub const SYS_getsid = 310; pub const SYS_setresuid = 311; pub const SYS_setresgid = 312; // 313 is obsolete signanosleep pub const SYS_aio_return = 314; pub const SYS_aio_suspend = 315; pub const SYS_aio_cancel = 316; pub const SYS_aio_error = 317; // 318 is freebsd6 aio_read // 319 is freebsd6 aio_write // 320 is freebsd6 lio_listio pub const SYS_yield = 321; // 322 is obsolete thr_sleep // 323 is obsolete thr_wakeup pub const SYS_mlockall = 324; pub const SYS_munlockall = 325; pub const SYS___getcwd = 326; pub const SYS_sched_setparam = 327; pub const SYS_sched_getparam = 328; pub const SYS_sched_setscheduler = 329; pub const SYS_sched_getscheduler = 330; pub const SYS_sched_yield = 331; pub const SYS_sched_get_priority_max = 332; pub const SYS_sched_get_priority_min = 333; pub const SYS_sched_rr_get_interval = 334; pub const SYS_utrace = 335; // 336 is freebsd4 sendfile pub const SYS_kldsym = 337; pub const SYS_jail = 338; pub const SYS_nnpfs_syscall = 339; pub const SYS_sigprocmask = 340; pub const SYS_sigsuspend = 341; // 342 is freebsd4 sigaction pub const SYS_sigpending = 343; // 344 is freebsd4 sigreturn pub const SYS_sigtimedwait = 345; pub const SYS_sigwaitinfo = 346; pub const SYS___acl_get_file = 347; pub const SYS___acl_set_file = 348; pub const SYS___acl_get_fd = 349; pub const SYS___acl_set_fd = 350; pub const SYS___acl_delete_file = 351; pub const SYS___acl_delete_fd = 352; pub const SYS___acl_aclcheck_file = 353; pub const SYS___acl_aclcheck_fd = 354; pub const SYS_extattrctl = 355; pub const SYS_extattr_set_file = 356; pub const SYS_extattr_get_file = 357; pub const SYS_extattr_delete_file = 358; pub const SYS_aio_waitcomplete = 359; pub const SYS_getresuid = 360; pub const SYS_getresgid = 361; pub const SYS_kqueue = 362; pub const SYS_freebsd11_kevent = 363; // 364 is obsolete __cap_get_proc // 365 is obsolete __cap_set_proc // 366 is obsolete __cap_get_fd // 367 is obsolete __cap_get_file // 368 is obsolete __cap_set_fd // 369 is obsolete __cap_set_file pub const SYS_extattr_set_fd = 371; pub const SYS_extattr_get_fd = 372; pub const SYS_extattr_delete_fd = 373; pub const SYS___setugid = 374; pub const SYS_eaccess = 376; pub const SYS_afs3_syscall = 377; pub const SYS_nmount = 378; // 379 is obsolete kse_exit // 380 is obsolete kse_wakeup // 381 is obsolete kse_create // 382 is obsolete kse_thr_interrupt // 383 is obsolete kse_release pub const SYS___mac_get_proc = 384; pub const SYS___mac_set_proc = 385; pub const SYS___mac_get_fd = 386; pub const SYS___mac_get_file = 387; pub const SYS___mac_set_fd = 388; pub const SYS___mac_set_file = 389; pub const SYS_kenv = 390; pub const SYS_lchflags = 391; pub const SYS_uuidgen = 392; pub const SYS_sendfile = 393; pub const SYS_mac_syscall = 394; pub const SYS_freebsd11_getfsstat = 395; pub const SYS_freebsd11_statfs = 396; pub const SYS_freebsd11_fstatfs = 397; pub const SYS_freebsd11_fhstatfs = 398; pub const SYS_ksem_close = 400; pub const SYS_ksem_post = 401; pub const SYS_ksem_wait = 402; pub const SYS_ksem_trywait = 403; pub const SYS_ksem_init = 404; pub const SYS_ksem_open = 405; pub const SYS_ksem_unlink = 406; pub const SYS_ksem_getvalue = 407; pub const SYS_ksem_destroy = 408; pub const SYS___mac_get_pid = 409; pub const SYS___mac_get_link = 410; pub const SYS___mac_set_link = 411; pub const SYS_extattr_set_link = 412; pub const SYS_extattr_get_link = 413; pub const SYS_extattr_delete_link = 414; pub const SYS___mac_execve = 415; pub const SYS_sigaction = 416; pub const SYS_sigreturn = 417; pub const SYS_getcontext = 421; pub const SYS_setcontext = 422; pub const SYS_swapcontext = 423; pub const SYS_swapoff = 424; pub const SYS___acl_get_link = 425; pub const SYS___acl_set_link = 426; pub const SYS___acl_delete_link = 427; pub const SYS___acl_aclcheck_link = 428; pub const SYS_sigwait = 429; pub const SYS_thr_create = 430; pub const SYS_thr_exit = 431; pub const SYS_thr_self = 432; pub const SYS_thr_kill = 433; pub const SYS_jail_attach = 436; pub const SYS_extattr_list_fd = 437; pub const SYS_extattr_list_file = 438; pub const SYS_extattr_list_link = 439; // 440 is obsolete kse_switchin pub const SYS_ksem_timedwait = 441; pub const SYS_thr_suspend = 442; pub const SYS_thr_wake = 443; pub const SYS_kldunloadf = 444; pub const SYS_audit = 445; pub const SYS_auditon = 446; pub const SYS_getauid = 447; pub const SYS_setauid = 448; pub const SYS_getaudit = 449; pub const SYS_setaudit = 450; pub const SYS_getaudit_addr = 451; pub const SYS_setaudit_addr = 452; pub const SYS_auditctl = 453; pub const SYS__umtx_op = 454; pub const SYS_thr_new = 455; pub const SYS_sigqueue = 456; pub const SYS_kmq_open = 457; pub const SYS_kmq_setattr = 458; pub const SYS_kmq_timedreceive = 459; pub const SYS_kmq_timedsend = 460; pub const SYS_kmq_notify = 461; pub const SYS_kmq_unlink = 462; pub const SYS_abort2 = 463; pub const SYS_thr_set_name = 464; pub const SYS_aio_fsync = 465; pub const SYS_rtprio_thread = 466; pub const SYS_sctp_peeloff = 471; pub const SYS_sctp_generic_sendmsg = 472; pub const SYS_sctp_generic_sendmsg_iov = 473; pub const SYS_sctp_generic_recvmsg = 474; pub const SYS_pread = 475; pub const SYS_pwrite = 476; pub const SYS_mmap = 477; pub const SYS_lseek = 478; pub const SYS_truncate = 479; pub const SYS_ftruncate = 480; pub const SYS_thr_kill2 = 481; pub const SYS_shm_open = 482; pub const SYS_shm_unlink = 483; pub const SYS_cpuset = 484; pub const SYS_cpuset_setid = 485; pub const SYS_cpuset_getid = 486; pub const SYS_cpuset_getaffinity = 487; pub const SYS_cpuset_setaffinity = 488; pub const SYS_faccessat = 489; pub const SYS_fchmodat = 490; pub const SYS_fchownat = 491; pub const SYS_fexecve = 492; pub const SYS_freebsd11_fstatat = 493; pub const SYS_futimesat = 494; pub const SYS_linkat = 495; pub const SYS_mkdirat = 496; pub const SYS_mkfifoat = 497; pub const SYS_freebsd11_mknodat = 498; pub const SYS_openat = 499; pub const SYS_readlinkat = 500; pub const SYS_renameat = 501; pub const SYS_symlinkat = 502; pub const SYS_unlinkat = 503; pub const SYS_posix_openpt = 504; pub const SYS_gssd_syscall = 505; pub const SYS_jail_get = 506; pub const SYS_jail_set = 507; pub const SYS_jail_remove = 508; pub const SYS_closefrom = 509; pub const SYS___semctl = 510; pub const SYS_msgctl = 511; pub const SYS_shmctl = 512; pub const SYS_lpathconf = 513; // 514 is obsolete cap_new pub const SYS___cap_rights_get = 515; pub const SYS_cap_enter = 516; pub const SYS_cap_getmode = 517; pub const SYS_pdfork = 518; pub const SYS_pdkill = 519; pub const SYS_pdgetpid = 520; pub const SYS_pselect = 522; pub const SYS_getloginclass = 523; pub const SYS_setloginclass = 524; pub const SYS_rctl_get_racct = 525; pub const SYS_rctl_get_rules = 526; pub const SYS_rctl_get_limits = 527; pub const SYS_rctl_add_rule = 528; pub const SYS_rctl_remove_rule = 529; pub const SYS_posix_fallocate = 530; pub const SYS_posix_fadvise = 531; pub const SYS_wait6 = 532; pub const SYS_cap_rights_limit = 533; pub const SYS_cap_ioctls_limit = 534; pub const SYS_cap_ioctls_get = 535; pub const SYS_cap_fcntls_limit = 536; pub const SYS_cap_fcntls_get = 537; pub const SYS_bindat = 538; pub const SYS_connectat = 539; pub const SYS_chflagsat = 540; pub const SYS_accept4 = 541; pub const SYS_pipe2 = 542; pub const SYS_aio_mlock = 543; pub const SYS_procctl = 544; pub const SYS_ppoll = 545; pub const SYS_futimens = 546; pub const SYS_utimensat = 547; // 548 is obsolete numa_getaffinity // 549 is obsolete numa_setaffinity pub const SYS_fdatasync = 550; pub const SYS_fstat = 551; pub const SYS_fstatat = 552; pub const SYS_fhstat = 553; pub const SYS_getdirentries = 554; pub const SYS_statfs = 555; pub const SYS_fstatfs = 556; pub const SYS_getfsstat = 557; pub const SYS_fhstatfs = 558; pub const SYS_mknodat = 559; pub const SYS_kevent = 560; pub const SYS_cpuset_getdomain = 561; pub const SYS_cpuset_setdomain = 562; pub const SYS_getrandom = 563; pub const SYS_MAXSYSCALL = 564;
std/os/freebsd/syscall.zig
const builtin = @import("builtin"); const std = @import("std"); const os = std.os; pub const iovec = if (builtin.link_libc) @cImport({ @cInclude("sys/uio.h"); }).iovec else extern struct { iov_base: *c_void, iov_len: usize, }; pub const readv = if (builtin.is_test) testable_readv else real_readv; fn real_readv(pid: os.pid_t, buffer: []u8, remote_addr: usize) !usize { var local_iov = iovec{ .iov_base = @ptrCast(*c_void, buffer), .iov_len = buffer.len }; var remote_iov = iovec{ .iov_base = @intToPtr(*c_void, remote_addr), .iov_len = buffer.len }; var write_array = [_]iovec{local_iov}; var read_array = [_]iovec{remote_iov}; const result = os.linux.syscall6( os.SYS.process_vm_readv, @intCast(usize, pid), @ptrToInt(&write_array), write_array.len, @ptrToInt(&read_array), read_array.len, 0, ); try handleError(result); return result; } /// Instead of reading memory from an active process, /// this function reads from the 'value_for_buffer' variable. /// This is automatically used when zig is running tests. fn testable_readv(unused: os.pid_t, buffer: []u8, value_for_buffer: anytype) !usize { const value_as_bytes = std.mem.asBytes(&value_for_buffer); if (value_as_bytes.len > buffer.len and value_as_bytes[buffer.len] != 0) return error.ReadvTestError; for (buffer) |*i, n| i.* = value_as_bytes[n]; return buffer.len; } fn handleError(result: usize) !void { const err = os.errno(result); return switch (err) { 0 => {}, os.EFAULT => error.InvalidMemorySpace, os.EINVAL => error.EINVAL, os.ENOMEM => error.MemoryError, os.EPERM => error.InsufficientPermission, os.ESRCH => error.NoPIDExists, else => error.UnknownPVReadvError, }; } pub fn writev(pid: os.pid_t, buffer: []u8, remote_addr: usize) !usize { var local_iov = iovec{ .iov_base = @ptrCast(*c_void, buffer), .iov_len = buffer.len }; var remote_iov = iovec{ .iov_base = @intToPtr(*c_void, remote_addr), .iov_len = buffer.len }; var read_array = [_]iovec{local_iov}; var write_array = [_]iovec{remote_iov}; const result = os.linux.syscall6( os.SYS.process_vm_writev, // Syscall expects pid_t, zig fn expects usize. @intCast(usize, pid), @ptrToInt(&read_array), write_array.len, @ptrToInt(&write_array), read_array.len, 0, ); try handleError(result); return result; }
src/c.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const File = std.fs.File; const LinenoiseState = @import("state.zig").LinenoiseState; pub const History = @import("history.zig").History; const term = @import("term.zig"); const isUnsupportedTerm = term.isUnsupportedTerm; const enableRawMode = term.enableRawMode; const disableRawMode = term.disableRawMode; const getColumns = term.getColumns; pub const HintsCallback = (fn (Allocator, []const u8) Allocator.Error!?[]const u8); pub const CompletionsCallback = (fn (Allocator, []const u8) Allocator.Error![]const []const u8); const key_null = 0; const key_ctrl_a = 1; const key_ctrl_b = 2; const key_ctrl_c = 3; const key_ctrl_d = 4; const key_ctrl_e = 5; const key_ctrl_f = 6; const key_ctrl_h = 8; const key_tab = 9; const key_ctrl_k = 11; const key_ctrl_l = 12; const key_enter = 13; const key_ctrl_n = 14; const key_ctrl_p = 16; const key_ctrl_t = 20; const key_ctrl_u = 21; const key_ctrl_w = 23; const key_esc = 27; const key_backspace = 127; fn linenoiseEdit(ln: *Linenoise, in: File, out: File, prompt: []const u8) !?[]const u8 { var state = LinenoiseState.init(ln, in, out, prompt); defer state.buf.deinit(state.allocator); try state.ln.history.add(""); state.ln.history.current = state.ln.history.hist.items.len - 1; try state.refreshLine(); while (true) { var input_buf: [1]u8 = undefined; if ((try in.read(&input_buf)) < 1) return null; var c = input_buf[0]; // Browse completions before editing if (c == key_tab) { if (try state.browseCompletions()) |new_c| { c = new_c; } } switch (c) { key_null, key_tab => {}, key_ctrl_a => try state.editMoveHome(), key_ctrl_b => try state.editMoveLeft(), key_ctrl_c => return error.CtrlC, key_ctrl_d => { if (state.buf.items.len > 0) { try state.editDelete(); } else { state.ln.history.pop(); return null; } }, key_ctrl_e => try state.editMoveEnd(), key_ctrl_f => try state.editMoveRight(), key_ctrl_k => try state.editKillLineForward(), key_ctrl_l => { try term.clearScreen(); try state.refreshLine(); }, key_enter => { state.ln.history.pop(); return try ln.allocator.dupe(u8, state.buf.items); }, key_ctrl_n => try state.editHistoryNext(.next), key_ctrl_p => try state.editHistoryNext(.prev), key_ctrl_t => try state.editSwapPrev(), key_ctrl_u => try state.editKillLineBackward(), key_ctrl_w => try state.editDeletePrevWord(), key_esc => { if ((try in.read(&input_buf)) < 1) return null; switch (input_buf[0]) { 'b' => try state.editMoveWordStart(), 'f' => try state.editMoveWordEnd(), '[' => { if ((try in.read(&input_buf)) < 1) return null; switch (input_buf[0]) { '0'...'9' => { const num = input_buf[0]; if ((try in.read(&input_buf)) < 1) return null; if (num == '3' and input_buf[0] == '~') try state.editDelete(); }, 'A' => try state.editHistoryNext(.prev), 'B' => try state.editHistoryNext(.next), 'C' => try state.editMoveRight(), 'D' => try state.editMoveLeft(), 'H' => try state.editMoveHome(), 'F' => try state.editMoveEnd(), else => {}, } }, '0' => { if ((try in.read(&input_buf)) < 1) return null; switch (input_buf[0]) { 'H' => try state.editMoveHome(), 'F' => try state.editMoveEnd(), else => {}, } }, else => {}, } }, key_backspace, key_ctrl_h => try state.editBackspace(), else => { var utf8_buf: [4]u8 = undefined; const utf8_len = std.unicode.utf8CodepointSequenceLength(c) catch continue; utf8_buf[0] = c; if ((try in.read(utf8_buf[1..utf8_len])) < utf8_len - 1) return null; try state.editInsert(utf8_buf[0..utf8_len]); }, } } } /// Read a line with custom line editing mechanics. This includes hints, /// completions and history fn linenoiseRaw(ln: *Linenoise, in: File, out: File, prompt: []const u8) !?[]const u8 { defer out.writeAll("\n") catch {}; const orig = try enableRawMode(in); defer disableRawMode(in, orig); return try linenoiseEdit(ln, in, out, prompt); } /// Read a line with no special features (no hints, no completions, no history) fn linenoiseNoTTY(allocator: Allocator, stdin: File) !?[]const u8 { var reader = stdin.reader(); const max_line_len = std.math.maxInt(usize); return reader.readUntilDelimiterAlloc(allocator, '\n', max_line_len) catch |e| switch (e) { error.EndOfStream => return null, else => return e, }; } pub const Linenoise = struct { allocator: Allocator, history: History, multiline_mode: bool, mask_mode: bool, hints_callback: ?HintsCallback, completions_callback: ?CompletionsCallback, const Self = @This(); /// Initialize a linenoise struct pub fn init(allocator: Allocator) Self { return Self{ .allocator = allocator, .history = History.empty(allocator), .mask_mode = false, .multiline_mode = false, .hints_callback = null, .completions_callback = null, }; } /// Free all resources occupied by this struct pub fn deinit(self: *Self) void { self.history.deinit(); } /// Reads a line from the terminal. Caller owns returned memory pub fn linenoise(self: *Self, prompt: []const u8) !?[]const u8 { const stdin_file = std.io.getStdIn(); const stdout_file = std.io.getStdOut(); if (stdin_file.isTty()) { if (isUnsupportedTerm()) { try stdout_file.writeAll(prompt); return try linenoiseNoTTY(self.allocator, stdin_file); } else { return try linenoiseRaw(self, stdin_file, stdout_file, prompt); } } else { return try linenoiseNoTTY(self.allocator, stdin_file); } } }; test "all" { _ = @import("history.zig"); }
src/main.zig
const std = @import("std"); const input = @embedFile("data/input17"); usingnamespace @import("util.zig"); pub fn main() !void { var allocator_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; const part1 = p1: { var s = prepare(allocator, input); defer s.deinit(); boot(&s, .d3); break :p1 s.active_cubes.count(); }; print("[Part1] Active cubes 3D: {}", .{part1}); const part2 = p2: { var s = prepare(allocator, input); defer s.deinit(); boot(&s, .d4); break :p2 s.active_cubes.count(); }; print("[Part2] Active cubes 4D: {}", .{part2}); } const Pos = struct { x: i32, y: i32, z: i32, w: i32 }; const State = struct { const Self = @This(); const CubeSet = std.AutoHashMap(Pos, void); active_cubes: CubeSet, next_active_cubes: CubeSet, bounds_min: Pos = .{ .x = -1, .y = -1, .z = -1, .w = -1 }, bounds_max: Pos = .{ .x = 1, .y = 1, .z = 1, .w = 1 }, pub fn init(allocator: *std.mem.Allocator) State { return .{ .active_cubes = CubeSet.init(allocator), .next_active_cubes = CubeSet.init(allocator), }; } pub fn deinit(self: *Self) void { self.active_cubes.deinit(); self.next_active_cubes.deinit(); } pub fn activate(self: *Self, pos: Pos) void { self.next_active_cubes.put(pos, {}) catch @panic("put failed"); self.bounds_min.x = std.math.min(self.bounds_min.x, pos.x - 1); self.bounds_min.y = std.math.min(self.bounds_min.y, pos.y - 1); self.bounds_min.z = std.math.min(self.bounds_min.z, pos.z - 1); self.bounds_min.w = std.math.min(self.bounds_min.w, pos.w - 1); self.bounds_max.x = std.math.max(self.bounds_max.x, pos.x + 1); self.bounds_max.y = std.math.max(self.bounds_max.y, pos.y + 1); self.bounds_max.z = std.math.max(self.bounds_max.z, pos.z + 1); self.bounds_max.w = std.math.max(self.bounds_max.w, pos.w + 1); } pub fn deactivate(self: *Self, pos: Pos) void { _ = self.next_active_cubes.remove(pos); } pub fn applyChanges(self: *Self) void { self.active_cubes.deinit(); self.active_cubes = self.next_active_cubes.clone() catch @panic("clone failed"); } pub fn isActive(self: Self, pos: Pos) bool { return self.active_cubes.contains(pos); } }; fn prepare(allocator: *std.mem.Allocator, input_str: []const u8) State { var s = State.init(allocator); var reader = lines(input_str); var pos: Pos = .{ .x = 0, .y = 0, .z = 0, .w = 0 }; while (reader.next()) |line| : (pos.y += 1){ for (line) |c, i| { pos.x = @intCast(i32, i); if (c == '#') { s.activate(pos); } } } s.applyChanges(); return s; } fn boot(state: *State, comptime dim: Dim) void { comptime var i: usize = 0; inline while (i < 6) : (i += 1) { step(state, dim); } } const Dim = enum { d3, d4 }; fn step(state: *State, comptime dim: Dim) void { const min = state.bounds_min; const max = state.bounds_max; switch (dim) { .d3 => { var pos = Pos{ .x = min.x, .y = min.y, .z = min.z, .w = 0 }; step3D(state, &pos, min, max, .d3); }, .d4 => { var pos = min; step4D(state, &pos, min, max); }, } state.applyChanges(); } fn step4D(state: *State, pos: *Pos, min: Pos, max: Pos) void { pos.w = min.w; while (pos.w <= max.w) : (pos.w += 1) { step3D(state, pos, min, max, .d4); } } fn step3D(state: *State, pos: *Pos, min: Pos, max: Pos, comptime dim: Dim) void { pos.z = min.z; while (pos.z <= max.z) : (pos.z += 1) { pos.y = min.y; while (pos.y <= max.y) : (pos.y += 1) { pos.x = min.x; while (pos.x <= max.x) : (pos.x += 1) { const active_neighbours = countActiveNeighbours(state, pos.*, dim); if (state.isActive(pos.*)) { if (active_neighbours != 2 and active_neighbours != 3) { state.deactivate(pos.*); } } else { if (active_neighbours == 3) { state.activate(pos.*); } } } } } } fn countActiveNeighbours(state: *const State, pos: Pos, comptime dim: Dim) usize { var count: usize = 0; switch (dim) { .d3 => { const initial_offset = Pos{ .x = -1, .y = -1, .z = -1, .w = 0 }; countActiveNeighbours3D(state, pos, initial_offset, &count); }, .d4 => countActiveNeighbours4D(state, pos, &count), } return count; } fn countActiveNeighbours4D(state: *const State, pos: Pos, count: *usize) void { var offset = Pos{ .x = -1, .y = -1, .z = -1, .w = -1 }; while (offset.w <= 1) : (offset.w += 1) { countActiveNeighbours3D(state, pos, offset, count); } } fn countActiveNeighbours3D(state: *const State, pos: Pos, neighbour_offset: Pos, count: *usize) void { var offset = neighbour_offset; offset.z = -1; while (offset.z <= 1) : (offset.z += 1) { offset.y = -1; while (offset.y <= 1) : (offset.y += 1) { offset.x = -1; while (offset.x <= 1) : (offset.x += 1) { if (offset.x != 0 or offset.y != 0 or offset.z != 0 or offset.w != 0) { const neighbour_pos = Pos{ .x = pos.x + offset.x, .y = pos.y + offset.y, .z = pos.z + offset.z, .w = pos.w + offset.w, }; count.* += @boolToInt(state.isActive(neighbour_pos)); } } } } } const expectEqual = std.testing.expectEqual; test "boot 3D" { var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; var s = prepare(allocator, test_input); defer s.deinit(); boot(&s, .d3); expectEqual(@as(usize, 112), s.active_cubes.count()); } test "boot 4D" { var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; var s = prepare(allocator, test_input); defer s.deinit(); boot(&s, .d4); expectEqual(@as(usize, 848), s.active_cubes.count()); } const test_input = \\.#. \\..# \\### ;
src/day17.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Number = struct { const PAIR = std.math.maxInt(usize); const State = enum { SEARCH, EXPLODE, SPLIT }; const Cell = struct { num: usize, l: ?*Cell, r: ?*Cell, p: ?*Cell, fn init() *Cell { var c: *Cell = allocator.create(Cell) catch unreachable; c.*.num = 0; c.*.l = null; c.*.r = null; c.*.p = null; return c; } pub fn init_num(num: usize) *Cell { var c = Cell.init(); c.*.num = num; return c; } pub fn init_pair(l: *Cell, r: *Cell) *Cell { var c = Cell.init(); c.*.num = PAIR; c.l = l; c.r = r; l.p = c; r.p = c; return c; } pub fn clone(c: *Cell) *Cell { if (c.is_num()) return init_num(c.num); return init_pair(c.l.?.clone(), c.r.?.clone()); } pub fn deinit(self: *Cell) void { if (self.l) |l| l.*.deinit(); if (self.r) |r| r.*.deinit(); allocator.destroy(self); } pub fn equal(self: *Cell, other: *Cell) bool { if (self.is_num() and other.is_num()) { return self.num == other.num; } if (self.is_pair() and other.is_pair()) { return Cell.equal(self.l.?, other.l.?) and Cell.equal(self.r.?, other.r.?); } return false; } pub fn is_num(self: Cell) bool { return self.num != PAIR; } pub fn is_pair(self: Cell) bool { return self.num == PAIR; } pub fn is_simple(self: Cell) bool { return self.is_pair() and self.l.?.is_num() and self.r.?.is_num(); } pub fn show(self: Cell) void { if (self.is_num()) { std.debug.warn("{d}", .{self.num}); } else { std.debug.warn("[", .{}); self.l.?.show(); std.debug.warn(",", .{}); self.r.?.show(); std.debug.warn("]", .{}); } } pub fn add(l: *Cell, r: *Cell) *Cell { var c: *Cell = init_pair(l.clone(), r.clone()); c.*.reduce(); return c; } pub fn parse_pair(data: []const u8, pos: *usize) *Cell { pos.* += 1; // '[' var l = parse_cell(data, pos); pos.* += 1; // ',' var r = parse_cell(data, pos); pos.* += 1; // ']' var c = init_pair(l, r); return c; } pub fn parse_cell(data: []const u8, pos: *usize) *Cell { if (data[pos.*] < '0' or data[pos.*] > '9') { return parse_pair(data, pos); } var num: usize = 0; for (data[pos.*..]) |c| { if (c < '0' or c > '9') break; num *= 10; num += c - '0'; pos.* += 1; } return init_num(num); } fn find_parent_for_right(self: *Cell) ?*Cell { // std.debug.warn("FIND RIGHT node {}\n", .{self}); if (self.p) |p| { if (self == p.r) { return p.l; } return p.find_parent_for_right(); } return null; } fn find_parent_for_left(self: *Cell) ?*Cell { // std.debug.warn("FIND LEFT node {}\n", .{self}); if (self.p) |p| { if (self == p.l) { return p.r; } return p.find_parent_for_left(); } return null; } fn add_first(self: *Cell, delta: usize) void { if (self.is_num()) { // std.debug.warn("ADDING FIRST {} to {} => {}\n", .{ delta, self.*.num, self.*.num + delta }); self.*.num += delta; } else { self.l.?.add_first(delta); } } fn add_last(self: *Cell, delta: usize) void { if (self.is_num()) { // std.debug.warn("ADDING LAST {} to {} => {}\n", .{ delta, self.*.num, self.*.num + delta }); self.*.num += delta; } else { self.r.?.add_last(delta); } } pub fn magnitude(self: *Cell) usize { if (self.is_num()) { return self.num; } return 3 * self.l.?.magnitude() + 2 * self.r.?.magnitude(); } pub fn reduce(self: *Cell) void { // std.debug.warn("REDUCE ", .{}); // self.show(); // std.debug.warn("\n", .{}); while (true) { if (self.explode(1)) continue; if (self.split(1)) continue; break; } } pub fn split(self: *Cell, depth: usize) bool { if (self.*.is_num()) { if (self.*.num < 10) return false; const mid = @divTrunc(self.*.num, 2); const odd = if (self.*.num & 1 == 1) @as(usize, 1) else @as(usize, 0); // std.debug.warn("[{}] SPLIT {} => [{},{}]\n", .{ depth, self.*.num, mid, mid + odd }); self.*.num = PAIR; self.*.l = init_num(mid); self.*.l.?.p = self; self.*.r = init_num(mid + odd); self.*.r.?.p = self; return true; } else { if (self.*.l.?.split(depth + 1)) return true; if (self.*.r.?.split(depth + 1)) return true; return false; } } pub fn explode(self: *Cell, depth: usize) bool { if (self.*.is_num()) { return false; } if (depth <= 4 or !self.is_simple()) { if (self.*.l.?.explode(depth + 1)) return true; if (self.*.r.?.explode(depth + 1)) return true; return false; } // std.debug.warn("[{}] EXPLODE ", .{depth}); // self.*.show(); // std.debug.warn("\n", .{}); const L = self.*.l.?.num; const R = self.*.r.?.num; self.*.l.?.deinit(); self.*.r.?.deinit(); self.*.num = 0; self.*.l = null; self.*.r = null; var node: ?*Cell = null; node = self.find_parent_for_right(); if (node) |n| { n.add_last(L); } node = self.find_parent_for_left(); if (node) |n| { n.add_first(R); } return true; } }; numbers: std.ArrayList(*Cell), pub fn init() Number { var self = Number{ .numbers = std.ArrayList(*Cell).init(allocator), }; return self; } pub fn deinit(self: *Number) void { for (self.numbers.items) |*n| { n.*.deinit(); } self.numbers.deinit(); } pub fn process_line(self: *Number, data: []const u8) !void { var pos: usize = 0; var num = Cell.parse_cell(data, &pos); try self.numbers.append(num); } pub fn add_all(self: *Number) usize { var sum: ?*Cell = null; for (self.numbers.items) |n| { if (sum == null) { sum = n.clone(); } else { var s = Cell.add(sum.?, n); sum.?.deinit(); sum = s; } } var mag: usize = 0; if (sum != null) { mag = sum.?.magnitude(); sum.?.deinit(); } return mag; } pub fn largest_sum_of_two(self: *Number) usize { var mag: usize = 0; var j0: usize = 0; while (j0 < self.numbers.items.len) : (j0 += 1) { var j1: usize = 0; while (j1 < self.numbers.items.len) : (j1 += 1) { if (j0 == j1) continue; var c0 = self.numbers.items[j0].clone(); defer c0.deinit(); var c1 = self.numbers.items[j1].clone(); defer c1.deinit(); var s = Cell.add(c0, c1); defer s.deinit(); var m = s.magnitude(); if (mag < m) mag = m; } } return mag; } }; // test "sample part a reduce 1" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[[[[[9,8],1],2],3],4]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[[[[0,9],2],3],4]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a reduce 2" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[7,[6,[5,[4,[3,2]]]]]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[7,[6,[5,[7,0]]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a reduce 3" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[[6,[5,[4,[3,2]]]],1]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[[6,[5,[7,0]]],3]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a reduce 4" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[[3,[2,[8,0]]],[9,[5,[7,0]]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a reduce 5" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[[[[[4,3],4],4],[7,[[8,4],9]]],[1,1]]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a reduce 6" { // var pos: usize = 0; // std.debug.warn("\n", .{}); // pos = 0; // var ori = Number.Cell.parse_cell("[[[[[1,1],[2,2]],[3,3]],[4,4]],[5,5]]", &pos); // defer ori.deinit(); // ori.reduce(); // pos = 0; // var res = Number.Cell.parse_cell("[[[[3,0],[5,3]],[4,4]],[5,5]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(ori, res)); // } // test "sample part a add 0" { // const data: []const u8 = // \\[1,2] // \\[[3,4],5] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[1,2],[[3,4],5]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 1" { // const data: []const u8 = // \\[1,1] // \\[2,2] // \\[3,3] // \\[4,4] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[1,1],[2,2]],[3,3]],[4,4]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 2" { // const data: []const u8 = // \\[1,1] // \\[2,2] // \\[3,3] // \\[4,4] // \\[5,5] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[3,0],[5,3]],[4,4]],[5,5]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 3" { // const data: []const u8 = // \\[1,1] // \\[2,2] // \\[3,3] // \\[4,4] // \\[5,5] // \\[6,6] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[5,0],[7,4]],[5,5]],[6,6]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 4.1" { // const data: []const u8 = // \\[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]] // \\[7,[[[3,7],[4,3]],[[6,3],[8,8]]]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 4.2" { // const data: []const u8 = // \\[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]] // \\[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[6,7],[6,7]],[[7,7],[0,7]]],[[[8,7],[7,7]],[[8,8],[8,0]]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a add 4.3" { // const data: []const u8 = // \\[[[[6,7],[6,7]],[[7,7],[0,7]]],[[[8,7],[7,7]],[[8,8],[8,0]]]] // \\[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[7,0],[7,7]],[[7,7],[7,8]]],[[[7,7],[8,8]],[[7,7],[8,7]]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } // test "sample part a magnitude 1" { // const data: []const u8 = // \\[[1,2],[[3,4],5]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // try testing.expect(number.magnitude() == 143); // } // test "sample part a magnitude 2" { // const data: []const u8 = // \\[[[[0,7],4],[[7,8],[6,0]]],[8,1]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // try testing.expect(number.magnitude() == 1384); // } // test "sample part a magnitude 6" { // const data: []const u8 = // \\[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // try testing.expect(number.magnitude() == 3488); // } // test "sample part a add 11" { // const data: []const u8 = // \\[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]] // \\[7,[[[3,7],[4,3]],[[6,3],[8,8]]]] // \\[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]] // \\[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]] // \\[7,[5,[[3,8],[1,4]]]] // \\[[2,[2,2]],[8,[8,1]]] // \\[2,9] // \\[1,[[[9,3],9],[[9,0],[0,7]]]] // \\[[[5,[7,4]],7],1] // \\[[[[4,2],2],6],[8,7]] // ; // var number = Number.init(); // defer number.deinit(); // var it = std.mem.split(u8, data, "\n"); // while (it.next()) |line| { // try number.process_line(line); // } // var pos: usize = 0; // var res = Number.Cell.parse_cell("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", &pos); // defer res.deinit(); // try testing.expect(Number.Cell.equal(number.value.?, res)); // } test "sample part a add sample" { const data: []const u8 = \\[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]] \\[[[5,[2,8]],4],[5,[[9,9],0]]] \\[6,[[[6,2],[5,6]],[[7,6],[4,7]]]] \\[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]] \\[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]] \\[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]] \\[[[[5,4],[7,7]],8],[[8,3],8]] \\[[9,3],[[9,9],[6,[4,9]]]] \\[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]] \\[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]] ; var number = Number.init(); defer number.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try number.process_line(line); } const mag = number.add_all(); try testing.expect(mag == 4140); } test "sample part b" { const data: []const u8 = \\[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]] \\[[[5,[2,8]],4],[5,[[9,9],0]]] \\[6,[[[6,2],[5,6]],[[7,6],[4,7]]]] \\[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]] \\[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]] \\[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]] \\[[[[5,4],[7,7]],8],[[8,3],8]] \\[[9,3],[[9,9],[6,[4,9]]]] \\[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]] \\[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]] ; var number = Number.init(); defer number.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try number.process_line(line); } const mag = number.largest_sum_of_two(); try testing.expect(mag == 3993); }
2021/p18/number.zig
/// The function fiatP384AddcarryxU32 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^32 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] fn fiatP384AddcarryxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u64 = ((@intCast(u64, arg1) + @intCast(u64, arg2)) + @intCast(u64, arg3)); const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff))); const x3: u1 = @intCast(u1, (x1 >> 32)); out1.* = x2; out2.* = x3; } /// The function fiatP384SubborrowxU32 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^32 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] fn fiatP384SubborrowxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: i64 = ((@intCast(i64, arg2) - @intCast(i64, arg1)) - @intCast(i64, arg3)); const x2: i1 = @intCast(i1, (x1 >> 32)); const x3: u32 = @intCast(u32, (x1 & @intCast(i64, 0xffffffff))); out1.* = x3; out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2))); } /// The function fiatP384MulxU32 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^32 /// out2 = ⌊arg1 * arg2 / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0xffffffff] fn fiatP384MulxU32(out1: *u32, out2: *u32, arg1: u32, arg2: u32) callconv(.Inline) void { const x1: u64 = (@intCast(u64, arg1) * @intCast(u64, arg2)); const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff))); const x3: u32 = @intCast(u32, (x1 >> 32)); out1.* = x2; out2.* = x3; } /// The function fiatP384CmovznzU32 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 fiatP384CmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u1 = (~(~arg1)); const x2: u32 = @intCast(u32, (@intCast(i64, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i64, 0xffffffff))); const x3: u32 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function fiatP384Mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Mul(out1: *[12]u32, arg1: [12]u32, arg2: [12]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[8]); const x9: u32 = (arg1[9]); const x10: u32 = (arg1[10]); const x11: u32 = (arg1[11]); const x12: u32 = (arg1[0]); var x13: u32 = undefined; var x14: u32 = undefined; fiatP384MulxU32(&x13, &x14, x12, (arg2[11])); var x15: u32 = undefined; var x16: u32 = undefined; fiatP384MulxU32(&x15, &x16, x12, (arg2[10])); var x17: u32 = undefined; var x18: u32 = undefined; fiatP384MulxU32(&x17, &x18, x12, (arg2[9])); var x19: u32 = undefined; var x20: u32 = undefined; fiatP384MulxU32(&x19, &x20, x12, (arg2[8])); var x21: u32 = undefined; var x22: u32 = undefined; fiatP384MulxU32(&x21, &x22, x12, (arg2[7])); var x23: u32 = undefined; var x24: u32 = undefined; fiatP384MulxU32(&x23, &x24, x12, (arg2[6])); var x25: u32 = undefined; var x26: u32 = undefined; fiatP384MulxU32(&x25, &x26, x12, (arg2[5])); var x27: u32 = undefined; var x28: u32 = undefined; fiatP384MulxU32(&x27, &x28, x12, (arg2[4])); var x29: u32 = undefined; var x30: u32 = undefined; fiatP384MulxU32(&x29, &x30, x12, (arg2[3])); var x31: u32 = undefined; var x32: u32 = undefined; fiatP384MulxU32(&x31, &x32, x12, (arg2[2])); var x33: u32 = undefined; var x34: u32 = undefined; fiatP384MulxU32(&x33, &x34, x12, (arg2[1])); var x35: u32 = undefined; var x36: u32 = undefined; fiatP384MulxU32(&x35, &x36, x12, (arg2[0])); var x37: u32 = undefined; var x38: u1 = undefined; fiatP384AddcarryxU32(&x37, &x38, 0x0, x36, x33); var x39: u32 = undefined; var x40: u1 = undefined; fiatP384AddcarryxU32(&x39, &x40, x38, x34, x31); var x41: u32 = undefined; var x42: u1 = undefined; fiatP384AddcarryxU32(&x41, &x42, x40, x32, x29); var x43: u32 = undefined; var x44: u1 = undefined; fiatP384AddcarryxU32(&x43, &x44, x42, x30, x27); var x45: u32 = undefined; var x46: u1 = undefined; fiatP384AddcarryxU32(&x45, &x46, x44, x28, x25); var x47: u32 = undefined; var x48: u1 = undefined; fiatP384AddcarryxU32(&x47, &x48, x46, x26, x23); var x49: u32 = undefined; var x50: u1 = undefined; fiatP384AddcarryxU32(&x49, &x50, x48, x24, x21); var x51: u32 = undefined; var x52: u1 = undefined; fiatP384AddcarryxU32(&x51, &x52, x50, x22, x19); var x53: u32 = undefined; var x54: u1 = undefined; fiatP384AddcarryxU32(&x53, &x54, x52, x20, x17); var x55: u32 = undefined; var x56: u1 = undefined; fiatP384AddcarryxU32(&x55, &x56, x54, x18, x15); var x57: u32 = undefined; var x58: u1 = undefined; fiatP384AddcarryxU32(&x57, &x58, x56, x16, x13); const x59: u32 = (@intCast(u32, x58) + x14); var x60: u32 = undefined; var x61: u32 = undefined; fiatP384MulxU32(&x60, &x61, x35, 0xffffffff); var x62: u32 = undefined; var x63: u32 = undefined; fiatP384MulxU32(&x62, &x63, x35, 0xffffffff); var x64: u32 = undefined; var x65: u32 = undefined; fiatP384MulxU32(&x64, &x65, x35, 0xffffffff); var x66: u32 = undefined; var x67: u32 = undefined; fiatP384MulxU32(&x66, &x67, x35, 0xffffffff); var x68: u32 = undefined; var x69: u32 = undefined; fiatP384MulxU32(&x68, &x69, x35, 0xffffffff); var x70: u32 = undefined; var x71: u32 = undefined; fiatP384MulxU32(&x70, &x71, x35, 0xffffffff); var x72: u32 = undefined; var x73: u32 = undefined; fiatP384MulxU32(&x72, &x73, x35, 0xffffffff); var x74: u32 = undefined; var x75: u32 = undefined; fiatP384MulxU32(&x74, &x75, x35, 0xfffffffe); var x76: u32 = undefined; var x77: u32 = undefined; fiatP384MulxU32(&x76, &x77, x35, 0xffffffff); var x78: u32 = undefined; var x79: u32 = undefined; fiatP384MulxU32(&x78, &x79, x35, 0xffffffff); var x80: u32 = undefined; var x81: u1 = undefined; fiatP384AddcarryxU32(&x80, &x81, 0x0, x77, x74); var x82: u32 = undefined; var x83: u1 = undefined; fiatP384AddcarryxU32(&x82, &x83, x81, x75, x72); var x84: u32 = undefined; var x85: u1 = undefined; fiatP384AddcarryxU32(&x84, &x85, x83, x73, x70); var x86: u32 = undefined; var x87: u1 = undefined; fiatP384AddcarryxU32(&x86, &x87, x85, x71, x68); var x88: u32 = undefined; var x89: u1 = undefined; fiatP384AddcarryxU32(&x88, &x89, x87, x69, x66); var x90: u32 = undefined; var x91: u1 = undefined; fiatP384AddcarryxU32(&x90, &x91, x89, x67, x64); var x92: u32 = undefined; var x93: u1 = undefined; fiatP384AddcarryxU32(&x92, &x93, x91, x65, x62); var x94: u32 = undefined; var x95: u1 = undefined; fiatP384AddcarryxU32(&x94, &x95, x93, x63, x60); const x96: u32 = (@intCast(u32, x95) + x61); var x97: u32 = undefined; var x98: u1 = undefined; fiatP384AddcarryxU32(&x97, &x98, 0x0, x35, x78); var x99: u32 = undefined; var x100: u1 = undefined; fiatP384AddcarryxU32(&x99, &x100, x98, x37, x79); var x101: u32 = undefined; var x102: u1 = undefined; fiatP384AddcarryxU32(&x101, &x102, x100, x39, @intCast(u32, 0x0)); var x103: u32 = undefined; var x104: u1 = undefined; fiatP384AddcarryxU32(&x103, &x104, x102, x41, x76); var x105: u32 = undefined; var x106: u1 = undefined; fiatP384AddcarryxU32(&x105, &x106, x104, x43, x80); var x107: u32 = undefined; var x108: u1 = undefined; fiatP384AddcarryxU32(&x107, &x108, x106, x45, x82); var x109: u32 = undefined; var x110: u1 = undefined; fiatP384AddcarryxU32(&x109, &x110, x108, x47, x84); var x111: u32 = undefined; var x112: u1 = undefined; fiatP384AddcarryxU32(&x111, &x112, x110, x49, x86); var x113: u32 = undefined; var x114: u1 = undefined; fiatP384AddcarryxU32(&x113, &x114, x112, x51, x88); var x115: u32 = undefined; var x116: u1 = undefined; fiatP384AddcarryxU32(&x115, &x116, x114, x53, x90); var x117: u32 = undefined; var x118: u1 = undefined; fiatP384AddcarryxU32(&x117, &x118, x116, x55, x92); var x119: u32 = undefined; var x120: u1 = undefined; fiatP384AddcarryxU32(&x119, &x120, x118, x57, x94); var x121: u32 = undefined; var x122: u1 = undefined; fiatP384AddcarryxU32(&x121, &x122, x120, x59, x96); var x123: u32 = undefined; var x124: u32 = undefined; fiatP384MulxU32(&x123, &x124, x1, (arg2[11])); var x125: u32 = undefined; var x126: u32 = undefined; fiatP384MulxU32(&x125, &x126, x1, (arg2[10])); var x127: u32 = undefined; var x128: u32 = undefined; fiatP384MulxU32(&x127, &x128, x1, (arg2[9])); var x129: u32 = undefined; var x130: u32 = undefined; fiatP384MulxU32(&x129, &x130, x1, (arg2[8])); var x131: u32 = undefined; var x132: u32 = undefined; fiatP384MulxU32(&x131, &x132, x1, (arg2[7])); var x133: u32 = undefined; var x134: u32 = undefined; fiatP384MulxU32(&x133, &x134, x1, (arg2[6])); var x135: u32 = undefined; var x136: u32 = undefined; fiatP384MulxU32(&x135, &x136, x1, (arg2[5])); var x137: u32 = undefined; var x138: u32 = undefined; fiatP384MulxU32(&x137, &x138, x1, (arg2[4])); var x139: u32 = undefined; var x140: u32 = undefined; fiatP384MulxU32(&x139, &x140, x1, (arg2[3])); var x141: u32 = undefined; var x142: u32 = undefined; fiatP384MulxU32(&x141, &x142, x1, (arg2[2])); var x143: u32 = undefined; var x144: u32 = undefined; fiatP384MulxU32(&x143, &x144, x1, (arg2[1])); var x145: u32 = undefined; var x146: u32 = undefined; fiatP384MulxU32(&x145, &x146, x1, (arg2[0])); var x147: u32 = undefined; var x148: u1 = undefined; fiatP384AddcarryxU32(&x147, &x148, 0x0, x146, x143); var x149: u32 = undefined; var x150: u1 = undefined; fiatP384AddcarryxU32(&x149, &x150, x148, x144, x141); var x151: u32 = undefined; var x152: u1 = undefined; fiatP384AddcarryxU32(&x151, &x152, x150, x142, x139); var x153: u32 = undefined; var x154: u1 = undefined; fiatP384AddcarryxU32(&x153, &x154, x152, x140, x137); var x155: u32 = undefined; var x156: u1 = undefined; fiatP384AddcarryxU32(&x155, &x156, x154, x138, x135); var x157: u32 = undefined; var x158: u1 = undefined; fiatP384AddcarryxU32(&x157, &x158, x156, x136, x133); var x159: u32 = undefined; var x160: u1 = undefined; fiatP384AddcarryxU32(&x159, &x160, x158, x134, x131); var x161: u32 = undefined; var x162: u1 = undefined; fiatP384AddcarryxU32(&x161, &x162, x160, x132, x129); var x163: u32 = undefined; var x164: u1 = undefined; fiatP384AddcarryxU32(&x163, &x164, x162, x130, x127); var x165: u32 = undefined; var x166: u1 = undefined; fiatP384AddcarryxU32(&x165, &x166, x164, x128, x125); var x167: u32 = undefined; var x168: u1 = undefined; fiatP384AddcarryxU32(&x167, &x168, x166, x126, x123); const x169: u32 = (@intCast(u32, x168) + x124); var x170: u32 = undefined; var x171: u1 = undefined; fiatP384AddcarryxU32(&x170, &x171, 0x0, x99, x145); var x172: u32 = undefined; var x173: u1 = undefined; fiatP384AddcarryxU32(&x172, &x173, x171, x101, x147); var x174: u32 = undefined; var x175: u1 = undefined; fiatP384AddcarryxU32(&x174, &x175, x173, x103, x149); var x176: u32 = undefined; var x177: u1 = undefined; fiatP384AddcarryxU32(&x176, &x177, x175, x105, x151); var x178: u32 = undefined; var x179: u1 = undefined; fiatP384AddcarryxU32(&x178, &x179, x177, x107, x153); var x180: u32 = undefined; var x181: u1 = undefined; fiatP384AddcarryxU32(&x180, &x181, x179, x109, x155); var x182: u32 = undefined; var x183: u1 = undefined; fiatP384AddcarryxU32(&x182, &x183, x181, x111, x157); var x184: u32 = undefined; var x185: u1 = undefined; fiatP384AddcarryxU32(&x184, &x185, x183, x113, x159); var x186: u32 = undefined; var x187: u1 = undefined; fiatP384AddcarryxU32(&x186, &x187, x185, x115, x161); var x188: u32 = undefined; var x189: u1 = undefined; fiatP384AddcarryxU32(&x188, &x189, x187, x117, x163); var x190: u32 = undefined; var x191: u1 = undefined; fiatP384AddcarryxU32(&x190, &x191, x189, x119, x165); var x192: u32 = undefined; var x193: u1 = undefined; fiatP384AddcarryxU32(&x192, &x193, x191, x121, x167); var x194: u32 = undefined; var x195: u1 = undefined; fiatP384AddcarryxU32(&x194, &x195, x193, @intCast(u32, x122), x169); var x196: u32 = undefined; var x197: u32 = undefined; fiatP384MulxU32(&x196, &x197, x170, 0xffffffff); var x198: u32 = undefined; var x199: u32 = undefined; fiatP384MulxU32(&x198, &x199, x170, 0xffffffff); var x200: u32 = undefined; var x201: u32 = undefined; fiatP384MulxU32(&x200, &x201, x170, 0xffffffff); var x202: u32 = undefined; var x203: u32 = undefined; fiatP384MulxU32(&x202, &x203, x170, 0xffffffff); var x204: u32 = undefined; var x205: u32 = undefined; fiatP384MulxU32(&x204, &x205, x170, 0xffffffff); var x206: u32 = undefined; var x207: u32 = undefined; fiatP384MulxU32(&x206, &x207, x170, 0xffffffff); var x208: u32 = undefined; var x209: u32 = undefined; fiatP384MulxU32(&x208, &x209, x170, 0xffffffff); var x210: u32 = undefined; var x211: u32 = undefined; fiatP384MulxU32(&x210, &x211, x170, 0xfffffffe); var x212: u32 = undefined; var x213: u32 = undefined; fiatP384MulxU32(&x212, &x213, x170, 0xffffffff); var x214: u32 = undefined; var x215: u32 = undefined; fiatP384MulxU32(&x214, &x215, x170, 0xffffffff); var x216: u32 = undefined; var x217: u1 = undefined; fiatP384AddcarryxU32(&x216, &x217, 0x0, x213, x210); var x218: u32 = undefined; var x219: u1 = undefined; fiatP384AddcarryxU32(&x218, &x219, x217, x211, x208); var x220: u32 = undefined; var x221: u1 = undefined; fiatP384AddcarryxU32(&x220, &x221, x219, x209, x206); var x222: u32 = undefined; var x223: u1 = undefined; fiatP384AddcarryxU32(&x222, &x223, x221, x207, x204); var x224: u32 = undefined; var x225: u1 = undefined; fiatP384AddcarryxU32(&x224, &x225, x223, x205, x202); var x226: u32 = undefined; var x227: u1 = undefined; fiatP384AddcarryxU32(&x226, &x227, x225, x203, x200); var x228: u32 = undefined; var x229: u1 = undefined; fiatP384AddcarryxU32(&x228, &x229, x227, x201, x198); var x230: u32 = undefined; var x231: u1 = undefined; fiatP384AddcarryxU32(&x230, &x231, x229, x199, x196); const x232: u32 = (@intCast(u32, x231) + x197); var x233: u32 = undefined; var x234: u1 = undefined; fiatP384AddcarryxU32(&x233, &x234, 0x0, x170, x214); var x235: u32 = undefined; var x236: u1 = undefined; fiatP384AddcarryxU32(&x235, &x236, x234, x172, x215); var x237: u32 = undefined; var x238: u1 = undefined; fiatP384AddcarryxU32(&x237, &x238, x236, x174, @intCast(u32, 0x0)); var x239: u32 = undefined; var x240: u1 = undefined; fiatP384AddcarryxU32(&x239, &x240, x238, x176, x212); var x241: u32 = undefined; var x242: u1 = undefined; fiatP384AddcarryxU32(&x241, &x242, x240, x178, x216); var x243: u32 = undefined; var x244: u1 = undefined; fiatP384AddcarryxU32(&x243, &x244, x242, x180, x218); var x245: u32 = undefined; var x246: u1 = undefined; fiatP384AddcarryxU32(&x245, &x246, x244, x182, x220); var x247: u32 = undefined; var x248: u1 = undefined; fiatP384AddcarryxU32(&x247, &x248, x246, x184, x222); var x249: u32 = undefined; var x250: u1 = undefined; fiatP384AddcarryxU32(&x249, &x250, x248, x186, x224); var x251: u32 = undefined; var x252: u1 = undefined; fiatP384AddcarryxU32(&x251, &x252, x250, x188, x226); var x253: u32 = undefined; var x254: u1 = undefined; fiatP384AddcarryxU32(&x253, &x254, x252, x190, x228); var x255: u32 = undefined; var x256: u1 = undefined; fiatP384AddcarryxU32(&x255, &x256, x254, x192, x230); var x257: u32 = undefined; var x258: u1 = undefined; fiatP384AddcarryxU32(&x257, &x258, x256, x194, x232); const x259: u32 = (@intCast(u32, x258) + @intCast(u32, x195)); var x260: u32 = undefined; var x261: u32 = undefined; fiatP384MulxU32(&x260, &x261, x2, (arg2[11])); var x262: u32 = undefined; var x263: u32 = undefined; fiatP384MulxU32(&x262, &x263, x2, (arg2[10])); var x264: u32 = undefined; var x265: u32 = undefined; fiatP384MulxU32(&x264, &x265, x2, (arg2[9])); var x266: u32 = undefined; var x267: u32 = undefined; fiatP384MulxU32(&x266, &x267, x2, (arg2[8])); var x268: u32 = undefined; var x269: u32 = undefined; fiatP384MulxU32(&x268, &x269, x2, (arg2[7])); var x270: u32 = undefined; var x271: u32 = undefined; fiatP384MulxU32(&x270, &x271, x2, (arg2[6])); var x272: u32 = undefined; var x273: u32 = undefined; fiatP384MulxU32(&x272, &x273, x2, (arg2[5])); var x274: u32 = undefined; var x275: u32 = undefined; fiatP384MulxU32(&x274, &x275, x2, (arg2[4])); var x276: u32 = undefined; var x277: u32 = undefined; fiatP384MulxU32(&x276, &x277, x2, (arg2[3])); var x278: u32 = undefined; var x279: u32 = undefined; fiatP384MulxU32(&x278, &x279, x2, (arg2[2])); var x280: u32 = undefined; var x281: u32 = undefined; fiatP384MulxU32(&x280, &x281, x2, (arg2[1])); var x282: u32 = undefined; var x283: u32 = undefined; fiatP384MulxU32(&x282, &x283, x2, (arg2[0])); var x284: u32 = undefined; var x285: u1 = undefined; fiatP384AddcarryxU32(&x284, &x285, 0x0, x283, x280); var x286: u32 = undefined; var x287: u1 = undefined; fiatP384AddcarryxU32(&x286, &x287, x285, x281, x278); var x288: u32 = undefined; var x289: u1 = undefined; fiatP384AddcarryxU32(&x288, &x289, x287, x279, x276); var x290: u32 = undefined; var x291: u1 = undefined; fiatP384AddcarryxU32(&x290, &x291, x289, x277, x274); var x292: u32 = undefined; var x293: u1 = undefined; fiatP384AddcarryxU32(&x292, &x293, x291, x275, x272); var x294: u32 = undefined; var x295: u1 = undefined; fiatP384AddcarryxU32(&x294, &x295, x293, x273, x270); var x296: u32 = undefined; var x297: u1 = undefined; fiatP384AddcarryxU32(&x296, &x297, x295, x271, x268); var x298: u32 = undefined; var x299: u1 = undefined; fiatP384AddcarryxU32(&x298, &x299, x297, x269, x266); var x300: u32 = undefined; var x301: u1 = undefined; fiatP384AddcarryxU32(&x300, &x301, x299, x267, x264); var x302: u32 = undefined; var x303: u1 = undefined; fiatP384AddcarryxU32(&x302, &x303, x301, x265, x262); var x304: u32 = undefined; var x305: u1 = undefined; fiatP384AddcarryxU32(&x304, &x305, x303, x263, x260); const x306: u32 = (@intCast(u32, x305) + x261); var x307: u32 = undefined; var x308: u1 = undefined; fiatP384AddcarryxU32(&x307, &x308, 0x0, x235, x282); var x309: u32 = undefined; var x310: u1 = undefined; fiatP384AddcarryxU32(&x309, &x310, x308, x237, x284); var x311: u32 = undefined; var x312: u1 = undefined; fiatP384AddcarryxU32(&x311, &x312, x310, x239, x286); var x313: u32 = undefined; var x314: u1 = undefined; fiatP384AddcarryxU32(&x313, &x314, x312, x241, x288); var x315: u32 = undefined; var x316: u1 = undefined; fiatP384AddcarryxU32(&x315, &x316, x314, x243, x290); var x317: u32 = undefined; var x318: u1 = undefined; fiatP384AddcarryxU32(&x317, &x318, x316, x245, x292); var x319: u32 = undefined; var x320: u1 = undefined; fiatP384AddcarryxU32(&x319, &x320, x318, x247, x294); var x321: u32 = undefined; var x322: u1 = undefined; fiatP384AddcarryxU32(&x321, &x322, x320, x249, x296); var x323: u32 = undefined; var x324: u1 = undefined; fiatP384AddcarryxU32(&x323, &x324, x322, x251, x298); var x325: u32 = undefined; var x326: u1 = undefined; fiatP384AddcarryxU32(&x325, &x326, x324, x253, x300); var x327: u32 = undefined; var x328: u1 = undefined; fiatP384AddcarryxU32(&x327, &x328, x326, x255, x302); var x329: u32 = undefined; var x330: u1 = undefined; fiatP384AddcarryxU32(&x329, &x330, x328, x257, x304); var x331: u32 = undefined; var x332: u1 = undefined; fiatP384AddcarryxU32(&x331, &x332, x330, x259, x306); var x333: u32 = undefined; var x334: u32 = undefined; fiatP384MulxU32(&x333, &x334, x307, 0xffffffff); var x335: u32 = undefined; var x336: u32 = undefined; fiatP384MulxU32(&x335, &x336, x307, 0xffffffff); var x337: u32 = undefined; var x338: u32 = undefined; fiatP384MulxU32(&x337, &x338, x307, 0xffffffff); var x339: u32 = undefined; var x340: u32 = undefined; fiatP384MulxU32(&x339, &x340, x307, 0xffffffff); var x341: u32 = undefined; var x342: u32 = undefined; fiatP384MulxU32(&x341, &x342, x307, 0xffffffff); var x343: u32 = undefined; var x344: u32 = undefined; fiatP384MulxU32(&x343, &x344, x307, 0xffffffff); var x345: u32 = undefined; var x346: u32 = undefined; fiatP384MulxU32(&x345, &x346, x307, 0xffffffff); var x347: u32 = undefined; var x348: u32 = undefined; fiatP384MulxU32(&x347, &x348, x307, 0xfffffffe); var x349: u32 = undefined; var x350: u32 = undefined; fiatP384MulxU32(&x349, &x350, x307, 0xffffffff); var x351: u32 = undefined; var x352: u32 = undefined; fiatP384MulxU32(&x351, &x352, x307, 0xffffffff); var x353: u32 = undefined; var x354: u1 = undefined; fiatP384AddcarryxU32(&x353, &x354, 0x0, x350, x347); var x355: u32 = undefined; var x356: u1 = undefined; fiatP384AddcarryxU32(&x355, &x356, x354, x348, x345); var x357: u32 = undefined; var x358: u1 = undefined; fiatP384AddcarryxU32(&x357, &x358, x356, x346, x343); var x359: u32 = undefined; var x360: u1 = undefined; fiatP384AddcarryxU32(&x359, &x360, x358, x344, x341); var x361: u32 = undefined; var x362: u1 = undefined; fiatP384AddcarryxU32(&x361, &x362, x360, x342, x339); var x363: u32 = undefined; var x364: u1 = undefined; fiatP384AddcarryxU32(&x363, &x364, x362, x340, x337); var x365: u32 = undefined; var x366: u1 = undefined; fiatP384AddcarryxU32(&x365, &x366, x364, x338, x335); var x367: u32 = undefined; var x368: u1 = undefined; fiatP384AddcarryxU32(&x367, &x368, x366, x336, x333); const x369: u32 = (@intCast(u32, x368) + x334); var x370: u32 = undefined; var x371: u1 = undefined; fiatP384AddcarryxU32(&x370, &x371, 0x0, x307, x351); var x372: u32 = undefined; var x373: u1 = undefined; fiatP384AddcarryxU32(&x372, &x373, x371, x309, x352); var x374: u32 = undefined; var x375: u1 = undefined; fiatP384AddcarryxU32(&x374, &x375, x373, x311, @intCast(u32, 0x0)); var x376: u32 = undefined; var x377: u1 = undefined; fiatP384AddcarryxU32(&x376, &x377, x375, x313, x349); var x378: u32 = undefined; var x379: u1 = undefined; fiatP384AddcarryxU32(&x378, &x379, x377, x315, x353); var x380: u32 = undefined; var x381: u1 = undefined; fiatP384AddcarryxU32(&x380, &x381, x379, x317, x355); var x382: u32 = undefined; var x383: u1 = undefined; fiatP384AddcarryxU32(&x382, &x383, x381, x319, x357); var x384: u32 = undefined; var x385: u1 = undefined; fiatP384AddcarryxU32(&x384, &x385, x383, x321, x359); var x386: u32 = undefined; var x387: u1 = undefined; fiatP384AddcarryxU32(&x386, &x387, x385, x323, x361); var x388: u32 = undefined; var x389: u1 = undefined; fiatP384AddcarryxU32(&x388, &x389, x387, x325, x363); var x390: u32 = undefined; var x391: u1 = undefined; fiatP384AddcarryxU32(&x390, &x391, x389, x327, x365); var x392: u32 = undefined; var x393: u1 = undefined; fiatP384AddcarryxU32(&x392, &x393, x391, x329, x367); var x394: u32 = undefined; var x395: u1 = undefined; fiatP384AddcarryxU32(&x394, &x395, x393, x331, x369); const x396: u32 = (@intCast(u32, x395) + @intCast(u32, x332)); var x397: u32 = undefined; var x398: u32 = undefined; fiatP384MulxU32(&x397, &x398, x3, (arg2[11])); var x399: u32 = undefined; var x400: u32 = undefined; fiatP384MulxU32(&x399, &x400, x3, (arg2[10])); var x401: u32 = undefined; var x402: u32 = undefined; fiatP384MulxU32(&x401, &x402, x3, (arg2[9])); var x403: u32 = undefined; var x404: u32 = undefined; fiatP384MulxU32(&x403, &x404, x3, (arg2[8])); var x405: u32 = undefined; var x406: u32 = undefined; fiatP384MulxU32(&x405, &x406, x3, (arg2[7])); var x407: u32 = undefined; var x408: u32 = undefined; fiatP384MulxU32(&x407, &x408, x3, (arg2[6])); var x409: u32 = undefined; var x410: u32 = undefined; fiatP384MulxU32(&x409, &x410, x3, (arg2[5])); var x411: u32 = undefined; var x412: u32 = undefined; fiatP384MulxU32(&x411, &x412, x3, (arg2[4])); var x413: u32 = undefined; var x414: u32 = undefined; fiatP384MulxU32(&x413, &x414, x3, (arg2[3])); var x415: u32 = undefined; var x416: u32 = undefined; fiatP384MulxU32(&x415, &x416, x3, (arg2[2])); var x417: u32 = undefined; var x418: u32 = undefined; fiatP384MulxU32(&x417, &x418, x3, (arg2[1])); var x419: u32 = undefined; var x420: u32 = undefined; fiatP384MulxU32(&x419, &x420, x3, (arg2[0])); var x421: u32 = undefined; var x422: u1 = undefined; fiatP384AddcarryxU32(&x421, &x422, 0x0, x420, x417); var x423: u32 = undefined; var x424: u1 = undefined; fiatP384AddcarryxU32(&x423, &x424, x422, x418, x415); var x425: u32 = undefined; var x426: u1 = undefined; fiatP384AddcarryxU32(&x425, &x426, x424, x416, x413); var x427: u32 = undefined; var x428: u1 = undefined; fiatP384AddcarryxU32(&x427, &x428, x426, x414, x411); var x429: u32 = undefined; var x430: u1 = undefined; fiatP384AddcarryxU32(&x429, &x430, x428, x412, x409); var x431: u32 = undefined; var x432: u1 = undefined; fiatP384AddcarryxU32(&x431, &x432, x430, x410, x407); var x433: u32 = undefined; var x434: u1 = undefined; fiatP384AddcarryxU32(&x433, &x434, x432, x408, x405); var x435: u32 = undefined; var x436: u1 = undefined; fiatP384AddcarryxU32(&x435, &x436, x434, x406, x403); var x437: u32 = undefined; var x438: u1 = undefined; fiatP384AddcarryxU32(&x437, &x438, x436, x404, x401); var x439: u32 = undefined; var x440: u1 = undefined; fiatP384AddcarryxU32(&x439, &x440, x438, x402, x399); var x441: u32 = undefined; var x442: u1 = undefined; fiatP384AddcarryxU32(&x441, &x442, x440, x400, x397); const x443: u32 = (@intCast(u32, x442) + x398); var x444: u32 = undefined; var x445: u1 = undefined; fiatP384AddcarryxU32(&x444, &x445, 0x0, x372, x419); var x446: u32 = undefined; var x447: u1 = undefined; fiatP384AddcarryxU32(&x446, &x447, x445, x374, x421); var x448: u32 = undefined; var x449: u1 = undefined; fiatP384AddcarryxU32(&x448, &x449, x447, x376, x423); var x450: u32 = undefined; var x451: u1 = undefined; fiatP384AddcarryxU32(&x450, &x451, x449, x378, x425); var x452: u32 = undefined; var x453: u1 = undefined; fiatP384AddcarryxU32(&x452, &x453, x451, x380, x427); var x454: u32 = undefined; var x455: u1 = undefined; fiatP384AddcarryxU32(&x454, &x455, x453, x382, x429); var x456: u32 = undefined; var x457: u1 = undefined; fiatP384AddcarryxU32(&x456, &x457, x455, x384, x431); var x458: u32 = undefined; var x459: u1 = undefined; fiatP384AddcarryxU32(&x458, &x459, x457, x386, x433); var x460: u32 = undefined; var x461: u1 = undefined; fiatP384AddcarryxU32(&x460, &x461, x459, x388, x435); var x462: u32 = undefined; var x463: u1 = undefined; fiatP384AddcarryxU32(&x462, &x463, x461, x390, x437); var x464: u32 = undefined; var x465: u1 = undefined; fiatP384AddcarryxU32(&x464, &x465, x463, x392, x439); var x466: u32 = undefined; var x467: u1 = undefined; fiatP384AddcarryxU32(&x466, &x467, x465, x394, x441); var x468: u32 = undefined; var x469: u1 = undefined; fiatP384AddcarryxU32(&x468, &x469, x467, x396, x443); var x470: u32 = undefined; var x471: u32 = undefined; fiatP384MulxU32(&x470, &x471, x444, 0xffffffff); var x472: u32 = undefined; var x473: u32 = undefined; fiatP384MulxU32(&x472, &x473, x444, 0xffffffff); var x474: u32 = undefined; var x475: u32 = undefined; fiatP384MulxU32(&x474, &x475, x444, 0xffffffff); var x476: u32 = undefined; var x477: u32 = undefined; fiatP384MulxU32(&x476, &x477, x444, 0xffffffff); var x478: u32 = undefined; var x479: u32 = undefined; fiatP384MulxU32(&x478, &x479, x444, 0xffffffff); var x480: u32 = undefined; var x481: u32 = undefined; fiatP384MulxU32(&x480, &x481, x444, 0xffffffff); var x482: u32 = undefined; var x483: u32 = undefined; fiatP384MulxU32(&x482, &x483, x444, 0xffffffff); var x484: u32 = undefined; var x485: u32 = undefined; fiatP384MulxU32(&x484, &x485, x444, 0xfffffffe); var x486: u32 = undefined; var x487: u32 = undefined; fiatP384MulxU32(&x486, &x487, x444, 0xffffffff); var x488: u32 = undefined; var x489: u32 = undefined; fiatP384MulxU32(&x488, &x489, x444, 0xffffffff); var x490: u32 = undefined; var x491: u1 = undefined; fiatP384AddcarryxU32(&x490, &x491, 0x0, x487, x484); var x492: u32 = undefined; var x493: u1 = undefined; fiatP384AddcarryxU32(&x492, &x493, x491, x485, x482); var x494: u32 = undefined; var x495: u1 = undefined; fiatP384AddcarryxU32(&x494, &x495, x493, x483, x480); var x496: u32 = undefined; var x497: u1 = undefined; fiatP384AddcarryxU32(&x496, &x497, x495, x481, x478); var x498: u32 = undefined; var x499: u1 = undefined; fiatP384AddcarryxU32(&x498, &x499, x497, x479, x476); var x500: u32 = undefined; var x501: u1 = undefined; fiatP384AddcarryxU32(&x500, &x501, x499, x477, x474); var x502: u32 = undefined; var x503: u1 = undefined; fiatP384AddcarryxU32(&x502, &x503, x501, x475, x472); var x504: u32 = undefined; var x505: u1 = undefined; fiatP384AddcarryxU32(&x504, &x505, x503, x473, x470); const x506: u32 = (@intCast(u32, x505) + x471); var x507: u32 = undefined; var x508: u1 = undefined; fiatP384AddcarryxU32(&x507, &x508, 0x0, x444, x488); var x509: u32 = undefined; var x510: u1 = undefined; fiatP384AddcarryxU32(&x509, &x510, x508, x446, x489); var x511: u32 = undefined; var x512: u1 = undefined; fiatP384AddcarryxU32(&x511, &x512, x510, x448, @intCast(u32, 0x0)); var x513: u32 = undefined; var x514: u1 = undefined; fiatP384AddcarryxU32(&x513, &x514, x512, x450, x486); var x515: u32 = undefined; var x516: u1 = undefined; fiatP384AddcarryxU32(&x515, &x516, x514, x452, x490); var x517: u32 = undefined; var x518: u1 = undefined; fiatP384AddcarryxU32(&x517, &x518, x516, x454, x492); var x519: u32 = undefined; var x520: u1 = undefined; fiatP384AddcarryxU32(&x519, &x520, x518, x456, x494); var x521: u32 = undefined; var x522: u1 = undefined; fiatP384AddcarryxU32(&x521, &x522, x520, x458, x496); var x523: u32 = undefined; var x524: u1 = undefined; fiatP384AddcarryxU32(&x523, &x524, x522, x460, x498); var x525: u32 = undefined; var x526: u1 = undefined; fiatP384AddcarryxU32(&x525, &x526, x524, x462, x500); var x527: u32 = undefined; var x528: u1 = undefined; fiatP384AddcarryxU32(&x527, &x528, x526, x464, x502); var x529: u32 = undefined; var x530: u1 = undefined; fiatP384AddcarryxU32(&x529, &x530, x528, x466, x504); var x531: u32 = undefined; var x532: u1 = undefined; fiatP384AddcarryxU32(&x531, &x532, x530, x468, x506); const x533: u32 = (@intCast(u32, x532) + @intCast(u32, x469)); var x534: u32 = undefined; var x535: u32 = undefined; fiatP384MulxU32(&x534, &x535, x4, (arg2[11])); var x536: u32 = undefined; var x537: u32 = undefined; fiatP384MulxU32(&x536, &x537, x4, (arg2[10])); var x538: u32 = undefined; var x539: u32 = undefined; fiatP384MulxU32(&x538, &x539, x4, (arg2[9])); var x540: u32 = undefined; var x541: u32 = undefined; fiatP384MulxU32(&x540, &x541, x4, (arg2[8])); var x542: u32 = undefined; var x543: u32 = undefined; fiatP384MulxU32(&x542, &x543, x4, (arg2[7])); var x544: u32 = undefined; var x545: u32 = undefined; fiatP384MulxU32(&x544, &x545, x4, (arg2[6])); var x546: u32 = undefined; var x547: u32 = undefined; fiatP384MulxU32(&x546, &x547, x4, (arg2[5])); var x548: u32 = undefined; var x549: u32 = undefined; fiatP384MulxU32(&x548, &x549, x4, (arg2[4])); var x550: u32 = undefined; var x551: u32 = undefined; fiatP384MulxU32(&x550, &x551, x4, (arg2[3])); var x552: u32 = undefined; var x553: u32 = undefined; fiatP384MulxU32(&x552, &x553, x4, (arg2[2])); var x554: u32 = undefined; var x555: u32 = undefined; fiatP384MulxU32(&x554, &x555, x4, (arg2[1])); var x556: u32 = undefined; var x557: u32 = undefined; fiatP384MulxU32(&x556, &x557, x4, (arg2[0])); var x558: u32 = undefined; var x559: u1 = undefined; fiatP384AddcarryxU32(&x558, &x559, 0x0, x557, x554); var x560: u32 = undefined; var x561: u1 = undefined; fiatP384AddcarryxU32(&x560, &x561, x559, x555, x552); var x562: u32 = undefined; var x563: u1 = undefined; fiatP384AddcarryxU32(&x562, &x563, x561, x553, x550); var x564: u32 = undefined; var x565: u1 = undefined; fiatP384AddcarryxU32(&x564, &x565, x563, x551, x548); var x566: u32 = undefined; var x567: u1 = undefined; fiatP384AddcarryxU32(&x566, &x567, x565, x549, x546); var x568: u32 = undefined; var x569: u1 = undefined; fiatP384AddcarryxU32(&x568, &x569, x567, x547, x544); var x570: u32 = undefined; var x571: u1 = undefined; fiatP384AddcarryxU32(&x570, &x571, x569, x545, x542); var x572: u32 = undefined; var x573: u1 = undefined; fiatP384AddcarryxU32(&x572, &x573, x571, x543, x540); var x574: u32 = undefined; var x575: u1 = undefined; fiatP384AddcarryxU32(&x574, &x575, x573, x541, x538); var x576: u32 = undefined; var x577: u1 = undefined; fiatP384AddcarryxU32(&x576, &x577, x575, x539, x536); var x578: u32 = undefined; var x579: u1 = undefined; fiatP384AddcarryxU32(&x578, &x579, x577, x537, x534); const x580: u32 = (@intCast(u32, x579) + x535); var x581: u32 = undefined; var x582: u1 = undefined; fiatP384AddcarryxU32(&x581, &x582, 0x0, x509, x556); var x583: u32 = undefined; var x584: u1 = undefined; fiatP384AddcarryxU32(&x583, &x584, x582, x511, x558); var x585: u32 = undefined; var x586: u1 = undefined; fiatP384AddcarryxU32(&x585, &x586, x584, x513, x560); var x587: u32 = undefined; var x588: u1 = undefined; fiatP384AddcarryxU32(&x587, &x588, x586, x515, x562); var x589: u32 = undefined; var x590: u1 = undefined; fiatP384AddcarryxU32(&x589, &x590, x588, x517, x564); var x591: u32 = undefined; var x592: u1 = undefined; fiatP384AddcarryxU32(&x591, &x592, x590, x519, x566); var x593: u32 = undefined; var x594: u1 = undefined; fiatP384AddcarryxU32(&x593, &x594, x592, x521, x568); var x595: u32 = undefined; var x596: u1 = undefined; fiatP384AddcarryxU32(&x595, &x596, x594, x523, x570); var x597: u32 = undefined; var x598: u1 = undefined; fiatP384AddcarryxU32(&x597, &x598, x596, x525, x572); var x599: u32 = undefined; var x600: u1 = undefined; fiatP384AddcarryxU32(&x599, &x600, x598, x527, x574); var x601: u32 = undefined; var x602: u1 = undefined; fiatP384AddcarryxU32(&x601, &x602, x600, x529, x576); var x603: u32 = undefined; var x604: u1 = undefined; fiatP384AddcarryxU32(&x603, &x604, x602, x531, x578); var x605: u32 = undefined; var x606: u1 = undefined; fiatP384AddcarryxU32(&x605, &x606, x604, x533, x580); var x607: u32 = undefined; var x608: u32 = undefined; fiatP384MulxU32(&x607, &x608, x581, 0xffffffff); var x609: u32 = undefined; var x610: u32 = undefined; fiatP384MulxU32(&x609, &x610, x581, 0xffffffff); var x611: u32 = undefined; var x612: u32 = undefined; fiatP384MulxU32(&x611, &x612, x581, 0xffffffff); var x613: u32 = undefined; var x614: u32 = undefined; fiatP384MulxU32(&x613, &x614, x581, 0xffffffff); var x615: u32 = undefined; var x616: u32 = undefined; fiatP384MulxU32(&x615, &x616, x581, 0xffffffff); var x617: u32 = undefined; var x618: u32 = undefined; fiatP384MulxU32(&x617, &x618, x581, 0xffffffff); var x619: u32 = undefined; var x620: u32 = undefined; fiatP384MulxU32(&x619, &x620, x581, 0xffffffff); var x621: u32 = undefined; var x622: u32 = undefined; fiatP384MulxU32(&x621, &x622, x581, 0xfffffffe); var x623: u32 = undefined; var x624: u32 = undefined; fiatP384MulxU32(&x623, &x624, x581, 0xffffffff); var x625: u32 = undefined; var x626: u32 = undefined; fiatP384MulxU32(&x625, &x626, x581, 0xffffffff); var x627: u32 = undefined; var x628: u1 = undefined; fiatP384AddcarryxU32(&x627, &x628, 0x0, x624, x621); var x629: u32 = undefined; var x630: u1 = undefined; fiatP384AddcarryxU32(&x629, &x630, x628, x622, x619); var x631: u32 = undefined; var x632: u1 = undefined; fiatP384AddcarryxU32(&x631, &x632, x630, x620, x617); var x633: u32 = undefined; var x634: u1 = undefined; fiatP384AddcarryxU32(&x633, &x634, x632, x618, x615); var x635: u32 = undefined; var x636: u1 = undefined; fiatP384AddcarryxU32(&x635, &x636, x634, x616, x613); var x637: u32 = undefined; var x638: u1 = undefined; fiatP384AddcarryxU32(&x637, &x638, x636, x614, x611); var x639: u32 = undefined; var x640: u1 = undefined; fiatP384AddcarryxU32(&x639, &x640, x638, x612, x609); var x641: u32 = undefined; var x642: u1 = undefined; fiatP384AddcarryxU32(&x641, &x642, x640, x610, x607); const x643: u32 = (@intCast(u32, x642) + x608); var x644: u32 = undefined; var x645: u1 = undefined; fiatP384AddcarryxU32(&x644, &x645, 0x0, x581, x625); var x646: u32 = undefined; var x647: u1 = undefined; fiatP384AddcarryxU32(&x646, &x647, x645, x583, x626); var x648: u32 = undefined; var x649: u1 = undefined; fiatP384AddcarryxU32(&x648, &x649, x647, x585, @intCast(u32, 0x0)); var x650: u32 = undefined; var x651: u1 = undefined; fiatP384AddcarryxU32(&x650, &x651, x649, x587, x623); var x652: u32 = undefined; var x653: u1 = undefined; fiatP384AddcarryxU32(&x652, &x653, x651, x589, x627); var x654: u32 = undefined; var x655: u1 = undefined; fiatP384AddcarryxU32(&x654, &x655, x653, x591, x629); var x656: u32 = undefined; var x657: u1 = undefined; fiatP384AddcarryxU32(&x656, &x657, x655, x593, x631); var x658: u32 = undefined; var x659: u1 = undefined; fiatP384AddcarryxU32(&x658, &x659, x657, x595, x633); var x660: u32 = undefined; var x661: u1 = undefined; fiatP384AddcarryxU32(&x660, &x661, x659, x597, x635); var x662: u32 = undefined; var x663: u1 = undefined; fiatP384AddcarryxU32(&x662, &x663, x661, x599, x637); var x664: u32 = undefined; var x665: u1 = undefined; fiatP384AddcarryxU32(&x664, &x665, x663, x601, x639); var x666: u32 = undefined; var x667: u1 = undefined; fiatP384AddcarryxU32(&x666, &x667, x665, x603, x641); var x668: u32 = undefined; var x669: u1 = undefined; fiatP384AddcarryxU32(&x668, &x669, x667, x605, x643); const x670: u32 = (@intCast(u32, x669) + @intCast(u32, x606)); var x671: u32 = undefined; var x672: u32 = undefined; fiatP384MulxU32(&x671, &x672, x5, (arg2[11])); var x673: u32 = undefined; var x674: u32 = undefined; fiatP384MulxU32(&x673, &x674, x5, (arg2[10])); var x675: u32 = undefined; var x676: u32 = undefined; fiatP384MulxU32(&x675, &x676, x5, (arg2[9])); var x677: u32 = undefined; var x678: u32 = undefined; fiatP384MulxU32(&x677, &x678, x5, (arg2[8])); var x679: u32 = undefined; var x680: u32 = undefined; fiatP384MulxU32(&x679, &x680, x5, (arg2[7])); var x681: u32 = undefined; var x682: u32 = undefined; fiatP384MulxU32(&x681, &x682, x5, (arg2[6])); var x683: u32 = undefined; var x684: u32 = undefined; fiatP384MulxU32(&x683, &x684, x5, (arg2[5])); var x685: u32 = undefined; var x686: u32 = undefined; fiatP384MulxU32(&x685, &x686, x5, (arg2[4])); var x687: u32 = undefined; var x688: u32 = undefined; fiatP384MulxU32(&x687, &x688, x5, (arg2[3])); var x689: u32 = undefined; var x690: u32 = undefined; fiatP384MulxU32(&x689, &x690, x5, (arg2[2])); var x691: u32 = undefined; var x692: u32 = undefined; fiatP384MulxU32(&x691, &x692, x5, (arg2[1])); var x693: u32 = undefined; var x694: u32 = undefined; fiatP384MulxU32(&x693, &x694, x5, (arg2[0])); var x695: u32 = undefined; var x696: u1 = undefined; fiatP384AddcarryxU32(&x695, &x696, 0x0, x694, x691); var x697: u32 = undefined; var x698: u1 = undefined; fiatP384AddcarryxU32(&x697, &x698, x696, x692, x689); var x699: u32 = undefined; var x700: u1 = undefined; fiatP384AddcarryxU32(&x699, &x700, x698, x690, x687); var x701: u32 = undefined; var x702: u1 = undefined; fiatP384AddcarryxU32(&x701, &x702, x700, x688, x685); var x703: u32 = undefined; var x704: u1 = undefined; fiatP384AddcarryxU32(&x703, &x704, x702, x686, x683); var x705: u32 = undefined; var x706: u1 = undefined; fiatP384AddcarryxU32(&x705, &x706, x704, x684, x681); var x707: u32 = undefined; var x708: u1 = undefined; fiatP384AddcarryxU32(&x707, &x708, x706, x682, x679); var x709: u32 = undefined; var x710: u1 = undefined; fiatP384AddcarryxU32(&x709, &x710, x708, x680, x677); var x711: u32 = undefined; var x712: u1 = undefined; fiatP384AddcarryxU32(&x711, &x712, x710, x678, x675); var x713: u32 = undefined; var x714: u1 = undefined; fiatP384AddcarryxU32(&x713, &x714, x712, x676, x673); var x715: u32 = undefined; var x716: u1 = undefined; fiatP384AddcarryxU32(&x715, &x716, x714, x674, x671); const x717: u32 = (@intCast(u32, x716) + x672); var x718: u32 = undefined; var x719: u1 = undefined; fiatP384AddcarryxU32(&x718, &x719, 0x0, x646, x693); var x720: u32 = undefined; var x721: u1 = undefined; fiatP384AddcarryxU32(&x720, &x721, x719, x648, x695); var x722: u32 = undefined; var x723: u1 = undefined; fiatP384AddcarryxU32(&x722, &x723, x721, x650, x697); var x724: u32 = undefined; var x725: u1 = undefined; fiatP384AddcarryxU32(&x724, &x725, x723, x652, x699); var x726: u32 = undefined; var x727: u1 = undefined; fiatP384AddcarryxU32(&x726, &x727, x725, x654, x701); var x728: u32 = undefined; var x729: u1 = undefined; fiatP384AddcarryxU32(&x728, &x729, x727, x656, x703); var x730: u32 = undefined; var x731: u1 = undefined; fiatP384AddcarryxU32(&x730, &x731, x729, x658, x705); var x732: u32 = undefined; var x733: u1 = undefined; fiatP384AddcarryxU32(&x732, &x733, x731, x660, x707); var x734: u32 = undefined; var x735: u1 = undefined; fiatP384AddcarryxU32(&x734, &x735, x733, x662, x709); var x736: u32 = undefined; var x737: u1 = undefined; fiatP384AddcarryxU32(&x736, &x737, x735, x664, x711); var x738: u32 = undefined; var x739: u1 = undefined; fiatP384AddcarryxU32(&x738, &x739, x737, x666, x713); var x740: u32 = undefined; var x741: u1 = undefined; fiatP384AddcarryxU32(&x740, &x741, x739, x668, x715); var x742: u32 = undefined; var x743: u1 = undefined; fiatP384AddcarryxU32(&x742, &x743, x741, x670, x717); var x744: u32 = undefined; var x745: u32 = undefined; fiatP384MulxU32(&x744, &x745, x718, 0xffffffff); var x746: u32 = undefined; var x747: u32 = undefined; fiatP384MulxU32(&x746, &x747, x718, 0xffffffff); var x748: u32 = undefined; var x749: u32 = undefined; fiatP384MulxU32(&x748, &x749, x718, 0xffffffff); var x750: u32 = undefined; var x751: u32 = undefined; fiatP384MulxU32(&x750, &x751, x718, 0xffffffff); var x752: u32 = undefined; var x753: u32 = undefined; fiatP384MulxU32(&x752, &x753, x718, 0xffffffff); var x754: u32 = undefined; var x755: u32 = undefined; fiatP384MulxU32(&x754, &x755, x718, 0xffffffff); var x756: u32 = undefined; var x757: u32 = undefined; fiatP384MulxU32(&x756, &x757, x718, 0xffffffff); var x758: u32 = undefined; var x759: u32 = undefined; fiatP384MulxU32(&x758, &x759, x718, 0xfffffffe); var x760: u32 = undefined; var x761: u32 = undefined; fiatP384MulxU32(&x760, &x761, x718, 0xffffffff); var x762: u32 = undefined; var x763: u32 = undefined; fiatP384MulxU32(&x762, &x763, x718, 0xffffffff); var x764: u32 = undefined; var x765: u1 = undefined; fiatP384AddcarryxU32(&x764, &x765, 0x0, x761, x758); var x766: u32 = undefined; var x767: u1 = undefined; fiatP384AddcarryxU32(&x766, &x767, x765, x759, x756); var x768: u32 = undefined; var x769: u1 = undefined; fiatP384AddcarryxU32(&x768, &x769, x767, x757, x754); var x770: u32 = undefined; var x771: u1 = undefined; fiatP384AddcarryxU32(&x770, &x771, x769, x755, x752); var x772: u32 = undefined; var x773: u1 = undefined; fiatP384AddcarryxU32(&x772, &x773, x771, x753, x750); var x774: u32 = undefined; var x775: u1 = undefined; fiatP384AddcarryxU32(&x774, &x775, x773, x751, x748); var x776: u32 = undefined; var x777: u1 = undefined; fiatP384AddcarryxU32(&x776, &x777, x775, x749, x746); var x778: u32 = undefined; var x779: u1 = undefined; fiatP384AddcarryxU32(&x778, &x779, x777, x747, x744); const x780: u32 = (@intCast(u32, x779) + x745); var x781: u32 = undefined; var x782: u1 = undefined; fiatP384AddcarryxU32(&x781, &x782, 0x0, x718, x762); var x783: u32 = undefined; var x784: u1 = undefined; fiatP384AddcarryxU32(&x783, &x784, x782, x720, x763); var x785: u32 = undefined; var x786: u1 = undefined; fiatP384AddcarryxU32(&x785, &x786, x784, x722, @intCast(u32, 0x0)); var x787: u32 = undefined; var x788: u1 = undefined; fiatP384AddcarryxU32(&x787, &x788, x786, x724, x760); var x789: u32 = undefined; var x790: u1 = undefined; fiatP384AddcarryxU32(&x789, &x790, x788, x726, x764); var x791: u32 = undefined; var x792: u1 = undefined; fiatP384AddcarryxU32(&x791, &x792, x790, x728, x766); var x793: u32 = undefined; var x794: u1 = undefined; fiatP384AddcarryxU32(&x793, &x794, x792, x730, x768); var x795: u32 = undefined; var x796: u1 = undefined; fiatP384AddcarryxU32(&x795, &x796, x794, x732, x770); var x797: u32 = undefined; var x798: u1 = undefined; fiatP384AddcarryxU32(&x797, &x798, x796, x734, x772); var x799: u32 = undefined; var x800: u1 = undefined; fiatP384AddcarryxU32(&x799, &x800, x798, x736, x774); var x801: u32 = undefined; var x802: u1 = undefined; fiatP384AddcarryxU32(&x801, &x802, x800, x738, x776); var x803: u32 = undefined; var x804: u1 = undefined; fiatP384AddcarryxU32(&x803, &x804, x802, x740, x778); var x805: u32 = undefined; var x806: u1 = undefined; fiatP384AddcarryxU32(&x805, &x806, x804, x742, x780); const x807: u32 = (@intCast(u32, x806) + @intCast(u32, x743)); var x808: u32 = undefined; var x809: u32 = undefined; fiatP384MulxU32(&x808, &x809, x6, (arg2[11])); var x810: u32 = undefined; var x811: u32 = undefined; fiatP384MulxU32(&x810, &x811, x6, (arg2[10])); var x812: u32 = undefined; var x813: u32 = undefined; fiatP384MulxU32(&x812, &x813, x6, (arg2[9])); var x814: u32 = undefined; var x815: u32 = undefined; fiatP384MulxU32(&x814, &x815, x6, (arg2[8])); var x816: u32 = undefined; var x817: u32 = undefined; fiatP384MulxU32(&x816, &x817, x6, (arg2[7])); var x818: u32 = undefined; var x819: u32 = undefined; fiatP384MulxU32(&x818, &x819, x6, (arg2[6])); var x820: u32 = undefined; var x821: u32 = undefined; fiatP384MulxU32(&x820, &x821, x6, (arg2[5])); var x822: u32 = undefined; var x823: u32 = undefined; fiatP384MulxU32(&x822, &x823, x6, (arg2[4])); var x824: u32 = undefined; var x825: u32 = undefined; fiatP384MulxU32(&x824, &x825, x6, (arg2[3])); var x826: u32 = undefined; var x827: u32 = undefined; fiatP384MulxU32(&x826, &x827, x6, (arg2[2])); var x828: u32 = undefined; var x829: u32 = undefined; fiatP384MulxU32(&x828, &x829, x6, (arg2[1])); var x830: u32 = undefined; var x831: u32 = undefined; fiatP384MulxU32(&x830, &x831, x6, (arg2[0])); var x832: u32 = undefined; var x833: u1 = undefined; fiatP384AddcarryxU32(&x832, &x833, 0x0, x831, x828); var x834: u32 = undefined; var x835: u1 = undefined; fiatP384AddcarryxU32(&x834, &x835, x833, x829, x826); var x836: u32 = undefined; var x837: u1 = undefined; fiatP384AddcarryxU32(&x836, &x837, x835, x827, x824); var x838: u32 = undefined; var x839: u1 = undefined; fiatP384AddcarryxU32(&x838, &x839, x837, x825, x822); var x840: u32 = undefined; var x841: u1 = undefined; fiatP384AddcarryxU32(&x840, &x841, x839, x823, x820); var x842: u32 = undefined; var x843: u1 = undefined; fiatP384AddcarryxU32(&x842, &x843, x841, x821, x818); var x844: u32 = undefined; var x845: u1 = undefined; fiatP384AddcarryxU32(&x844, &x845, x843, x819, x816); var x846: u32 = undefined; var x847: u1 = undefined; fiatP384AddcarryxU32(&x846, &x847, x845, x817, x814); var x848: u32 = undefined; var x849: u1 = undefined; fiatP384AddcarryxU32(&x848, &x849, x847, x815, x812); var x850: u32 = undefined; var x851: u1 = undefined; fiatP384AddcarryxU32(&x850, &x851, x849, x813, x810); var x852: u32 = undefined; var x853: u1 = undefined; fiatP384AddcarryxU32(&x852, &x853, x851, x811, x808); const x854: u32 = (@intCast(u32, x853) + x809); var x855: u32 = undefined; var x856: u1 = undefined; fiatP384AddcarryxU32(&x855, &x856, 0x0, x783, x830); var x857: u32 = undefined; var x858: u1 = undefined; fiatP384AddcarryxU32(&x857, &x858, x856, x785, x832); var x859: u32 = undefined; var x860: u1 = undefined; fiatP384AddcarryxU32(&x859, &x860, x858, x787, x834); var x861: u32 = undefined; var x862: u1 = undefined; fiatP384AddcarryxU32(&x861, &x862, x860, x789, x836); var x863: u32 = undefined; var x864: u1 = undefined; fiatP384AddcarryxU32(&x863, &x864, x862, x791, x838); var x865: u32 = undefined; var x866: u1 = undefined; fiatP384AddcarryxU32(&x865, &x866, x864, x793, x840); var x867: u32 = undefined; var x868: u1 = undefined; fiatP384AddcarryxU32(&x867, &x868, x866, x795, x842); var x869: u32 = undefined; var x870: u1 = undefined; fiatP384AddcarryxU32(&x869, &x870, x868, x797, x844); var x871: u32 = undefined; var x872: u1 = undefined; fiatP384AddcarryxU32(&x871, &x872, x870, x799, x846); var x873: u32 = undefined; var x874: u1 = undefined; fiatP384AddcarryxU32(&x873, &x874, x872, x801, x848); var x875: u32 = undefined; var x876: u1 = undefined; fiatP384AddcarryxU32(&x875, &x876, x874, x803, x850); var x877: u32 = undefined; var x878: u1 = undefined; fiatP384AddcarryxU32(&x877, &x878, x876, x805, x852); var x879: u32 = undefined; var x880: u1 = undefined; fiatP384AddcarryxU32(&x879, &x880, x878, x807, x854); var x881: u32 = undefined; var x882: u32 = undefined; fiatP384MulxU32(&x881, &x882, x855, 0xffffffff); var x883: u32 = undefined; var x884: u32 = undefined; fiatP384MulxU32(&x883, &x884, x855, 0xffffffff); var x885: u32 = undefined; var x886: u32 = undefined; fiatP384MulxU32(&x885, &x886, x855, 0xffffffff); var x887: u32 = undefined; var x888: u32 = undefined; fiatP384MulxU32(&x887, &x888, x855, 0xffffffff); var x889: u32 = undefined; var x890: u32 = undefined; fiatP384MulxU32(&x889, &x890, x855, 0xffffffff); var x891: u32 = undefined; var x892: u32 = undefined; fiatP384MulxU32(&x891, &x892, x855, 0xffffffff); var x893: u32 = undefined; var x894: u32 = undefined; fiatP384MulxU32(&x893, &x894, x855, 0xffffffff); var x895: u32 = undefined; var x896: u32 = undefined; fiatP384MulxU32(&x895, &x896, x855, 0xfffffffe); var x897: u32 = undefined; var x898: u32 = undefined; fiatP384MulxU32(&x897, &x898, x855, 0xffffffff); var x899: u32 = undefined; var x900: u32 = undefined; fiatP384MulxU32(&x899, &x900, x855, 0xffffffff); var x901: u32 = undefined; var x902: u1 = undefined; fiatP384AddcarryxU32(&x901, &x902, 0x0, x898, x895); var x903: u32 = undefined; var x904: u1 = undefined; fiatP384AddcarryxU32(&x903, &x904, x902, x896, x893); var x905: u32 = undefined; var x906: u1 = undefined; fiatP384AddcarryxU32(&x905, &x906, x904, x894, x891); var x907: u32 = undefined; var x908: u1 = undefined; fiatP384AddcarryxU32(&x907, &x908, x906, x892, x889); var x909: u32 = undefined; var x910: u1 = undefined; fiatP384AddcarryxU32(&x909, &x910, x908, x890, x887); var x911: u32 = undefined; var x912: u1 = undefined; fiatP384AddcarryxU32(&x911, &x912, x910, x888, x885); var x913: u32 = undefined; var x914: u1 = undefined; fiatP384AddcarryxU32(&x913, &x914, x912, x886, x883); var x915: u32 = undefined; var x916: u1 = undefined; fiatP384AddcarryxU32(&x915, &x916, x914, x884, x881); const x917: u32 = (@intCast(u32, x916) + x882); var x918: u32 = undefined; var x919: u1 = undefined; fiatP384AddcarryxU32(&x918, &x919, 0x0, x855, x899); var x920: u32 = undefined; var x921: u1 = undefined; fiatP384AddcarryxU32(&x920, &x921, x919, x857, x900); var x922: u32 = undefined; var x923: u1 = undefined; fiatP384AddcarryxU32(&x922, &x923, x921, x859, @intCast(u32, 0x0)); var x924: u32 = undefined; var x925: u1 = undefined; fiatP384AddcarryxU32(&x924, &x925, x923, x861, x897); var x926: u32 = undefined; var x927: u1 = undefined; fiatP384AddcarryxU32(&x926, &x927, x925, x863, x901); var x928: u32 = undefined; var x929: u1 = undefined; fiatP384AddcarryxU32(&x928, &x929, x927, x865, x903); var x930: u32 = undefined; var x931: u1 = undefined; fiatP384AddcarryxU32(&x930, &x931, x929, x867, x905); var x932: u32 = undefined; var x933: u1 = undefined; fiatP384AddcarryxU32(&x932, &x933, x931, x869, x907); var x934: u32 = undefined; var x935: u1 = undefined; fiatP384AddcarryxU32(&x934, &x935, x933, x871, x909); var x936: u32 = undefined; var x937: u1 = undefined; fiatP384AddcarryxU32(&x936, &x937, x935, x873, x911); var x938: u32 = undefined; var x939: u1 = undefined; fiatP384AddcarryxU32(&x938, &x939, x937, x875, x913); var x940: u32 = undefined; var x941: u1 = undefined; fiatP384AddcarryxU32(&x940, &x941, x939, x877, x915); var x942: u32 = undefined; var x943: u1 = undefined; fiatP384AddcarryxU32(&x942, &x943, x941, x879, x917); const x944: u32 = (@intCast(u32, x943) + @intCast(u32, x880)); var x945: u32 = undefined; var x946: u32 = undefined; fiatP384MulxU32(&x945, &x946, x7, (arg2[11])); var x947: u32 = undefined; var x948: u32 = undefined; fiatP384MulxU32(&x947, &x948, x7, (arg2[10])); var x949: u32 = undefined; var x950: u32 = undefined; fiatP384MulxU32(&x949, &x950, x7, (arg2[9])); var x951: u32 = undefined; var x952: u32 = undefined; fiatP384MulxU32(&x951, &x952, x7, (arg2[8])); var x953: u32 = undefined; var x954: u32 = undefined; fiatP384MulxU32(&x953, &x954, x7, (arg2[7])); var x955: u32 = undefined; var x956: u32 = undefined; fiatP384MulxU32(&x955, &x956, x7, (arg2[6])); var x957: u32 = undefined; var x958: u32 = undefined; fiatP384MulxU32(&x957, &x958, x7, (arg2[5])); var x959: u32 = undefined; var x960: u32 = undefined; fiatP384MulxU32(&x959, &x960, x7, (arg2[4])); var x961: u32 = undefined; var x962: u32 = undefined; fiatP384MulxU32(&x961, &x962, x7, (arg2[3])); var x963: u32 = undefined; var x964: u32 = undefined; fiatP384MulxU32(&x963, &x964, x7, (arg2[2])); var x965: u32 = undefined; var x966: u32 = undefined; fiatP384MulxU32(&x965, &x966, x7, (arg2[1])); var x967: u32 = undefined; var x968: u32 = undefined; fiatP384MulxU32(&x967, &x968, x7, (arg2[0])); var x969: u32 = undefined; var x970: u1 = undefined; fiatP384AddcarryxU32(&x969, &x970, 0x0, x968, x965); var x971: u32 = undefined; var x972: u1 = undefined; fiatP384AddcarryxU32(&x971, &x972, x970, x966, x963); var x973: u32 = undefined; var x974: u1 = undefined; fiatP384AddcarryxU32(&x973, &x974, x972, x964, x961); var x975: u32 = undefined; var x976: u1 = undefined; fiatP384AddcarryxU32(&x975, &x976, x974, x962, x959); var x977: u32 = undefined; var x978: u1 = undefined; fiatP384AddcarryxU32(&x977, &x978, x976, x960, x957); var x979: u32 = undefined; var x980: u1 = undefined; fiatP384AddcarryxU32(&x979, &x980, x978, x958, x955); var x981: u32 = undefined; var x982: u1 = undefined; fiatP384AddcarryxU32(&x981, &x982, x980, x956, x953); var x983: u32 = undefined; var x984: u1 = undefined; fiatP384AddcarryxU32(&x983, &x984, x982, x954, x951); var x985: u32 = undefined; var x986: u1 = undefined; fiatP384AddcarryxU32(&x985, &x986, x984, x952, x949); var x987: u32 = undefined; var x988: u1 = undefined; fiatP384AddcarryxU32(&x987, &x988, x986, x950, x947); var x989: u32 = undefined; var x990: u1 = undefined; fiatP384AddcarryxU32(&x989, &x990, x988, x948, x945); const x991: u32 = (@intCast(u32, x990) + x946); var x992: u32 = undefined; var x993: u1 = undefined; fiatP384AddcarryxU32(&x992, &x993, 0x0, x920, x967); var x994: u32 = undefined; var x995: u1 = undefined; fiatP384AddcarryxU32(&x994, &x995, x993, x922, x969); var x996: u32 = undefined; var x997: u1 = undefined; fiatP384AddcarryxU32(&x996, &x997, x995, x924, x971); var x998: u32 = undefined; var x999: u1 = undefined; fiatP384AddcarryxU32(&x998, &x999, x997, x926, x973); var x1000: u32 = undefined; var x1001: u1 = undefined; fiatP384AddcarryxU32(&x1000, &x1001, x999, x928, x975); var x1002: u32 = undefined; var x1003: u1 = undefined; fiatP384AddcarryxU32(&x1002, &x1003, x1001, x930, x977); var x1004: u32 = undefined; var x1005: u1 = undefined; fiatP384AddcarryxU32(&x1004, &x1005, x1003, x932, x979); var x1006: u32 = undefined; var x1007: u1 = undefined; fiatP384AddcarryxU32(&x1006, &x1007, x1005, x934, x981); var x1008: u32 = undefined; var x1009: u1 = undefined; fiatP384AddcarryxU32(&x1008, &x1009, x1007, x936, x983); var x1010: u32 = undefined; var x1011: u1 = undefined; fiatP384AddcarryxU32(&x1010, &x1011, x1009, x938, x985); var x1012: u32 = undefined; var x1013: u1 = undefined; fiatP384AddcarryxU32(&x1012, &x1013, x1011, x940, x987); var x1014: u32 = undefined; var x1015: u1 = undefined; fiatP384AddcarryxU32(&x1014, &x1015, x1013, x942, x989); var x1016: u32 = undefined; var x1017: u1 = undefined; fiatP384AddcarryxU32(&x1016, &x1017, x1015, x944, x991); var x1018: u32 = undefined; var x1019: u32 = undefined; fiatP384MulxU32(&x1018, &x1019, x992, 0xffffffff); var x1020: u32 = undefined; var x1021: u32 = undefined; fiatP384MulxU32(&x1020, &x1021, x992, 0xffffffff); var x1022: u32 = undefined; var x1023: u32 = undefined; fiatP384MulxU32(&x1022, &x1023, x992, 0xffffffff); var x1024: u32 = undefined; var x1025: u32 = undefined; fiatP384MulxU32(&x1024, &x1025, x992, 0xffffffff); var x1026: u32 = undefined; var x1027: u32 = undefined; fiatP384MulxU32(&x1026, &x1027, x992, 0xffffffff); var x1028: u32 = undefined; var x1029: u32 = undefined; fiatP384MulxU32(&x1028, &x1029, x992, 0xffffffff); var x1030: u32 = undefined; var x1031: u32 = undefined; fiatP384MulxU32(&x1030, &x1031, x992, 0xffffffff); var x1032: u32 = undefined; var x1033: u32 = undefined; fiatP384MulxU32(&x1032, &x1033, x992, 0xfffffffe); var x1034: u32 = undefined; var x1035: u32 = undefined; fiatP384MulxU32(&x1034, &x1035, x992, 0xffffffff); var x1036: u32 = undefined; var x1037: u32 = undefined; fiatP384MulxU32(&x1036, &x1037, x992, 0xffffffff); var x1038: u32 = undefined; var x1039: u1 = undefined; fiatP384AddcarryxU32(&x1038, &x1039, 0x0, x1035, x1032); var x1040: u32 = undefined; var x1041: u1 = undefined; fiatP384AddcarryxU32(&x1040, &x1041, x1039, x1033, x1030); var x1042: u32 = undefined; var x1043: u1 = undefined; fiatP384AddcarryxU32(&x1042, &x1043, x1041, x1031, x1028); var x1044: u32 = undefined; var x1045: u1 = undefined; fiatP384AddcarryxU32(&x1044, &x1045, x1043, x1029, x1026); var x1046: u32 = undefined; var x1047: u1 = undefined; fiatP384AddcarryxU32(&x1046, &x1047, x1045, x1027, x1024); var x1048: u32 = undefined; var x1049: u1 = undefined; fiatP384AddcarryxU32(&x1048, &x1049, x1047, x1025, x1022); var x1050: u32 = undefined; var x1051: u1 = undefined; fiatP384AddcarryxU32(&x1050, &x1051, x1049, x1023, x1020); var x1052: u32 = undefined; var x1053: u1 = undefined; fiatP384AddcarryxU32(&x1052, &x1053, x1051, x1021, x1018); const x1054: u32 = (@intCast(u32, x1053) + x1019); var x1055: u32 = undefined; var x1056: u1 = undefined; fiatP384AddcarryxU32(&x1055, &x1056, 0x0, x992, x1036); var x1057: u32 = undefined; var x1058: u1 = undefined; fiatP384AddcarryxU32(&x1057, &x1058, x1056, x994, x1037); var x1059: u32 = undefined; var x1060: u1 = undefined; fiatP384AddcarryxU32(&x1059, &x1060, x1058, x996, @intCast(u32, 0x0)); var x1061: u32 = undefined; var x1062: u1 = undefined; fiatP384AddcarryxU32(&x1061, &x1062, x1060, x998, x1034); var x1063: u32 = undefined; var x1064: u1 = undefined; fiatP384AddcarryxU32(&x1063, &x1064, x1062, x1000, x1038); var x1065: u32 = undefined; var x1066: u1 = undefined; fiatP384AddcarryxU32(&x1065, &x1066, x1064, x1002, x1040); var x1067: u32 = undefined; var x1068: u1 = undefined; fiatP384AddcarryxU32(&x1067, &x1068, x1066, x1004, x1042); var x1069: u32 = undefined; var x1070: u1 = undefined; fiatP384AddcarryxU32(&x1069, &x1070, x1068, x1006, x1044); var x1071: u32 = undefined; var x1072: u1 = undefined; fiatP384AddcarryxU32(&x1071, &x1072, x1070, x1008, x1046); var x1073: u32 = undefined; var x1074: u1 = undefined; fiatP384AddcarryxU32(&x1073, &x1074, x1072, x1010, x1048); var x1075: u32 = undefined; var x1076: u1 = undefined; fiatP384AddcarryxU32(&x1075, &x1076, x1074, x1012, x1050); var x1077: u32 = undefined; var x1078: u1 = undefined; fiatP384AddcarryxU32(&x1077, &x1078, x1076, x1014, x1052); var x1079: u32 = undefined; var x1080: u1 = undefined; fiatP384AddcarryxU32(&x1079, &x1080, x1078, x1016, x1054); const x1081: u32 = (@intCast(u32, x1080) + @intCast(u32, x1017)); var x1082: u32 = undefined; var x1083: u32 = undefined; fiatP384MulxU32(&x1082, &x1083, x8, (arg2[11])); var x1084: u32 = undefined; var x1085: u32 = undefined; fiatP384MulxU32(&x1084, &x1085, x8, (arg2[10])); var x1086: u32 = undefined; var x1087: u32 = undefined; fiatP384MulxU32(&x1086, &x1087, x8, (arg2[9])); var x1088: u32 = undefined; var x1089: u32 = undefined; fiatP384MulxU32(&x1088, &x1089, x8, (arg2[8])); var x1090: u32 = undefined; var x1091: u32 = undefined; fiatP384MulxU32(&x1090, &x1091, x8, (arg2[7])); var x1092: u32 = undefined; var x1093: u32 = undefined; fiatP384MulxU32(&x1092, &x1093, x8, (arg2[6])); var x1094: u32 = undefined; var x1095: u32 = undefined; fiatP384MulxU32(&x1094, &x1095, x8, (arg2[5])); var x1096: u32 = undefined; var x1097: u32 = undefined; fiatP384MulxU32(&x1096, &x1097, x8, (arg2[4])); var x1098: u32 = undefined; var x1099: u32 = undefined; fiatP384MulxU32(&x1098, &x1099, x8, (arg2[3])); var x1100: u32 = undefined; var x1101: u32 = undefined; fiatP384MulxU32(&x1100, &x1101, x8, (arg2[2])); var x1102: u32 = undefined; var x1103: u32 = undefined; fiatP384MulxU32(&x1102, &x1103, x8, (arg2[1])); var x1104: u32 = undefined; var x1105: u32 = undefined; fiatP384MulxU32(&x1104, &x1105, x8, (arg2[0])); var x1106: u32 = undefined; var x1107: u1 = undefined; fiatP384AddcarryxU32(&x1106, &x1107, 0x0, x1105, x1102); var x1108: u32 = undefined; var x1109: u1 = undefined; fiatP384AddcarryxU32(&x1108, &x1109, x1107, x1103, x1100); var x1110: u32 = undefined; var x1111: u1 = undefined; fiatP384AddcarryxU32(&x1110, &x1111, x1109, x1101, x1098); var x1112: u32 = undefined; var x1113: u1 = undefined; fiatP384AddcarryxU32(&x1112, &x1113, x1111, x1099, x1096); var x1114: u32 = undefined; var x1115: u1 = undefined; fiatP384AddcarryxU32(&x1114, &x1115, x1113, x1097, x1094); var x1116: u32 = undefined; var x1117: u1 = undefined; fiatP384AddcarryxU32(&x1116, &x1117, x1115, x1095, x1092); var x1118: u32 = undefined; var x1119: u1 = undefined; fiatP384AddcarryxU32(&x1118, &x1119, x1117, x1093, x1090); var x1120: u32 = undefined; var x1121: u1 = undefined; fiatP384AddcarryxU32(&x1120, &x1121, x1119, x1091, x1088); var x1122: u32 = undefined; var x1123: u1 = undefined; fiatP384AddcarryxU32(&x1122, &x1123, x1121, x1089, x1086); var x1124: u32 = undefined; var x1125: u1 = undefined; fiatP384AddcarryxU32(&x1124, &x1125, x1123, x1087, x1084); var x1126: u32 = undefined; var x1127: u1 = undefined; fiatP384AddcarryxU32(&x1126, &x1127, x1125, x1085, x1082); const x1128: u32 = (@intCast(u32, x1127) + x1083); var x1129: u32 = undefined; var x1130: u1 = undefined; fiatP384AddcarryxU32(&x1129, &x1130, 0x0, x1057, x1104); var x1131: u32 = undefined; var x1132: u1 = undefined; fiatP384AddcarryxU32(&x1131, &x1132, x1130, x1059, x1106); var x1133: u32 = undefined; var x1134: u1 = undefined; fiatP384AddcarryxU32(&x1133, &x1134, x1132, x1061, x1108); var x1135: u32 = undefined; var x1136: u1 = undefined; fiatP384AddcarryxU32(&x1135, &x1136, x1134, x1063, x1110); var x1137: u32 = undefined; var x1138: u1 = undefined; fiatP384AddcarryxU32(&x1137, &x1138, x1136, x1065, x1112); var x1139: u32 = undefined; var x1140: u1 = undefined; fiatP384AddcarryxU32(&x1139, &x1140, x1138, x1067, x1114); var x1141: u32 = undefined; var x1142: u1 = undefined; fiatP384AddcarryxU32(&x1141, &x1142, x1140, x1069, x1116); var x1143: u32 = undefined; var x1144: u1 = undefined; fiatP384AddcarryxU32(&x1143, &x1144, x1142, x1071, x1118); var x1145: u32 = undefined; var x1146: u1 = undefined; fiatP384AddcarryxU32(&x1145, &x1146, x1144, x1073, x1120); var x1147: u32 = undefined; var x1148: u1 = undefined; fiatP384AddcarryxU32(&x1147, &x1148, x1146, x1075, x1122); var x1149: u32 = undefined; var x1150: u1 = undefined; fiatP384AddcarryxU32(&x1149, &x1150, x1148, x1077, x1124); var x1151: u32 = undefined; var x1152: u1 = undefined; fiatP384AddcarryxU32(&x1151, &x1152, x1150, x1079, x1126); var x1153: u32 = undefined; var x1154: u1 = undefined; fiatP384AddcarryxU32(&x1153, &x1154, x1152, x1081, x1128); var x1155: u32 = undefined; var x1156: u32 = undefined; fiatP384MulxU32(&x1155, &x1156, x1129, 0xffffffff); var x1157: u32 = undefined; var x1158: u32 = undefined; fiatP384MulxU32(&x1157, &x1158, x1129, 0xffffffff); var x1159: u32 = undefined; var x1160: u32 = undefined; fiatP384MulxU32(&x1159, &x1160, x1129, 0xffffffff); var x1161: u32 = undefined; var x1162: u32 = undefined; fiatP384MulxU32(&x1161, &x1162, x1129, 0xffffffff); var x1163: u32 = undefined; var x1164: u32 = undefined; fiatP384MulxU32(&x1163, &x1164, x1129, 0xffffffff); var x1165: u32 = undefined; var x1166: u32 = undefined; fiatP384MulxU32(&x1165, &x1166, x1129, 0xffffffff); var x1167: u32 = undefined; var x1168: u32 = undefined; fiatP384MulxU32(&x1167, &x1168, x1129, 0xffffffff); var x1169: u32 = undefined; var x1170: u32 = undefined; fiatP384MulxU32(&x1169, &x1170, x1129, 0xfffffffe); var x1171: u32 = undefined; var x1172: u32 = undefined; fiatP384MulxU32(&x1171, &x1172, x1129, 0xffffffff); var x1173: u32 = undefined; var x1174: u32 = undefined; fiatP384MulxU32(&x1173, &x1174, x1129, 0xffffffff); var x1175: u32 = undefined; var x1176: u1 = undefined; fiatP384AddcarryxU32(&x1175, &x1176, 0x0, x1172, x1169); var x1177: u32 = undefined; var x1178: u1 = undefined; fiatP384AddcarryxU32(&x1177, &x1178, x1176, x1170, x1167); var x1179: u32 = undefined; var x1180: u1 = undefined; fiatP384AddcarryxU32(&x1179, &x1180, x1178, x1168, x1165); var x1181: u32 = undefined; var x1182: u1 = undefined; fiatP384AddcarryxU32(&x1181, &x1182, x1180, x1166, x1163); var x1183: u32 = undefined; var x1184: u1 = undefined; fiatP384AddcarryxU32(&x1183, &x1184, x1182, x1164, x1161); var x1185: u32 = undefined; var x1186: u1 = undefined; fiatP384AddcarryxU32(&x1185, &x1186, x1184, x1162, x1159); var x1187: u32 = undefined; var x1188: u1 = undefined; fiatP384AddcarryxU32(&x1187, &x1188, x1186, x1160, x1157); var x1189: u32 = undefined; var x1190: u1 = undefined; fiatP384AddcarryxU32(&x1189, &x1190, x1188, x1158, x1155); const x1191: u32 = (@intCast(u32, x1190) + x1156); var x1192: u32 = undefined; var x1193: u1 = undefined; fiatP384AddcarryxU32(&x1192, &x1193, 0x0, x1129, x1173); var x1194: u32 = undefined; var x1195: u1 = undefined; fiatP384AddcarryxU32(&x1194, &x1195, x1193, x1131, x1174); var x1196: u32 = undefined; var x1197: u1 = undefined; fiatP384AddcarryxU32(&x1196, &x1197, x1195, x1133, @intCast(u32, 0x0)); var x1198: u32 = undefined; var x1199: u1 = undefined; fiatP384AddcarryxU32(&x1198, &x1199, x1197, x1135, x1171); var x1200: u32 = undefined; var x1201: u1 = undefined; fiatP384AddcarryxU32(&x1200, &x1201, x1199, x1137, x1175); var x1202: u32 = undefined; var x1203: u1 = undefined; fiatP384AddcarryxU32(&x1202, &x1203, x1201, x1139, x1177); var x1204: u32 = undefined; var x1205: u1 = undefined; fiatP384AddcarryxU32(&x1204, &x1205, x1203, x1141, x1179); var x1206: u32 = undefined; var x1207: u1 = undefined; fiatP384AddcarryxU32(&x1206, &x1207, x1205, x1143, x1181); var x1208: u32 = undefined; var x1209: u1 = undefined; fiatP384AddcarryxU32(&x1208, &x1209, x1207, x1145, x1183); var x1210: u32 = undefined; var x1211: u1 = undefined; fiatP384AddcarryxU32(&x1210, &x1211, x1209, x1147, x1185); var x1212: u32 = undefined; var x1213: u1 = undefined; fiatP384AddcarryxU32(&x1212, &x1213, x1211, x1149, x1187); var x1214: u32 = undefined; var x1215: u1 = undefined; fiatP384AddcarryxU32(&x1214, &x1215, x1213, x1151, x1189); var x1216: u32 = undefined; var x1217: u1 = undefined; fiatP384AddcarryxU32(&x1216, &x1217, x1215, x1153, x1191); const x1218: u32 = (@intCast(u32, x1217) + @intCast(u32, x1154)); var x1219: u32 = undefined; var x1220: u32 = undefined; fiatP384MulxU32(&x1219, &x1220, x9, (arg2[11])); var x1221: u32 = undefined; var x1222: u32 = undefined; fiatP384MulxU32(&x1221, &x1222, x9, (arg2[10])); var x1223: u32 = undefined; var x1224: u32 = undefined; fiatP384MulxU32(&x1223, &x1224, x9, (arg2[9])); var x1225: u32 = undefined; var x1226: u32 = undefined; fiatP384MulxU32(&x1225, &x1226, x9, (arg2[8])); var x1227: u32 = undefined; var x1228: u32 = undefined; fiatP384MulxU32(&x1227, &x1228, x9, (arg2[7])); var x1229: u32 = undefined; var x1230: u32 = undefined; fiatP384MulxU32(&x1229, &x1230, x9, (arg2[6])); var x1231: u32 = undefined; var x1232: u32 = undefined; fiatP384MulxU32(&x1231, &x1232, x9, (arg2[5])); var x1233: u32 = undefined; var x1234: u32 = undefined; fiatP384MulxU32(&x1233, &x1234, x9, (arg2[4])); var x1235: u32 = undefined; var x1236: u32 = undefined; fiatP384MulxU32(&x1235, &x1236, x9, (arg2[3])); var x1237: u32 = undefined; var x1238: u32 = undefined; fiatP384MulxU32(&x1237, &x1238, x9, (arg2[2])); var x1239: u32 = undefined; var x1240: u32 = undefined; fiatP384MulxU32(&x1239, &x1240, x9, (arg2[1])); var x1241: u32 = undefined; var x1242: u32 = undefined; fiatP384MulxU32(&x1241, &x1242, x9, (arg2[0])); var x1243: u32 = undefined; var x1244: u1 = undefined; fiatP384AddcarryxU32(&x1243, &x1244, 0x0, x1242, x1239); var x1245: u32 = undefined; var x1246: u1 = undefined; fiatP384AddcarryxU32(&x1245, &x1246, x1244, x1240, x1237); var x1247: u32 = undefined; var x1248: u1 = undefined; fiatP384AddcarryxU32(&x1247, &x1248, x1246, x1238, x1235); var x1249: u32 = undefined; var x1250: u1 = undefined; fiatP384AddcarryxU32(&x1249, &x1250, x1248, x1236, x1233); var x1251: u32 = undefined; var x1252: u1 = undefined; fiatP384AddcarryxU32(&x1251, &x1252, x1250, x1234, x1231); var x1253: u32 = undefined; var x1254: u1 = undefined; fiatP384AddcarryxU32(&x1253, &x1254, x1252, x1232, x1229); var x1255: u32 = undefined; var x1256: u1 = undefined; fiatP384AddcarryxU32(&x1255, &x1256, x1254, x1230, x1227); var x1257: u32 = undefined; var x1258: u1 = undefined; fiatP384AddcarryxU32(&x1257, &x1258, x1256, x1228, x1225); var x1259: u32 = undefined; var x1260: u1 = undefined; fiatP384AddcarryxU32(&x1259, &x1260, x1258, x1226, x1223); var x1261: u32 = undefined; var x1262: u1 = undefined; fiatP384AddcarryxU32(&x1261, &x1262, x1260, x1224, x1221); var x1263: u32 = undefined; var x1264: u1 = undefined; fiatP384AddcarryxU32(&x1263, &x1264, x1262, x1222, x1219); const x1265: u32 = (@intCast(u32, x1264) + x1220); var x1266: u32 = undefined; var x1267: u1 = undefined; fiatP384AddcarryxU32(&x1266, &x1267, 0x0, x1194, x1241); var x1268: u32 = undefined; var x1269: u1 = undefined; fiatP384AddcarryxU32(&x1268, &x1269, x1267, x1196, x1243); var x1270: u32 = undefined; var x1271: u1 = undefined; fiatP384AddcarryxU32(&x1270, &x1271, x1269, x1198, x1245); var x1272: u32 = undefined; var x1273: u1 = undefined; fiatP384AddcarryxU32(&x1272, &x1273, x1271, x1200, x1247); var x1274: u32 = undefined; var x1275: u1 = undefined; fiatP384AddcarryxU32(&x1274, &x1275, x1273, x1202, x1249); var x1276: u32 = undefined; var x1277: u1 = undefined; fiatP384AddcarryxU32(&x1276, &x1277, x1275, x1204, x1251); var x1278: u32 = undefined; var x1279: u1 = undefined; fiatP384AddcarryxU32(&x1278, &x1279, x1277, x1206, x1253); var x1280: u32 = undefined; var x1281: u1 = undefined; fiatP384AddcarryxU32(&x1280, &x1281, x1279, x1208, x1255); var x1282: u32 = undefined; var x1283: u1 = undefined; fiatP384AddcarryxU32(&x1282, &x1283, x1281, x1210, x1257); var x1284: u32 = undefined; var x1285: u1 = undefined; fiatP384AddcarryxU32(&x1284, &x1285, x1283, x1212, x1259); var x1286: u32 = undefined; var x1287: u1 = undefined; fiatP384AddcarryxU32(&x1286, &x1287, x1285, x1214, x1261); var x1288: u32 = undefined; var x1289: u1 = undefined; fiatP384AddcarryxU32(&x1288, &x1289, x1287, x1216, x1263); var x1290: u32 = undefined; var x1291: u1 = undefined; fiatP384AddcarryxU32(&x1290, &x1291, x1289, x1218, x1265); var x1292: u32 = undefined; var x1293: u32 = undefined; fiatP384MulxU32(&x1292, &x1293, x1266, 0xffffffff); var x1294: u32 = undefined; var x1295: u32 = undefined; fiatP384MulxU32(&x1294, &x1295, x1266, 0xffffffff); var x1296: u32 = undefined; var x1297: u32 = undefined; fiatP384MulxU32(&x1296, &x1297, x1266, 0xffffffff); var x1298: u32 = undefined; var x1299: u32 = undefined; fiatP384MulxU32(&x1298, &x1299, x1266, 0xffffffff); var x1300: u32 = undefined; var x1301: u32 = undefined; fiatP384MulxU32(&x1300, &x1301, x1266, 0xffffffff); var x1302: u32 = undefined; var x1303: u32 = undefined; fiatP384MulxU32(&x1302, &x1303, x1266, 0xffffffff); var x1304: u32 = undefined; var x1305: u32 = undefined; fiatP384MulxU32(&x1304, &x1305, x1266, 0xffffffff); var x1306: u32 = undefined; var x1307: u32 = undefined; fiatP384MulxU32(&x1306, &x1307, x1266, 0xfffffffe); var x1308: u32 = undefined; var x1309: u32 = undefined; fiatP384MulxU32(&x1308, &x1309, x1266, 0xffffffff); var x1310: u32 = undefined; var x1311: u32 = undefined; fiatP384MulxU32(&x1310, &x1311, x1266, 0xffffffff); var x1312: u32 = undefined; var x1313: u1 = undefined; fiatP384AddcarryxU32(&x1312, &x1313, 0x0, x1309, x1306); var x1314: u32 = undefined; var x1315: u1 = undefined; fiatP384AddcarryxU32(&x1314, &x1315, x1313, x1307, x1304); var x1316: u32 = undefined; var x1317: u1 = undefined; fiatP384AddcarryxU32(&x1316, &x1317, x1315, x1305, x1302); var x1318: u32 = undefined; var x1319: u1 = undefined; fiatP384AddcarryxU32(&x1318, &x1319, x1317, x1303, x1300); var x1320: u32 = undefined; var x1321: u1 = undefined; fiatP384AddcarryxU32(&x1320, &x1321, x1319, x1301, x1298); var x1322: u32 = undefined; var x1323: u1 = undefined; fiatP384AddcarryxU32(&x1322, &x1323, x1321, x1299, x1296); var x1324: u32 = undefined; var x1325: u1 = undefined; fiatP384AddcarryxU32(&x1324, &x1325, x1323, x1297, x1294); var x1326: u32 = undefined; var x1327: u1 = undefined; fiatP384AddcarryxU32(&x1326, &x1327, x1325, x1295, x1292); const x1328: u32 = (@intCast(u32, x1327) + x1293); var x1329: u32 = undefined; var x1330: u1 = undefined; fiatP384AddcarryxU32(&x1329, &x1330, 0x0, x1266, x1310); var x1331: u32 = undefined; var x1332: u1 = undefined; fiatP384AddcarryxU32(&x1331, &x1332, x1330, x1268, x1311); var x1333: u32 = undefined; var x1334: u1 = undefined; fiatP384AddcarryxU32(&x1333, &x1334, x1332, x1270, @intCast(u32, 0x0)); var x1335: u32 = undefined; var x1336: u1 = undefined; fiatP384AddcarryxU32(&x1335, &x1336, x1334, x1272, x1308); var x1337: u32 = undefined; var x1338: u1 = undefined; fiatP384AddcarryxU32(&x1337, &x1338, x1336, x1274, x1312); var x1339: u32 = undefined; var x1340: u1 = undefined; fiatP384AddcarryxU32(&x1339, &x1340, x1338, x1276, x1314); var x1341: u32 = undefined; var x1342: u1 = undefined; fiatP384AddcarryxU32(&x1341, &x1342, x1340, x1278, x1316); var x1343: u32 = undefined; var x1344: u1 = undefined; fiatP384AddcarryxU32(&x1343, &x1344, x1342, x1280, x1318); var x1345: u32 = undefined; var x1346: u1 = undefined; fiatP384AddcarryxU32(&x1345, &x1346, x1344, x1282, x1320); var x1347: u32 = undefined; var x1348: u1 = undefined; fiatP384AddcarryxU32(&x1347, &x1348, x1346, x1284, x1322); var x1349: u32 = undefined; var x1350: u1 = undefined; fiatP384AddcarryxU32(&x1349, &x1350, x1348, x1286, x1324); var x1351: u32 = undefined; var x1352: u1 = undefined; fiatP384AddcarryxU32(&x1351, &x1352, x1350, x1288, x1326); var x1353: u32 = undefined; var x1354: u1 = undefined; fiatP384AddcarryxU32(&x1353, &x1354, x1352, x1290, x1328); const x1355: u32 = (@intCast(u32, x1354) + @intCast(u32, x1291)); var x1356: u32 = undefined; var x1357: u32 = undefined; fiatP384MulxU32(&x1356, &x1357, x10, (arg2[11])); var x1358: u32 = undefined; var x1359: u32 = undefined; fiatP384MulxU32(&x1358, &x1359, x10, (arg2[10])); var x1360: u32 = undefined; var x1361: u32 = undefined; fiatP384MulxU32(&x1360, &x1361, x10, (arg2[9])); var x1362: u32 = undefined; var x1363: u32 = undefined; fiatP384MulxU32(&x1362, &x1363, x10, (arg2[8])); var x1364: u32 = undefined; var x1365: u32 = undefined; fiatP384MulxU32(&x1364, &x1365, x10, (arg2[7])); var x1366: u32 = undefined; var x1367: u32 = undefined; fiatP384MulxU32(&x1366, &x1367, x10, (arg2[6])); var x1368: u32 = undefined; var x1369: u32 = undefined; fiatP384MulxU32(&x1368, &x1369, x10, (arg2[5])); var x1370: u32 = undefined; var x1371: u32 = undefined; fiatP384MulxU32(&x1370, &x1371, x10, (arg2[4])); var x1372: u32 = undefined; var x1373: u32 = undefined; fiatP384MulxU32(&x1372, &x1373, x10, (arg2[3])); var x1374: u32 = undefined; var x1375: u32 = undefined; fiatP384MulxU32(&x1374, &x1375, x10, (arg2[2])); var x1376: u32 = undefined; var x1377: u32 = undefined; fiatP384MulxU32(&x1376, &x1377, x10, (arg2[1])); var x1378: u32 = undefined; var x1379: u32 = undefined; fiatP384MulxU32(&x1378, &x1379, x10, (arg2[0])); var x1380: u32 = undefined; var x1381: u1 = undefined; fiatP384AddcarryxU32(&x1380, &x1381, 0x0, x1379, x1376); var x1382: u32 = undefined; var x1383: u1 = undefined; fiatP384AddcarryxU32(&x1382, &x1383, x1381, x1377, x1374); var x1384: u32 = undefined; var x1385: u1 = undefined; fiatP384AddcarryxU32(&x1384, &x1385, x1383, x1375, x1372); var x1386: u32 = undefined; var x1387: u1 = undefined; fiatP384AddcarryxU32(&x1386, &x1387, x1385, x1373, x1370); var x1388: u32 = undefined; var x1389: u1 = undefined; fiatP384AddcarryxU32(&x1388, &x1389, x1387, x1371, x1368); var x1390: u32 = undefined; var x1391: u1 = undefined; fiatP384AddcarryxU32(&x1390, &x1391, x1389, x1369, x1366); var x1392: u32 = undefined; var x1393: u1 = undefined; fiatP384AddcarryxU32(&x1392, &x1393, x1391, x1367, x1364); var x1394: u32 = undefined; var x1395: u1 = undefined; fiatP384AddcarryxU32(&x1394, &x1395, x1393, x1365, x1362); var x1396: u32 = undefined; var x1397: u1 = undefined; fiatP384AddcarryxU32(&x1396, &x1397, x1395, x1363, x1360); var x1398: u32 = undefined; var x1399: u1 = undefined; fiatP384AddcarryxU32(&x1398, &x1399, x1397, x1361, x1358); var x1400: u32 = undefined; var x1401: u1 = undefined; fiatP384AddcarryxU32(&x1400, &x1401, x1399, x1359, x1356); const x1402: u32 = (@intCast(u32, x1401) + x1357); var x1403: u32 = undefined; var x1404: u1 = undefined; fiatP384AddcarryxU32(&x1403, &x1404, 0x0, x1331, x1378); var x1405: u32 = undefined; var x1406: u1 = undefined; fiatP384AddcarryxU32(&x1405, &x1406, x1404, x1333, x1380); var x1407: u32 = undefined; var x1408: u1 = undefined; fiatP384AddcarryxU32(&x1407, &x1408, x1406, x1335, x1382); var x1409: u32 = undefined; var x1410: u1 = undefined; fiatP384AddcarryxU32(&x1409, &x1410, x1408, x1337, x1384); var x1411: u32 = undefined; var x1412: u1 = undefined; fiatP384AddcarryxU32(&x1411, &x1412, x1410, x1339, x1386); var x1413: u32 = undefined; var x1414: u1 = undefined; fiatP384AddcarryxU32(&x1413, &x1414, x1412, x1341, x1388); var x1415: u32 = undefined; var x1416: u1 = undefined; fiatP384AddcarryxU32(&x1415, &x1416, x1414, x1343, x1390); var x1417: u32 = undefined; var x1418: u1 = undefined; fiatP384AddcarryxU32(&x1417, &x1418, x1416, x1345, x1392); var x1419: u32 = undefined; var x1420: u1 = undefined; fiatP384AddcarryxU32(&x1419, &x1420, x1418, x1347, x1394); var x1421: u32 = undefined; var x1422: u1 = undefined; fiatP384AddcarryxU32(&x1421, &x1422, x1420, x1349, x1396); var x1423: u32 = undefined; var x1424: u1 = undefined; fiatP384AddcarryxU32(&x1423, &x1424, x1422, x1351, x1398); var x1425: u32 = undefined; var x1426: u1 = undefined; fiatP384AddcarryxU32(&x1425, &x1426, x1424, x1353, x1400); var x1427: u32 = undefined; var x1428: u1 = undefined; fiatP384AddcarryxU32(&x1427, &x1428, x1426, x1355, x1402); var x1429: u32 = undefined; var x1430: u32 = undefined; fiatP384MulxU32(&x1429, &x1430, x1403, 0xffffffff); var x1431: u32 = undefined; var x1432: u32 = undefined; fiatP384MulxU32(&x1431, &x1432, x1403, 0xffffffff); var x1433: u32 = undefined; var x1434: u32 = undefined; fiatP384MulxU32(&x1433, &x1434, x1403, 0xffffffff); var x1435: u32 = undefined; var x1436: u32 = undefined; fiatP384MulxU32(&x1435, &x1436, x1403, 0xffffffff); var x1437: u32 = undefined; var x1438: u32 = undefined; fiatP384MulxU32(&x1437, &x1438, x1403, 0xffffffff); var x1439: u32 = undefined; var x1440: u32 = undefined; fiatP384MulxU32(&x1439, &x1440, x1403, 0xffffffff); var x1441: u32 = undefined; var x1442: u32 = undefined; fiatP384MulxU32(&x1441, &x1442, x1403, 0xffffffff); var x1443: u32 = undefined; var x1444: u32 = undefined; fiatP384MulxU32(&x1443, &x1444, x1403, 0xfffffffe); var x1445: u32 = undefined; var x1446: u32 = undefined; fiatP384MulxU32(&x1445, &x1446, x1403, 0xffffffff); var x1447: u32 = undefined; var x1448: u32 = undefined; fiatP384MulxU32(&x1447, &x1448, x1403, 0xffffffff); var x1449: u32 = undefined; var x1450: u1 = undefined; fiatP384AddcarryxU32(&x1449, &x1450, 0x0, x1446, x1443); var x1451: u32 = undefined; var x1452: u1 = undefined; fiatP384AddcarryxU32(&x1451, &x1452, x1450, x1444, x1441); var x1453: u32 = undefined; var x1454: u1 = undefined; fiatP384AddcarryxU32(&x1453, &x1454, x1452, x1442, x1439); var x1455: u32 = undefined; var x1456: u1 = undefined; fiatP384AddcarryxU32(&x1455, &x1456, x1454, x1440, x1437); var x1457: u32 = undefined; var x1458: u1 = undefined; fiatP384AddcarryxU32(&x1457, &x1458, x1456, x1438, x1435); var x1459: u32 = undefined; var x1460: u1 = undefined; fiatP384AddcarryxU32(&x1459, &x1460, x1458, x1436, x1433); var x1461: u32 = undefined; var x1462: u1 = undefined; fiatP384AddcarryxU32(&x1461, &x1462, x1460, x1434, x1431); var x1463: u32 = undefined; var x1464: u1 = undefined; fiatP384AddcarryxU32(&x1463, &x1464, x1462, x1432, x1429); const x1465: u32 = (@intCast(u32, x1464) + x1430); var x1466: u32 = undefined; var x1467: u1 = undefined; fiatP384AddcarryxU32(&x1466, &x1467, 0x0, x1403, x1447); var x1468: u32 = undefined; var x1469: u1 = undefined; fiatP384AddcarryxU32(&x1468, &x1469, x1467, x1405, x1448); var x1470: u32 = undefined; var x1471: u1 = undefined; fiatP384AddcarryxU32(&x1470, &x1471, x1469, x1407, @intCast(u32, 0x0)); var x1472: u32 = undefined; var x1473: u1 = undefined; fiatP384AddcarryxU32(&x1472, &x1473, x1471, x1409, x1445); var x1474: u32 = undefined; var x1475: u1 = undefined; fiatP384AddcarryxU32(&x1474, &x1475, x1473, x1411, x1449); var x1476: u32 = undefined; var x1477: u1 = undefined; fiatP384AddcarryxU32(&x1476, &x1477, x1475, x1413, x1451); var x1478: u32 = undefined; var x1479: u1 = undefined; fiatP384AddcarryxU32(&x1478, &x1479, x1477, x1415, x1453); var x1480: u32 = undefined; var x1481: u1 = undefined; fiatP384AddcarryxU32(&x1480, &x1481, x1479, x1417, x1455); var x1482: u32 = undefined; var x1483: u1 = undefined; fiatP384AddcarryxU32(&x1482, &x1483, x1481, x1419, x1457); var x1484: u32 = undefined; var x1485: u1 = undefined; fiatP384AddcarryxU32(&x1484, &x1485, x1483, x1421, x1459); var x1486: u32 = undefined; var x1487: u1 = undefined; fiatP384AddcarryxU32(&x1486, &x1487, x1485, x1423, x1461); var x1488: u32 = undefined; var x1489: u1 = undefined; fiatP384AddcarryxU32(&x1488, &x1489, x1487, x1425, x1463); var x1490: u32 = undefined; var x1491: u1 = undefined; fiatP384AddcarryxU32(&x1490, &x1491, x1489, x1427, x1465); const x1492: u32 = (@intCast(u32, x1491) + @intCast(u32, x1428)); var x1493: u32 = undefined; var x1494: u32 = undefined; fiatP384MulxU32(&x1493, &x1494, x11, (arg2[11])); var x1495: u32 = undefined; var x1496: u32 = undefined; fiatP384MulxU32(&x1495, &x1496, x11, (arg2[10])); var x1497: u32 = undefined; var x1498: u32 = undefined; fiatP384MulxU32(&x1497, &x1498, x11, (arg2[9])); var x1499: u32 = undefined; var x1500: u32 = undefined; fiatP384MulxU32(&x1499, &x1500, x11, (arg2[8])); var x1501: u32 = undefined; var x1502: u32 = undefined; fiatP384MulxU32(&x1501, &x1502, x11, (arg2[7])); var x1503: u32 = undefined; var x1504: u32 = undefined; fiatP384MulxU32(&x1503, &x1504, x11, (arg2[6])); var x1505: u32 = undefined; var x1506: u32 = undefined; fiatP384MulxU32(&x1505, &x1506, x11, (arg2[5])); var x1507: u32 = undefined; var x1508: u32 = undefined; fiatP384MulxU32(&x1507, &x1508, x11, (arg2[4])); var x1509: u32 = undefined; var x1510: u32 = undefined; fiatP384MulxU32(&x1509, &x1510, x11, (arg2[3])); var x1511: u32 = undefined; var x1512: u32 = undefined; fiatP384MulxU32(&x1511, &x1512, x11, (arg2[2])); var x1513: u32 = undefined; var x1514: u32 = undefined; fiatP384MulxU32(&x1513, &x1514, x11, (arg2[1])); var x1515: u32 = undefined; var x1516: u32 = undefined; fiatP384MulxU32(&x1515, &x1516, x11, (arg2[0])); var x1517: u32 = undefined; var x1518: u1 = undefined; fiatP384AddcarryxU32(&x1517, &x1518, 0x0, x1516, x1513); var x1519: u32 = undefined; var x1520: u1 = undefined; fiatP384AddcarryxU32(&x1519, &x1520, x1518, x1514, x1511); var x1521: u32 = undefined; var x1522: u1 = undefined; fiatP384AddcarryxU32(&x1521, &x1522, x1520, x1512, x1509); var x1523: u32 = undefined; var x1524: u1 = undefined; fiatP384AddcarryxU32(&x1523, &x1524, x1522, x1510, x1507); var x1525: u32 = undefined; var x1526: u1 = undefined; fiatP384AddcarryxU32(&x1525, &x1526, x1524, x1508, x1505); var x1527: u32 = undefined; var x1528: u1 = undefined; fiatP384AddcarryxU32(&x1527, &x1528, x1526, x1506, x1503); var x1529: u32 = undefined; var x1530: u1 = undefined; fiatP384AddcarryxU32(&x1529, &x1530, x1528, x1504, x1501); var x1531: u32 = undefined; var x1532: u1 = undefined; fiatP384AddcarryxU32(&x1531, &x1532, x1530, x1502, x1499); var x1533: u32 = undefined; var x1534: u1 = undefined; fiatP384AddcarryxU32(&x1533, &x1534, x1532, x1500, x1497); var x1535: u32 = undefined; var x1536: u1 = undefined; fiatP384AddcarryxU32(&x1535, &x1536, x1534, x1498, x1495); var x1537: u32 = undefined; var x1538: u1 = undefined; fiatP384AddcarryxU32(&x1537, &x1538, x1536, x1496, x1493); const x1539: u32 = (@intCast(u32, x1538) + x1494); var x1540: u32 = undefined; var x1541: u1 = undefined; fiatP384AddcarryxU32(&x1540, &x1541, 0x0, x1468, x1515); var x1542: u32 = undefined; var x1543: u1 = undefined; fiatP384AddcarryxU32(&x1542, &x1543, x1541, x1470, x1517); var x1544: u32 = undefined; var x1545: u1 = undefined; fiatP384AddcarryxU32(&x1544, &x1545, x1543, x1472, x1519); var x1546: u32 = undefined; var x1547: u1 = undefined; fiatP384AddcarryxU32(&x1546, &x1547, x1545, x1474, x1521); var x1548: u32 = undefined; var x1549: u1 = undefined; fiatP384AddcarryxU32(&x1548, &x1549, x1547, x1476, x1523); var x1550: u32 = undefined; var x1551: u1 = undefined; fiatP384AddcarryxU32(&x1550, &x1551, x1549, x1478, x1525); var x1552: u32 = undefined; var x1553: u1 = undefined; fiatP384AddcarryxU32(&x1552, &x1553, x1551, x1480, x1527); var x1554: u32 = undefined; var x1555: u1 = undefined; fiatP384AddcarryxU32(&x1554, &x1555, x1553, x1482, x1529); var x1556: u32 = undefined; var x1557: u1 = undefined; fiatP384AddcarryxU32(&x1556, &x1557, x1555, x1484, x1531); var x1558: u32 = undefined; var x1559: u1 = undefined; fiatP384AddcarryxU32(&x1558, &x1559, x1557, x1486, x1533); var x1560: u32 = undefined; var x1561: u1 = undefined; fiatP384AddcarryxU32(&x1560, &x1561, x1559, x1488, x1535); var x1562: u32 = undefined; var x1563: u1 = undefined; fiatP384AddcarryxU32(&x1562, &x1563, x1561, x1490, x1537); var x1564: u32 = undefined; var x1565: u1 = undefined; fiatP384AddcarryxU32(&x1564, &x1565, x1563, x1492, x1539); var x1566: u32 = undefined; var x1567: u32 = undefined; fiatP384MulxU32(&x1566, &x1567, x1540, 0xffffffff); var x1568: u32 = undefined; var x1569: u32 = undefined; fiatP384MulxU32(&x1568, &x1569, x1540, 0xffffffff); var x1570: u32 = undefined; var x1571: u32 = undefined; fiatP384MulxU32(&x1570, &x1571, x1540, 0xffffffff); var x1572: u32 = undefined; var x1573: u32 = undefined; fiatP384MulxU32(&x1572, &x1573, x1540, 0xffffffff); var x1574: u32 = undefined; var x1575: u32 = undefined; fiatP384MulxU32(&x1574, &x1575, x1540, 0xffffffff); var x1576: u32 = undefined; var x1577: u32 = undefined; fiatP384MulxU32(&x1576, &x1577, x1540, 0xffffffff); var x1578: u32 = undefined; var x1579: u32 = undefined; fiatP384MulxU32(&x1578, &x1579, x1540, 0xffffffff); var x1580: u32 = undefined; var x1581: u32 = undefined; fiatP384MulxU32(&x1580, &x1581, x1540, 0xfffffffe); var x1582: u32 = undefined; var x1583: u32 = undefined; fiatP384MulxU32(&x1582, &x1583, x1540, 0xffffffff); var x1584: u32 = undefined; var x1585: u32 = undefined; fiatP384MulxU32(&x1584, &x1585, x1540, 0xffffffff); var x1586: u32 = undefined; var x1587: u1 = undefined; fiatP384AddcarryxU32(&x1586, &x1587, 0x0, x1583, x1580); var x1588: u32 = undefined; var x1589: u1 = undefined; fiatP384AddcarryxU32(&x1588, &x1589, x1587, x1581, x1578); var x1590: u32 = undefined; var x1591: u1 = undefined; fiatP384AddcarryxU32(&x1590, &x1591, x1589, x1579, x1576); var x1592: u32 = undefined; var x1593: u1 = undefined; fiatP384AddcarryxU32(&x1592, &x1593, x1591, x1577, x1574); var x1594: u32 = undefined; var x1595: u1 = undefined; fiatP384AddcarryxU32(&x1594, &x1595, x1593, x1575, x1572); var x1596: u32 = undefined; var x1597: u1 = undefined; fiatP384AddcarryxU32(&x1596, &x1597, x1595, x1573, x1570); var x1598: u32 = undefined; var x1599: u1 = undefined; fiatP384AddcarryxU32(&x1598, &x1599, x1597, x1571, x1568); var x1600: u32 = undefined; var x1601: u1 = undefined; fiatP384AddcarryxU32(&x1600, &x1601, x1599, x1569, x1566); const x1602: u32 = (@intCast(u32, x1601) + x1567); var x1603: u32 = undefined; var x1604: u1 = undefined; fiatP384AddcarryxU32(&x1603, &x1604, 0x0, x1540, x1584); var x1605: u32 = undefined; var x1606: u1 = undefined; fiatP384AddcarryxU32(&x1605, &x1606, x1604, x1542, x1585); var x1607: u32 = undefined; var x1608: u1 = undefined; fiatP384AddcarryxU32(&x1607, &x1608, x1606, x1544, @intCast(u32, 0x0)); var x1609: u32 = undefined; var x1610: u1 = undefined; fiatP384AddcarryxU32(&x1609, &x1610, x1608, x1546, x1582); var x1611: u32 = undefined; var x1612: u1 = undefined; fiatP384AddcarryxU32(&x1611, &x1612, x1610, x1548, x1586); var x1613: u32 = undefined; var x1614: u1 = undefined; fiatP384AddcarryxU32(&x1613, &x1614, x1612, x1550, x1588); var x1615: u32 = undefined; var x1616: u1 = undefined; fiatP384AddcarryxU32(&x1615, &x1616, x1614, x1552, x1590); var x1617: u32 = undefined; var x1618: u1 = undefined; fiatP384AddcarryxU32(&x1617, &x1618, x1616, x1554, x1592); var x1619: u32 = undefined; var x1620: u1 = undefined; fiatP384AddcarryxU32(&x1619, &x1620, x1618, x1556, x1594); var x1621: u32 = undefined; var x1622: u1 = undefined; fiatP384AddcarryxU32(&x1621, &x1622, x1620, x1558, x1596); var x1623: u32 = undefined; var x1624: u1 = undefined; fiatP384AddcarryxU32(&x1623, &x1624, x1622, x1560, x1598); var x1625: u32 = undefined; var x1626: u1 = undefined; fiatP384AddcarryxU32(&x1625, &x1626, x1624, x1562, x1600); var x1627: u32 = undefined; var x1628: u1 = undefined; fiatP384AddcarryxU32(&x1627, &x1628, x1626, x1564, x1602); const x1629: u32 = (@intCast(u32, x1628) + @intCast(u32, x1565)); var x1630: u32 = undefined; var x1631: u1 = undefined; fiatP384SubborrowxU32(&x1630, &x1631, 0x0, x1605, 0xffffffff); var x1632: u32 = undefined; var x1633: u1 = undefined; fiatP384SubborrowxU32(&x1632, &x1633, x1631, x1607, @intCast(u32, 0x0)); var x1634: u32 = undefined; var x1635: u1 = undefined; fiatP384SubborrowxU32(&x1634, &x1635, x1633, x1609, @intCast(u32, 0x0)); var x1636: u32 = undefined; var x1637: u1 = undefined; fiatP384SubborrowxU32(&x1636, &x1637, x1635, x1611, 0xffffffff); var x1638: u32 = undefined; var x1639: u1 = undefined; fiatP384SubborrowxU32(&x1638, &x1639, x1637, x1613, 0xfffffffe); var x1640: u32 = undefined; var x1641: u1 = undefined; fiatP384SubborrowxU32(&x1640, &x1641, x1639, x1615, 0xffffffff); var x1642: u32 = undefined; var x1643: u1 = undefined; fiatP384SubborrowxU32(&x1642, &x1643, x1641, x1617, 0xffffffff); var x1644: u32 = undefined; var x1645: u1 = undefined; fiatP384SubborrowxU32(&x1644, &x1645, x1643, x1619, 0xffffffff); var x1646: u32 = undefined; var x1647: u1 = undefined; fiatP384SubborrowxU32(&x1646, &x1647, x1645, x1621, 0xffffffff); var x1648: u32 = undefined; var x1649: u1 = undefined; fiatP384SubborrowxU32(&x1648, &x1649, x1647, x1623, 0xffffffff); var x1650: u32 = undefined; var x1651: u1 = undefined; fiatP384SubborrowxU32(&x1650, &x1651, x1649, x1625, 0xffffffff); var x1652: u32 = undefined; var x1653: u1 = undefined; fiatP384SubborrowxU32(&x1652, &x1653, x1651, x1627, 0xffffffff); var x1654: u32 = undefined; var x1655: u1 = undefined; fiatP384SubborrowxU32(&x1654, &x1655, x1653, x1629, @intCast(u32, 0x0)); var x1656: u32 = undefined; fiatP384CmovznzU32(&x1656, x1655, x1630, x1605); var x1657: u32 = undefined; fiatP384CmovznzU32(&x1657, x1655, x1632, x1607); var x1658: u32 = undefined; fiatP384CmovznzU32(&x1658, x1655, x1634, x1609); var x1659: u32 = undefined; fiatP384CmovznzU32(&x1659, x1655, x1636, x1611); var x1660: u32 = undefined; fiatP384CmovznzU32(&x1660, x1655, x1638, x1613); var x1661: u32 = undefined; fiatP384CmovznzU32(&x1661, x1655, x1640, x1615); var x1662: u32 = undefined; fiatP384CmovznzU32(&x1662, x1655, x1642, x1617); var x1663: u32 = undefined; fiatP384CmovznzU32(&x1663, x1655, x1644, x1619); var x1664: u32 = undefined; fiatP384CmovznzU32(&x1664, x1655, x1646, x1621); var x1665: u32 = undefined; fiatP384CmovznzU32(&x1665, x1655, x1648, x1623); var x1666: u32 = undefined; fiatP384CmovznzU32(&x1666, x1655, x1650, x1625); var x1667: u32 = undefined; fiatP384CmovznzU32(&x1667, x1655, x1652, x1627); out1[0] = x1656; out1[1] = x1657; out1[2] = x1658; out1[3] = x1659; out1[4] = x1660; out1[5] = x1661; out1[6] = x1662; out1[7] = x1663; out1[8] = x1664; out1[9] = x1665; out1[10] = x1666; out1[11] = x1667; } /// The function fiatP384Square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Square(out1: *[12]u32, arg1: [12]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[8]); const x9: u32 = (arg1[9]); const x10: u32 = (arg1[10]); const x11: u32 = (arg1[11]); const x12: u32 = (arg1[0]); var x13: u32 = undefined; var x14: u32 = undefined; fiatP384MulxU32(&x13, &x14, x12, (arg1[11])); var x15: u32 = undefined; var x16: u32 = undefined; fiatP384MulxU32(&x15, &x16, x12, (arg1[10])); var x17: u32 = undefined; var x18: u32 = undefined; fiatP384MulxU32(&x17, &x18, x12, (arg1[9])); var x19: u32 = undefined; var x20: u32 = undefined; fiatP384MulxU32(&x19, &x20, x12, (arg1[8])); var x21: u32 = undefined; var x22: u32 = undefined; fiatP384MulxU32(&x21, &x22, x12, (arg1[7])); var x23: u32 = undefined; var x24: u32 = undefined; fiatP384MulxU32(&x23, &x24, x12, (arg1[6])); var x25: u32 = undefined; var x26: u32 = undefined; fiatP384MulxU32(&x25, &x26, x12, (arg1[5])); var x27: u32 = undefined; var x28: u32 = undefined; fiatP384MulxU32(&x27, &x28, x12, (arg1[4])); var x29: u32 = undefined; var x30: u32 = undefined; fiatP384MulxU32(&x29, &x30, x12, (arg1[3])); var x31: u32 = undefined; var x32: u32 = undefined; fiatP384MulxU32(&x31, &x32, x12, (arg1[2])); var x33: u32 = undefined; var x34: u32 = undefined; fiatP384MulxU32(&x33, &x34, x12, (arg1[1])); var x35: u32 = undefined; var x36: u32 = undefined; fiatP384MulxU32(&x35, &x36, x12, (arg1[0])); var x37: u32 = undefined; var x38: u1 = undefined; fiatP384AddcarryxU32(&x37, &x38, 0x0, x36, x33); var x39: u32 = undefined; var x40: u1 = undefined; fiatP384AddcarryxU32(&x39, &x40, x38, x34, x31); var x41: u32 = undefined; var x42: u1 = undefined; fiatP384AddcarryxU32(&x41, &x42, x40, x32, x29); var x43: u32 = undefined; var x44: u1 = undefined; fiatP384AddcarryxU32(&x43, &x44, x42, x30, x27); var x45: u32 = undefined; var x46: u1 = undefined; fiatP384AddcarryxU32(&x45, &x46, x44, x28, x25); var x47: u32 = undefined; var x48: u1 = undefined; fiatP384AddcarryxU32(&x47, &x48, x46, x26, x23); var x49: u32 = undefined; var x50: u1 = undefined; fiatP384AddcarryxU32(&x49, &x50, x48, x24, x21); var x51: u32 = undefined; var x52: u1 = undefined; fiatP384AddcarryxU32(&x51, &x52, x50, x22, x19); var x53: u32 = undefined; var x54: u1 = undefined; fiatP384AddcarryxU32(&x53, &x54, x52, x20, x17); var x55: u32 = undefined; var x56: u1 = undefined; fiatP384AddcarryxU32(&x55, &x56, x54, x18, x15); var x57: u32 = undefined; var x58: u1 = undefined; fiatP384AddcarryxU32(&x57, &x58, x56, x16, x13); const x59: u32 = (@intCast(u32, x58) + x14); var x60: u32 = undefined; var x61: u32 = undefined; fiatP384MulxU32(&x60, &x61, x35, 0xffffffff); var x62: u32 = undefined; var x63: u32 = undefined; fiatP384MulxU32(&x62, &x63, x35, 0xffffffff); var x64: u32 = undefined; var x65: u32 = undefined; fiatP384MulxU32(&x64, &x65, x35, 0xffffffff); var x66: u32 = undefined; var x67: u32 = undefined; fiatP384MulxU32(&x66, &x67, x35, 0xffffffff); var x68: u32 = undefined; var x69: u32 = undefined; fiatP384MulxU32(&x68, &x69, x35, 0xffffffff); var x70: u32 = undefined; var x71: u32 = undefined; fiatP384MulxU32(&x70, &x71, x35, 0xffffffff); var x72: u32 = undefined; var x73: u32 = undefined; fiatP384MulxU32(&x72, &x73, x35, 0xffffffff); var x74: u32 = undefined; var x75: u32 = undefined; fiatP384MulxU32(&x74, &x75, x35, 0xfffffffe); var x76: u32 = undefined; var x77: u32 = undefined; fiatP384MulxU32(&x76, &x77, x35, 0xffffffff); var x78: u32 = undefined; var x79: u32 = undefined; fiatP384MulxU32(&x78, &x79, x35, 0xffffffff); var x80: u32 = undefined; var x81: u1 = undefined; fiatP384AddcarryxU32(&x80, &x81, 0x0, x77, x74); var x82: u32 = undefined; var x83: u1 = undefined; fiatP384AddcarryxU32(&x82, &x83, x81, x75, x72); var x84: u32 = undefined; var x85: u1 = undefined; fiatP384AddcarryxU32(&x84, &x85, x83, x73, x70); var x86: u32 = undefined; var x87: u1 = undefined; fiatP384AddcarryxU32(&x86, &x87, x85, x71, x68); var x88: u32 = undefined; var x89: u1 = undefined; fiatP384AddcarryxU32(&x88, &x89, x87, x69, x66); var x90: u32 = undefined; var x91: u1 = undefined; fiatP384AddcarryxU32(&x90, &x91, x89, x67, x64); var x92: u32 = undefined; var x93: u1 = undefined; fiatP384AddcarryxU32(&x92, &x93, x91, x65, x62); var x94: u32 = undefined; var x95: u1 = undefined; fiatP384AddcarryxU32(&x94, &x95, x93, x63, x60); const x96: u32 = (@intCast(u32, x95) + x61); var x97: u32 = undefined; var x98: u1 = undefined; fiatP384AddcarryxU32(&x97, &x98, 0x0, x35, x78); var x99: u32 = undefined; var x100: u1 = undefined; fiatP384AddcarryxU32(&x99, &x100, x98, x37, x79); var x101: u32 = undefined; var x102: u1 = undefined; fiatP384AddcarryxU32(&x101, &x102, x100, x39, @intCast(u32, 0x0)); var x103: u32 = undefined; var x104: u1 = undefined; fiatP384AddcarryxU32(&x103, &x104, x102, x41, x76); var x105: u32 = undefined; var x106: u1 = undefined; fiatP384AddcarryxU32(&x105, &x106, x104, x43, x80); var x107: u32 = undefined; var x108: u1 = undefined; fiatP384AddcarryxU32(&x107, &x108, x106, x45, x82); var x109: u32 = undefined; var x110: u1 = undefined; fiatP384AddcarryxU32(&x109, &x110, x108, x47, x84); var x111: u32 = undefined; var x112: u1 = undefined; fiatP384AddcarryxU32(&x111, &x112, x110, x49, x86); var x113: u32 = undefined; var x114: u1 = undefined; fiatP384AddcarryxU32(&x113, &x114, x112, x51, x88); var x115: u32 = undefined; var x116: u1 = undefined; fiatP384AddcarryxU32(&x115, &x116, x114, x53, x90); var x117: u32 = undefined; var x118: u1 = undefined; fiatP384AddcarryxU32(&x117, &x118, x116, x55, x92); var x119: u32 = undefined; var x120: u1 = undefined; fiatP384AddcarryxU32(&x119, &x120, x118, x57, x94); var x121: u32 = undefined; var x122: u1 = undefined; fiatP384AddcarryxU32(&x121, &x122, x120, x59, x96); var x123: u32 = undefined; var x124: u32 = undefined; fiatP384MulxU32(&x123, &x124, x1, (arg1[11])); var x125: u32 = undefined; var x126: u32 = undefined; fiatP384MulxU32(&x125, &x126, x1, (arg1[10])); var x127: u32 = undefined; var x128: u32 = undefined; fiatP384MulxU32(&x127, &x128, x1, (arg1[9])); var x129: u32 = undefined; var x130: u32 = undefined; fiatP384MulxU32(&x129, &x130, x1, (arg1[8])); var x131: u32 = undefined; var x132: u32 = undefined; fiatP384MulxU32(&x131, &x132, x1, (arg1[7])); var x133: u32 = undefined; var x134: u32 = undefined; fiatP384MulxU32(&x133, &x134, x1, (arg1[6])); var x135: u32 = undefined; var x136: u32 = undefined; fiatP384MulxU32(&x135, &x136, x1, (arg1[5])); var x137: u32 = undefined; var x138: u32 = undefined; fiatP384MulxU32(&x137, &x138, x1, (arg1[4])); var x139: u32 = undefined; var x140: u32 = undefined; fiatP384MulxU32(&x139, &x140, x1, (arg1[3])); var x141: u32 = undefined; var x142: u32 = undefined; fiatP384MulxU32(&x141, &x142, x1, (arg1[2])); var x143: u32 = undefined; var x144: u32 = undefined; fiatP384MulxU32(&x143, &x144, x1, (arg1[1])); var x145: u32 = undefined; var x146: u32 = undefined; fiatP384MulxU32(&x145, &x146, x1, (arg1[0])); var x147: u32 = undefined; var x148: u1 = undefined; fiatP384AddcarryxU32(&x147, &x148, 0x0, x146, x143); var x149: u32 = undefined; var x150: u1 = undefined; fiatP384AddcarryxU32(&x149, &x150, x148, x144, x141); var x151: u32 = undefined; var x152: u1 = undefined; fiatP384AddcarryxU32(&x151, &x152, x150, x142, x139); var x153: u32 = undefined; var x154: u1 = undefined; fiatP384AddcarryxU32(&x153, &x154, x152, x140, x137); var x155: u32 = undefined; var x156: u1 = undefined; fiatP384AddcarryxU32(&x155, &x156, x154, x138, x135); var x157: u32 = undefined; var x158: u1 = undefined; fiatP384AddcarryxU32(&x157, &x158, x156, x136, x133); var x159: u32 = undefined; var x160: u1 = undefined; fiatP384AddcarryxU32(&x159, &x160, x158, x134, x131); var x161: u32 = undefined; var x162: u1 = undefined; fiatP384AddcarryxU32(&x161, &x162, x160, x132, x129); var x163: u32 = undefined; var x164: u1 = undefined; fiatP384AddcarryxU32(&x163, &x164, x162, x130, x127); var x165: u32 = undefined; var x166: u1 = undefined; fiatP384AddcarryxU32(&x165, &x166, x164, x128, x125); var x167: u32 = undefined; var x168: u1 = undefined; fiatP384AddcarryxU32(&x167, &x168, x166, x126, x123); const x169: u32 = (@intCast(u32, x168) + x124); var x170: u32 = undefined; var x171: u1 = undefined; fiatP384AddcarryxU32(&x170, &x171, 0x0, x99, x145); var x172: u32 = undefined; var x173: u1 = undefined; fiatP384AddcarryxU32(&x172, &x173, x171, x101, x147); var x174: u32 = undefined; var x175: u1 = undefined; fiatP384AddcarryxU32(&x174, &x175, x173, x103, x149); var x176: u32 = undefined; var x177: u1 = undefined; fiatP384AddcarryxU32(&x176, &x177, x175, x105, x151); var x178: u32 = undefined; var x179: u1 = undefined; fiatP384AddcarryxU32(&x178, &x179, x177, x107, x153); var x180: u32 = undefined; var x181: u1 = undefined; fiatP384AddcarryxU32(&x180, &x181, x179, x109, x155); var x182: u32 = undefined; var x183: u1 = undefined; fiatP384AddcarryxU32(&x182, &x183, x181, x111, x157); var x184: u32 = undefined; var x185: u1 = undefined; fiatP384AddcarryxU32(&x184, &x185, x183, x113, x159); var x186: u32 = undefined; var x187: u1 = undefined; fiatP384AddcarryxU32(&x186, &x187, x185, x115, x161); var x188: u32 = undefined; var x189: u1 = undefined; fiatP384AddcarryxU32(&x188, &x189, x187, x117, x163); var x190: u32 = undefined; var x191: u1 = undefined; fiatP384AddcarryxU32(&x190, &x191, x189, x119, x165); var x192: u32 = undefined; var x193: u1 = undefined; fiatP384AddcarryxU32(&x192, &x193, x191, x121, x167); var x194: u32 = undefined; var x195: u1 = undefined; fiatP384AddcarryxU32(&x194, &x195, x193, @intCast(u32, x122), x169); var x196: u32 = undefined; var x197: u32 = undefined; fiatP384MulxU32(&x196, &x197, x170, 0xffffffff); var x198: u32 = undefined; var x199: u32 = undefined; fiatP384MulxU32(&x198, &x199, x170, 0xffffffff); var x200: u32 = undefined; var x201: u32 = undefined; fiatP384MulxU32(&x200, &x201, x170, 0xffffffff); var x202: u32 = undefined; var x203: u32 = undefined; fiatP384MulxU32(&x202, &x203, x170, 0xffffffff); var x204: u32 = undefined; var x205: u32 = undefined; fiatP384MulxU32(&x204, &x205, x170, 0xffffffff); var x206: u32 = undefined; var x207: u32 = undefined; fiatP384MulxU32(&x206, &x207, x170, 0xffffffff); var x208: u32 = undefined; var x209: u32 = undefined; fiatP384MulxU32(&x208, &x209, x170, 0xffffffff); var x210: u32 = undefined; var x211: u32 = undefined; fiatP384MulxU32(&x210, &x211, x170, 0xfffffffe); var x212: u32 = undefined; var x213: u32 = undefined; fiatP384MulxU32(&x212, &x213, x170, 0xffffffff); var x214: u32 = undefined; var x215: u32 = undefined; fiatP384MulxU32(&x214, &x215, x170, 0xffffffff); var x216: u32 = undefined; var x217: u1 = undefined; fiatP384AddcarryxU32(&x216, &x217, 0x0, x213, x210); var x218: u32 = undefined; var x219: u1 = undefined; fiatP384AddcarryxU32(&x218, &x219, x217, x211, x208); var x220: u32 = undefined; var x221: u1 = undefined; fiatP384AddcarryxU32(&x220, &x221, x219, x209, x206); var x222: u32 = undefined; var x223: u1 = undefined; fiatP384AddcarryxU32(&x222, &x223, x221, x207, x204); var x224: u32 = undefined; var x225: u1 = undefined; fiatP384AddcarryxU32(&x224, &x225, x223, x205, x202); var x226: u32 = undefined; var x227: u1 = undefined; fiatP384AddcarryxU32(&x226, &x227, x225, x203, x200); var x228: u32 = undefined; var x229: u1 = undefined; fiatP384AddcarryxU32(&x228, &x229, x227, x201, x198); var x230: u32 = undefined; var x231: u1 = undefined; fiatP384AddcarryxU32(&x230, &x231, x229, x199, x196); const x232: u32 = (@intCast(u32, x231) + x197); var x233: u32 = undefined; var x234: u1 = undefined; fiatP384AddcarryxU32(&x233, &x234, 0x0, x170, x214); var x235: u32 = undefined; var x236: u1 = undefined; fiatP384AddcarryxU32(&x235, &x236, x234, x172, x215); var x237: u32 = undefined; var x238: u1 = undefined; fiatP384AddcarryxU32(&x237, &x238, x236, x174, @intCast(u32, 0x0)); var x239: u32 = undefined; var x240: u1 = undefined; fiatP384AddcarryxU32(&x239, &x240, x238, x176, x212); var x241: u32 = undefined; var x242: u1 = undefined; fiatP384AddcarryxU32(&x241, &x242, x240, x178, x216); var x243: u32 = undefined; var x244: u1 = undefined; fiatP384AddcarryxU32(&x243, &x244, x242, x180, x218); var x245: u32 = undefined; var x246: u1 = undefined; fiatP384AddcarryxU32(&x245, &x246, x244, x182, x220); var x247: u32 = undefined; var x248: u1 = undefined; fiatP384AddcarryxU32(&x247, &x248, x246, x184, x222); var x249: u32 = undefined; var x250: u1 = undefined; fiatP384AddcarryxU32(&x249, &x250, x248, x186, x224); var x251: u32 = undefined; var x252: u1 = undefined; fiatP384AddcarryxU32(&x251, &x252, x250, x188, x226); var x253: u32 = undefined; var x254: u1 = undefined; fiatP384AddcarryxU32(&x253, &x254, x252, x190, x228); var x255: u32 = undefined; var x256: u1 = undefined; fiatP384AddcarryxU32(&x255, &x256, x254, x192, x230); var x257: u32 = undefined; var x258: u1 = undefined; fiatP384AddcarryxU32(&x257, &x258, x256, x194, x232); const x259: u32 = (@intCast(u32, x258) + @intCast(u32, x195)); var x260: u32 = undefined; var x261: u32 = undefined; fiatP384MulxU32(&x260, &x261, x2, (arg1[11])); var x262: u32 = undefined; var x263: u32 = undefined; fiatP384MulxU32(&x262, &x263, x2, (arg1[10])); var x264: u32 = undefined; var x265: u32 = undefined; fiatP384MulxU32(&x264, &x265, x2, (arg1[9])); var x266: u32 = undefined; var x267: u32 = undefined; fiatP384MulxU32(&x266, &x267, x2, (arg1[8])); var x268: u32 = undefined; var x269: u32 = undefined; fiatP384MulxU32(&x268, &x269, x2, (arg1[7])); var x270: u32 = undefined; var x271: u32 = undefined; fiatP384MulxU32(&x270, &x271, x2, (arg1[6])); var x272: u32 = undefined; var x273: u32 = undefined; fiatP384MulxU32(&x272, &x273, x2, (arg1[5])); var x274: u32 = undefined; var x275: u32 = undefined; fiatP384MulxU32(&x274, &x275, x2, (arg1[4])); var x276: u32 = undefined; var x277: u32 = undefined; fiatP384MulxU32(&x276, &x277, x2, (arg1[3])); var x278: u32 = undefined; var x279: u32 = undefined; fiatP384MulxU32(&x278, &x279, x2, (arg1[2])); var x280: u32 = undefined; var x281: u32 = undefined; fiatP384MulxU32(&x280, &x281, x2, (arg1[1])); var x282: u32 = undefined; var x283: u32 = undefined; fiatP384MulxU32(&x282, &x283, x2, (arg1[0])); var x284: u32 = undefined; var x285: u1 = undefined; fiatP384AddcarryxU32(&x284, &x285, 0x0, x283, x280); var x286: u32 = undefined; var x287: u1 = undefined; fiatP384AddcarryxU32(&x286, &x287, x285, x281, x278); var x288: u32 = undefined; var x289: u1 = undefined; fiatP384AddcarryxU32(&x288, &x289, x287, x279, x276); var x290: u32 = undefined; var x291: u1 = undefined; fiatP384AddcarryxU32(&x290, &x291, x289, x277, x274); var x292: u32 = undefined; var x293: u1 = undefined; fiatP384AddcarryxU32(&x292, &x293, x291, x275, x272); var x294: u32 = undefined; var x295: u1 = undefined; fiatP384AddcarryxU32(&x294, &x295, x293, x273, x270); var x296: u32 = undefined; var x297: u1 = undefined; fiatP384AddcarryxU32(&x296, &x297, x295, x271, x268); var x298: u32 = undefined; var x299: u1 = undefined; fiatP384AddcarryxU32(&x298, &x299, x297, x269, x266); var x300: u32 = undefined; var x301: u1 = undefined; fiatP384AddcarryxU32(&x300, &x301, x299, x267, x264); var x302: u32 = undefined; var x303: u1 = undefined; fiatP384AddcarryxU32(&x302, &x303, x301, x265, x262); var x304: u32 = undefined; var x305: u1 = undefined; fiatP384AddcarryxU32(&x304, &x305, x303, x263, x260); const x306: u32 = (@intCast(u32, x305) + x261); var x307: u32 = undefined; var x308: u1 = undefined; fiatP384AddcarryxU32(&x307, &x308, 0x0, x235, x282); var x309: u32 = undefined; var x310: u1 = undefined; fiatP384AddcarryxU32(&x309, &x310, x308, x237, x284); var x311: u32 = undefined; var x312: u1 = undefined; fiatP384AddcarryxU32(&x311, &x312, x310, x239, x286); var x313: u32 = undefined; var x314: u1 = undefined; fiatP384AddcarryxU32(&x313, &x314, x312, x241, x288); var x315: u32 = undefined; var x316: u1 = undefined; fiatP384AddcarryxU32(&x315, &x316, x314, x243, x290); var x317: u32 = undefined; var x318: u1 = undefined; fiatP384AddcarryxU32(&x317, &x318, x316, x245, x292); var x319: u32 = undefined; var x320: u1 = undefined; fiatP384AddcarryxU32(&x319, &x320, x318, x247, x294); var x321: u32 = undefined; var x322: u1 = undefined; fiatP384AddcarryxU32(&x321, &x322, x320, x249, x296); var x323: u32 = undefined; var x324: u1 = undefined; fiatP384AddcarryxU32(&x323, &x324, x322, x251, x298); var x325: u32 = undefined; var x326: u1 = undefined; fiatP384AddcarryxU32(&x325, &x326, x324, x253, x300); var x327: u32 = undefined; var x328: u1 = undefined; fiatP384AddcarryxU32(&x327, &x328, x326, x255, x302); var x329: u32 = undefined; var x330: u1 = undefined; fiatP384AddcarryxU32(&x329, &x330, x328, x257, x304); var x331: u32 = undefined; var x332: u1 = undefined; fiatP384AddcarryxU32(&x331, &x332, x330, x259, x306); var x333: u32 = undefined; var x334: u32 = undefined; fiatP384MulxU32(&x333, &x334, x307, 0xffffffff); var x335: u32 = undefined; var x336: u32 = undefined; fiatP384MulxU32(&x335, &x336, x307, 0xffffffff); var x337: u32 = undefined; var x338: u32 = undefined; fiatP384MulxU32(&x337, &x338, x307, 0xffffffff); var x339: u32 = undefined; var x340: u32 = undefined; fiatP384MulxU32(&x339, &x340, x307, 0xffffffff); var x341: u32 = undefined; var x342: u32 = undefined; fiatP384MulxU32(&x341, &x342, x307, 0xffffffff); var x343: u32 = undefined; var x344: u32 = undefined; fiatP384MulxU32(&x343, &x344, x307, 0xffffffff); var x345: u32 = undefined; var x346: u32 = undefined; fiatP384MulxU32(&x345, &x346, x307, 0xffffffff); var x347: u32 = undefined; var x348: u32 = undefined; fiatP384MulxU32(&x347, &x348, x307, 0xfffffffe); var x349: u32 = undefined; var x350: u32 = undefined; fiatP384MulxU32(&x349, &x350, x307, 0xffffffff); var x351: u32 = undefined; var x352: u32 = undefined; fiatP384MulxU32(&x351, &x352, x307, 0xffffffff); var x353: u32 = undefined; var x354: u1 = undefined; fiatP384AddcarryxU32(&x353, &x354, 0x0, x350, x347); var x355: u32 = undefined; var x356: u1 = undefined; fiatP384AddcarryxU32(&x355, &x356, x354, x348, x345); var x357: u32 = undefined; var x358: u1 = undefined; fiatP384AddcarryxU32(&x357, &x358, x356, x346, x343); var x359: u32 = undefined; var x360: u1 = undefined; fiatP384AddcarryxU32(&x359, &x360, x358, x344, x341); var x361: u32 = undefined; var x362: u1 = undefined; fiatP384AddcarryxU32(&x361, &x362, x360, x342, x339); var x363: u32 = undefined; var x364: u1 = undefined; fiatP384AddcarryxU32(&x363, &x364, x362, x340, x337); var x365: u32 = undefined; var x366: u1 = undefined; fiatP384AddcarryxU32(&x365, &x366, x364, x338, x335); var x367: u32 = undefined; var x368: u1 = undefined; fiatP384AddcarryxU32(&x367, &x368, x366, x336, x333); const x369: u32 = (@intCast(u32, x368) + x334); var x370: u32 = undefined; var x371: u1 = undefined; fiatP384AddcarryxU32(&x370, &x371, 0x0, x307, x351); var x372: u32 = undefined; var x373: u1 = undefined; fiatP384AddcarryxU32(&x372, &x373, x371, x309, x352); var x374: u32 = undefined; var x375: u1 = undefined; fiatP384AddcarryxU32(&x374, &x375, x373, x311, @intCast(u32, 0x0)); var x376: u32 = undefined; var x377: u1 = undefined; fiatP384AddcarryxU32(&x376, &x377, x375, x313, x349); var x378: u32 = undefined; var x379: u1 = undefined; fiatP384AddcarryxU32(&x378, &x379, x377, x315, x353); var x380: u32 = undefined; var x381: u1 = undefined; fiatP384AddcarryxU32(&x380, &x381, x379, x317, x355); var x382: u32 = undefined; var x383: u1 = undefined; fiatP384AddcarryxU32(&x382, &x383, x381, x319, x357); var x384: u32 = undefined; var x385: u1 = undefined; fiatP384AddcarryxU32(&x384, &x385, x383, x321, x359); var x386: u32 = undefined; var x387: u1 = undefined; fiatP384AddcarryxU32(&x386, &x387, x385, x323, x361); var x388: u32 = undefined; var x389: u1 = undefined; fiatP384AddcarryxU32(&x388, &x389, x387, x325, x363); var x390: u32 = undefined; var x391: u1 = undefined; fiatP384AddcarryxU32(&x390, &x391, x389, x327, x365); var x392: u32 = undefined; var x393: u1 = undefined; fiatP384AddcarryxU32(&x392, &x393, x391, x329, x367); var x394: u32 = undefined; var x395: u1 = undefined; fiatP384AddcarryxU32(&x394, &x395, x393, x331, x369); const x396: u32 = (@intCast(u32, x395) + @intCast(u32, x332)); var x397: u32 = undefined; var x398: u32 = undefined; fiatP384MulxU32(&x397, &x398, x3, (arg1[11])); var x399: u32 = undefined; var x400: u32 = undefined; fiatP384MulxU32(&x399, &x400, x3, (arg1[10])); var x401: u32 = undefined; var x402: u32 = undefined; fiatP384MulxU32(&x401, &x402, x3, (arg1[9])); var x403: u32 = undefined; var x404: u32 = undefined; fiatP384MulxU32(&x403, &x404, x3, (arg1[8])); var x405: u32 = undefined; var x406: u32 = undefined; fiatP384MulxU32(&x405, &x406, x3, (arg1[7])); var x407: u32 = undefined; var x408: u32 = undefined; fiatP384MulxU32(&x407, &x408, x3, (arg1[6])); var x409: u32 = undefined; var x410: u32 = undefined; fiatP384MulxU32(&x409, &x410, x3, (arg1[5])); var x411: u32 = undefined; var x412: u32 = undefined; fiatP384MulxU32(&x411, &x412, x3, (arg1[4])); var x413: u32 = undefined; var x414: u32 = undefined; fiatP384MulxU32(&x413, &x414, x3, (arg1[3])); var x415: u32 = undefined; var x416: u32 = undefined; fiatP384MulxU32(&x415, &x416, x3, (arg1[2])); var x417: u32 = undefined; var x418: u32 = undefined; fiatP384MulxU32(&x417, &x418, x3, (arg1[1])); var x419: u32 = undefined; var x420: u32 = undefined; fiatP384MulxU32(&x419, &x420, x3, (arg1[0])); var x421: u32 = undefined; var x422: u1 = undefined; fiatP384AddcarryxU32(&x421, &x422, 0x0, x420, x417); var x423: u32 = undefined; var x424: u1 = undefined; fiatP384AddcarryxU32(&x423, &x424, x422, x418, x415); var x425: u32 = undefined; var x426: u1 = undefined; fiatP384AddcarryxU32(&x425, &x426, x424, x416, x413); var x427: u32 = undefined; var x428: u1 = undefined; fiatP384AddcarryxU32(&x427, &x428, x426, x414, x411); var x429: u32 = undefined; var x430: u1 = undefined; fiatP384AddcarryxU32(&x429, &x430, x428, x412, x409); var x431: u32 = undefined; var x432: u1 = undefined; fiatP384AddcarryxU32(&x431, &x432, x430, x410, x407); var x433: u32 = undefined; var x434: u1 = undefined; fiatP384AddcarryxU32(&x433, &x434, x432, x408, x405); var x435: u32 = undefined; var x436: u1 = undefined; fiatP384AddcarryxU32(&x435, &x436, x434, x406, x403); var x437: u32 = undefined; var x438: u1 = undefined; fiatP384AddcarryxU32(&x437, &x438, x436, x404, x401); var x439: u32 = undefined; var x440: u1 = undefined; fiatP384AddcarryxU32(&x439, &x440, x438, x402, x399); var x441: u32 = undefined; var x442: u1 = undefined; fiatP384AddcarryxU32(&x441, &x442, x440, x400, x397); const x443: u32 = (@intCast(u32, x442) + x398); var x444: u32 = undefined; var x445: u1 = undefined; fiatP384AddcarryxU32(&x444, &x445, 0x0, x372, x419); var x446: u32 = undefined; var x447: u1 = undefined; fiatP384AddcarryxU32(&x446, &x447, x445, x374, x421); var x448: u32 = undefined; var x449: u1 = undefined; fiatP384AddcarryxU32(&x448, &x449, x447, x376, x423); var x450: u32 = undefined; var x451: u1 = undefined; fiatP384AddcarryxU32(&x450, &x451, x449, x378, x425); var x452: u32 = undefined; var x453: u1 = undefined; fiatP384AddcarryxU32(&x452, &x453, x451, x380, x427); var x454: u32 = undefined; var x455: u1 = undefined; fiatP384AddcarryxU32(&x454, &x455, x453, x382, x429); var x456: u32 = undefined; var x457: u1 = undefined; fiatP384AddcarryxU32(&x456, &x457, x455, x384, x431); var x458: u32 = undefined; var x459: u1 = undefined; fiatP384AddcarryxU32(&x458, &x459, x457, x386, x433); var x460: u32 = undefined; var x461: u1 = undefined; fiatP384AddcarryxU32(&x460, &x461, x459, x388, x435); var x462: u32 = undefined; var x463: u1 = undefined; fiatP384AddcarryxU32(&x462, &x463, x461, x390, x437); var x464: u32 = undefined; var x465: u1 = undefined; fiatP384AddcarryxU32(&x464, &x465, x463, x392, x439); var x466: u32 = undefined; var x467: u1 = undefined; fiatP384AddcarryxU32(&x466, &x467, x465, x394, x441); var x468: u32 = undefined; var x469: u1 = undefined; fiatP384AddcarryxU32(&x468, &x469, x467, x396, x443); var x470: u32 = undefined; var x471: u32 = undefined; fiatP384MulxU32(&x470, &x471, x444, 0xffffffff); var x472: u32 = undefined; var x473: u32 = undefined; fiatP384MulxU32(&x472, &x473, x444, 0xffffffff); var x474: u32 = undefined; var x475: u32 = undefined; fiatP384MulxU32(&x474, &x475, x444, 0xffffffff); var x476: u32 = undefined; var x477: u32 = undefined; fiatP384MulxU32(&x476, &x477, x444, 0xffffffff); var x478: u32 = undefined; var x479: u32 = undefined; fiatP384MulxU32(&x478, &x479, x444, 0xffffffff); var x480: u32 = undefined; var x481: u32 = undefined; fiatP384MulxU32(&x480, &x481, x444, 0xffffffff); var x482: u32 = undefined; var x483: u32 = undefined; fiatP384MulxU32(&x482, &x483, x444, 0xffffffff); var x484: u32 = undefined; var x485: u32 = undefined; fiatP384MulxU32(&x484, &x485, x444, 0xfffffffe); var x486: u32 = undefined; var x487: u32 = undefined; fiatP384MulxU32(&x486, &x487, x444, 0xffffffff); var x488: u32 = undefined; var x489: u32 = undefined; fiatP384MulxU32(&x488, &x489, x444, 0xffffffff); var x490: u32 = undefined; var x491: u1 = undefined; fiatP384AddcarryxU32(&x490, &x491, 0x0, x487, x484); var x492: u32 = undefined; var x493: u1 = undefined; fiatP384AddcarryxU32(&x492, &x493, x491, x485, x482); var x494: u32 = undefined; var x495: u1 = undefined; fiatP384AddcarryxU32(&x494, &x495, x493, x483, x480); var x496: u32 = undefined; var x497: u1 = undefined; fiatP384AddcarryxU32(&x496, &x497, x495, x481, x478); var x498: u32 = undefined; var x499: u1 = undefined; fiatP384AddcarryxU32(&x498, &x499, x497, x479, x476); var x500: u32 = undefined; var x501: u1 = undefined; fiatP384AddcarryxU32(&x500, &x501, x499, x477, x474); var x502: u32 = undefined; var x503: u1 = undefined; fiatP384AddcarryxU32(&x502, &x503, x501, x475, x472); var x504: u32 = undefined; var x505: u1 = undefined; fiatP384AddcarryxU32(&x504, &x505, x503, x473, x470); const x506: u32 = (@intCast(u32, x505) + x471); var x507: u32 = undefined; var x508: u1 = undefined; fiatP384AddcarryxU32(&x507, &x508, 0x0, x444, x488); var x509: u32 = undefined; var x510: u1 = undefined; fiatP384AddcarryxU32(&x509, &x510, x508, x446, x489); var x511: u32 = undefined; var x512: u1 = undefined; fiatP384AddcarryxU32(&x511, &x512, x510, x448, @intCast(u32, 0x0)); var x513: u32 = undefined; var x514: u1 = undefined; fiatP384AddcarryxU32(&x513, &x514, x512, x450, x486); var x515: u32 = undefined; var x516: u1 = undefined; fiatP384AddcarryxU32(&x515, &x516, x514, x452, x490); var x517: u32 = undefined; var x518: u1 = undefined; fiatP384AddcarryxU32(&x517, &x518, x516, x454, x492); var x519: u32 = undefined; var x520: u1 = undefined; fiatP384AddcarryxU32(&x519, &x520, x518, x456, x494); var x521: u32 = undefined; var x522: u1 = undefined; fiatP384AddcarryxU32(&x521, &x522, x520, x458, x496); var x523: u32 = undefined; var x524: u1 = undefined; fiatP384AddcarryxU32(&x523, &x524, x522, x460, x498); var x525: u32 = undefined; var x526: u1 = undefined; fiatP384AddcarryxU32(&x525, &x526, x524, x462, x500); var x527: u32 = undefined; var x528: u1 = undefined; fiatP384AddcarryxU32(&x527, &x528, x526, x464, x502); var x529: u32 = undefined; var x530: u1 = undefined; fiatP384AddcarryxU32(&x529, &x530, x528, x466, x504); var x531: u32 = undefined; var x532: u1 = undefined; fiatP384AddcarryxU32(&x531, &x532, x530, x468, x506); const x533: u32 = (@intCast(u32, x532) + @intCast(u32, x469)); var x534: u32 = undefined; var x535: u32 = undefined; fiatP384MulxU32(&x534, &x535, x4, (arg1[11])); var x536: u32 = undefined; var x537: u32 = undefined; fiatP384MulxU32(&x536, &x537, x4, (arg1[10])); var x538: u32 = undefined; var x539: u32 = undefined; fiatP384MulxU32(&x538, &x539, x4, (arg1[9])); var x540: u32 = undefined; var x541: u32 = undefined; fiatP384MulxU32(&x540, &x541, x4, (arg1[8])); var x542: u32 = undefined; var x543: u32 = undefined; fiatP384MulxU32(&x542, &x543, x4, (arg1[7])); var x544: u32 = undefined; var x545: u32 = undefined; fiatP384MulxU32(&x544, &x545, x4, (arg1[6])); var x546: u32 = undefined; var x547: u32 = undefined; fiatP384MulxU32(&x546, &x547, x4, (arg1[5])); var x548: u32 = undefined; var x549: u32 = undefined; fiatP384MulxU32(&x548, &x549, x4, (arg1[4])); var x550: u32 = undefined; var x551: u32 = undefined; fiatP384MulxU32(&x550, &x551, x4, (arg1[3])); var x552: u32 = undefined; var x553: u32 = undefined; fiatP384MulxU32(&x552, &x553, x4, (arg1[2])); var x554: u32 = undefined; var x555: u32 = undefined; fiatP384MulxU32(&x554, &x555, x4, (arg1[1])); var x556: u32 = undefined; var x557: u32 = undefined; fiatP384MulxU32(&x556, &x557, x4, (arg1[0])); var x558: u32 = undefined; var x559: u1 = undefined; fiatP384AddcarryxU32(&x558, &x559, 0x0, x557, x554); var x560: u32 = undefined; var x561: u1 = undefined; fiatP384AddcarryxU32(&x560, &x561, x559, x555, x552); var x562: u32 = undefined; var x563: u1 = undefined; fiatP384AddcarryxU32(&x562, &x563, x561, x553, x550); var x564: u32 = undefined; var x565: u1 = undefined; fiatP384AddcarryxU32(&x564, &x565, x563, x551, x548); var x566: u32 = undefined; var x567: u1 = undefined; fiatP384AddcarryxU32(&x566, &x567, x565, x549, x546); var x568: u32 = undefined; var x569: u1 = undefined; fiatP384AddcarryxU32(&x568, &x569, x567, x547, x544); var x570: u32 = undefined; var x571: u1 = undefined; fiatP384AddcarryxU32(&x570, &x571, x569, x545, x542); var x572: u32 = undefined; var x573: u1 = undefined; fiatP384AddcarryxU32(&x572, &x573, x571, x543, x540); var x574: u32 = undefined; var x575: u1 = undefined; fiatP384AddcarryxU32(&x574, &x575, x573, x541, x538); var x576: u32 = undefined; var x577: u1 = undefined; fiatP384AddcarryxU32(&x576, &x577, x575, x539, x536); var x578: u32 = undefined; var x579: u1 = undefined; fiatP384AddcarryxU32(&x578, &x579, x577, x537, x534); const x580: u32 = (@intCast(u32, x579) + x535); var x581: u32 = undefined; var x582: u1 = undefined; fiatP384AddcarryxU32(&x581, &x582, 0x0, x509, x556); var x583: u32 = undefined; var x584: u1 = undefined; fiatP384AddcarryxU32(&x583, &x584, x582, x511, x558); var x585: u32 = undefined; var x586: u1 = undefined; fiatP384AddcarryxU32(&x585, &x586, x584, x513, x560); var x587: u32 = undefined; var x588: u1 = undefined; fiatP384AddcarryxU32(&x587, &x588, x586, x515, x562); var x589: u32 = undefined; var x590: u1 = undefined; fiatP384AddcarryxU32(&x589, &x590, x588, x517, x564); var x591: u32 = undefined; var x592: u1 = undefined; fiatP384AddcarryxU32(&x591, &x592, x590, x519, x566); var x593: u32 = undefined; var x594: u1 = undefined; fiatP384AddcarryxU32(&x593, &x594, x592, x521, x568); var x595: u32 = undefined; var x596: u1 = undefined; fiatP384AddcarryxU32(&x595, &x596, x594, x523, x570); var x597: u32 = undefined; var x598: u1 = undefined; fiatP384AddcarryxU32(&x597, &x598, x596, x525, x572); var x599: u32 = undefined; var x600: u1 = undefined; fiatP384AddcarryxU32(&x599, &x600, x598, x527, x574); var x601: u32 = undefined; var x602: u1 = undefined; fiatP384AddcarryxU32(&x601, &x602, x600, x529, x576); var x603: u32 = undefined; var x604: u1 = undefined; fiatP384AddcarryxU32(&x603, &x604, x602, x531, x578); var x605: u32 = undefined; var x606: u1 = undefined; fiatP384AddcarryxU32(&x605, &x606, x604, x533, x580); var x607: u32 = undefined; var x608: u32 = undefined; fiatP384MulxU32(&x607, &x608, x581, 0xffffffff); var x609: u32 = undefined; var x610: u32 = undefined; fiatP384MulxU32(&x609, &x610, x581, 0xffffffff); var x611: u32 = undefined; var x612: u32 = undefined; fiatP384MulxU32(&x611, &x612, x581, 0xffffffff); var x613: u32 = undefined; var x614: u32 = undefined; fiatP384MulxU32(&x613, &x614, x581, 0xffffffff); var x615: u32 = undefined; var x616: u32 = undefined; fiatP384MulxU32(&x615, &x616, x581, 0xffffffff); var x617: u32 = undefined; var x618: u32 = undefined; fiatP384MulxU32(&x617, &x618, x581, 0xffffffff); var x619: u32 = undefined; var x620: u32 = undefined; fiatP384MulxU32(&x619, &x620, x581, 0xffffffff); var x621: u32 = undefined; var x622: u32 = undefined; fiatP384MulxU32(&x621, &x622, x581, 0xfffffffe); var x623: u32 = undefined; var x624: u32 = undefined; fiatP384MulxU32(&x623, &x624, x581, 0xffffffff); var x625: u32 = undefined; var x626: u32 = undefined; fiatP384MulxU32(&x625, &x626, x581, 0xffffffff); var x627: u32 = undefined; var x628: u1 = undefined; fiatP384AddcarryxU32(&x627, &x628, 0x0, x624, x621); var x629: u32 = undefined; var x630: u1 = undefined; fiatP384AddcarryxU32(&x629, &x630, x628, x622, x619); var x631: u32 = undefined; var x632: u1 = undefined; fiatP384AddcarryxU32(&x631, &x632, x630, x620, x617); var x633: u32 = undefined; var x634: u1 = undefined; fiatP384AddcarryxU32(&x633, &x634, x632, x618, x615); var x635: u32 = undefined; var x636: u1 = undefined; fiatP384AddcarryxU32(&x635, &x636, x634, x616, x613); var x637: u32 = undefined; var x638: u1 = undefined; fiatP384AddcarryxU32(&x637, &x638, x636, x614, x611); var x639: u32 = undefined; var x640: u1 = undefined; fiatP384AddcarryxU32(&x639, &x640, x638, x612, x609); var x641: u32 = undefined; var x642: u1 = undefined; fiatP384AddcarryxU32(&x641, &x642, x640, x610, x607); const x643: u32 = (@intCast(u32, x642) + x608); var x644: u32 = undefined; var x645: u1 = undefined; fiatP384AddcarryxU32(&x644, &x645, 0x0, x581, x625); var x646: u32 = undefined; var x647: u1 = undefined; fiatP384AddcarryxU32(&x646, &x647, x645, x583, x626); var x648: u32 = undefined; var x649: u1 = undefined; fiatP384AddcarryxU32(&x648, &x649, x647, x585, @intCast(u32, 0x0)); var x650: u32 = undefined; var x651: u1 = undefined; fiatP384AddcarryxU32(&x650, &x651, x649, x587, x623); var x652: u32 = undefined; var x653: u1 = undefined; fiatP384AddcarryxU32(&x652, &x653, x651, x589, x627); var x654: u32 = undefined; var x655: u1 = undefined; fiatP384AddcarryxU32(&x654, &x655, x653, x591, x629); var x656: u32 = undefined; var x657: u1 = undefined; fiatP384AddcarryxU32(&x656, &x657, x655, x593, x631); var x658: u32 = undefined; var x659: u1 = undefined; fiatP384AddcarryxU32(&x658, &x659, x657, x595, x633); var x660: u32 = undefined; var x661: u1 = undefined; fiatP384AddcarryxU32(&x660, &x661, x659, x597, x635); var x662: u32 = undefined; var x663: u1 = undefined; fiatP384AddcarryxU32(&x662, &x663, x661, x599, x637); var x664: u32 = undefined; var x665: u1 = undefined; fiatP384AddcarryxU32(&x664, &x665, x663, x601, x639); var x666: u32 = undefined; var x667: u1 = undefined; fiatP384AddcarryxU32(&x666, &x667, x665, x603, x641); var x668: u32 = undefined; var x669: u1 = undefined; fiatP384AddcarryxU32(&x668, &x669, x667, x605, x643); const x670: u32 = (@intCast(u32, x669) + @intCast(u32, x606)); var x671: u32 = undefined; var x672: u32 = undefined; fiatP384MulxU32(&x671, &x672, x5, (arg1[11])); var x673: u32 = undefined; var x674: u32 = undefined; fiatP384MulxU32(&x673, &x674, x5, (arg1[10])); var x675: u32 = undefined; var x676: u32 = undefined; fiatP384MulxU32(&x675, &x676, x5, (arg1[9])); var x677: u32 = undefined; var x678: u32 = undefined; fiatP384MulxU32(&x677, &x678, x5, (arg1[8])); var x679: u32 = undefined; var x680: u32 = undefined; fiatP384MulxU32(&x679, &x680, x5, (arg1[7])); var x681: u32 = undefined; var x682: u32 = undefined; fiatP384MulxU32(&x681, &x682, x5, (arg1[6])); var x683: u32 = undefined; var x684: u32 = undefined; fiatP384MulxU32(&x683, &x684, x5, (arg1[5])); var x685: u32 = undefined; var x686: u32 = undefined; fiatP384MulxU32(&x685, &x686, x5, (arg1[4])); var x687: u32 = undefined; var x688: u32 = undefined; fiatP384MulxU32(&x687, &x688, x5, (arg1[3])); var x689: u32 = undefined; var x690: u32 = undefined; fiatP384MulxU32(&x689, &x690, x5, (arg1[2])); var x691: u32 = undefined; var x692: u32 = undefined; fiatP384MulxU32(&x691, &x692, x5, (arg1[1])); var x693: u32 = undefined; var x694: u32 = undefined; fiatP384MulxU32(&x693, &x694, x5, (arg1[0])); var x695: u32 = undefined; var x696: u1 = undefined; fiatP384AddcarryxU32(&x695, &x696, 0x0, x694, x691); var x697: u32 = undefined; var x698: u1 = undefined; fiatP384AddcarryxU32(&x697, &x698, x696, x692, x689); var x699: u32 = undefined; var x700: u1 = undefined; fiatP384AddcarryxU32(&x699, &x700, x698, x690, x687); var x701: u32 = undefined; var x702: u1 = undefined; fiatP384AddcarryxU32(&x701, &x702, x700, x688, x685); var x703: u32 = undefined; var x704: u1 = undefined; fiatP384AddcarryxU32(&x703, &x704, x702, x686, x683); var x705: u32 = undefined; var x706: u1 = undefined; fiatP384AddcarryxU32(&x705, &x706, x704, x684, x681); var x707: u32 = undefined; var x708: u1 = undefined; fiatP384AddcarryxU32(&x707, &x708, x706, x682, x679); var x709: u32 = undefined; var x710: u1 = undefined; fiatP384AddcarryxU32(&x709, &x710, x708, x680, x677); var x711: u32 = undefined; var x712: u1 = undefined; fiatP384AddcarryxU32(&x711, &x712, x710, x678, x675); var x713: u32 = undefined; var x714: u1 = undefined; fiatP384AddcarryxU32(&x713, &x714, x712, x676, x673); var x715: u32 = undefined; var x716: u1 = undefined; fiatP384AddcarryxU32(&x715, &x716, x714, x674, x671); const x717: u32 = (@intCast(u32, x716) + x672); var x718: u32 = undefined; var x719: u1 = undefined; fiatP384AddcarryxU32(&x718, &x719, 0x0, x646, x693); var x720: u32 = undefined; var x721: u1 = undefined; fiatP384AddcarryxU32(&x720, &x721, x719, x648, x695); var x722: u32 = undefined; var x723: u1 = undefined; fiatP384AddcarryxU32(&x722, &x723, x721, x650, x697); var x724: u32 = undefined; var x725: u1 = undefined; fiatP384AddcarryxU32(&x724, &x725, x723, x652, x699); var x726: u32 = undefined; var x727: u1 = undefined; fiatP384AddcarryxU32(&x726, &x727, x725, x654, x701); var x728: u32 = undefined; var x729: u1 = undefined; fiatP384AddcarryxU32(&x728, &x729, x727, x656, x703); var x730: u32 = undefined; var x731: u1 = undefined; fiatP384AddcarryxU32(&x730, &x731, x729, x658, x705); var x732: u32 = undefined; var x733: u1 = undefined; fiatP384AddcarryxU32(&x732, &x733, x731, x660, x707); var x734: u32 = undefined; var x735: u1 = undefined; fiatP384AddcarryxU32(&x734, &x735, x733, x662, x709); var x736: u32 = undefined; var x737: u1 = undefined; fiatP384AddcarryxU32(&x736, &x737, x735, x664, x711); var x738: u32 = undefined; var x739: u1 = undefined; fiatP384AddcarryxU32(&x738, &x739, x737, x666, x713); var x740: u32 = undefined; var x741: u1 = undefined; fiatP384AddcarryxU32(&x740, &x741, x739, x668, x715); var x742: u32 = undefined; var x743: u1 = undefined; fiatP384AddcarryxU32(&x742, &x743, x741, x670, x717); var x744: u32 = undefined; var x745: u32 = undefined; fiatP384MulxU32(&x744, &x745, x718, 0xffffffff); var x746: u32 = undefined; var x747: u32 = undefined; fiatP384MulxU32(&x746, &x747, x718, 0xffffffff); var x748: u32 = undefined; var x749: u32 = undefined; fiatP384MulxU32(&x748, &x749, x718, 0xffffffff); var x750: u32 = undefined; var x751: u32 = undefined; fiatP384MulxU32(&x750, &x751, x718, 0xffffffff); var x752: u32 = undefined; var x753: u32 = undefined; fiatP384MulxU32(&x752, &x753, x718, 0xffffffff); var x754: u32 = undefined; var x755: u32 = undefined; fiatP384MulxU32(&x754, &x755, x718, 0xffffffff); var x756: u32 = undefined; var x757: u32 = undefined; fiatP384MulxU32(&x756, &x757, x718, 0xffffffff); var x758: u32 = undefined; var x759: u32 = undefined; fiatP384MulxU32(&x758, &x759, x718, 0xfffffffe); var x760: u32 = undefined; var x761: u32 = undefined; fiatP384MulxU32(&x760, &x761, x718, 0xffffffff); var x762: u32 = undefined; var x763: u32 = undefined; fiatP384MulxU32(&x762, &x763, x718, 0xffffffff); var x764: u32 = undefined; var x765: u1 = undefined; fiatP384AddcarryxU32(&x764, &x765, 0x0, x761, x758); var x766: u32 = undefined; var x767: u1 = undefined; fiatP384AddcarryxU32(&x766, &x767, x765, x759, x756); var x768: u32 = undefined; var x769: u1 = undefined; fiatP384AddcarryxU32(&x768, &x769, x767, x757, x754); var x770: u32 = undefined; var x771: u1 = undefined; fiatP384AddcarryxU32(&x770, &x771, x769, x755, x752); var x772: u32 = undefined; var x773: u1 = undefined; fiatP384AddcarryxU32(&x772, &x773, x771, x753, x750); var x774: u32 = undefined; var x775: u1 = undefined; fiatP384AddcarryxU32(&x774, &x775, x773, x751, x748); var x776: u32 = undefined; var x777: u1 = undefined; fiatP384AddcarryxU32(&x776, &x777, x775, x749, x746); var x778: u32 = undefined; var x779: u1 = undefined; fiatP384AddcarryxU32(&x778, &x779, x777, x747, x744); const x780: u32 = (@intCast(u32, x779) + x745); var x781: u32 = undefined; var x782: u1 = undefined; fiatP384AddcarryxU32(&x781, &x782, 0x0, x718, x762); var x783: u32 = undefined; var x784: u1 = undefined; fiatP384AddcarryxU32(&x783, &x784, x782, x720, x763); var x785: u32 = undefined; var x786: u1 = undefined; fiatP384AddcarryxU32(&x785, &x786, x784, x722, @intCast(u32, 0x0)); var x787: u32 = undefined; var x788: u1 = undefined; fiatP384AddcarryxU32(&x787, &x788, x786, x724, x760); var x789: u32 = undefined; var x790: u1 = undefined; fiatP384AddcarryxU32(&x789, &x790, x788, x726, x764); var x791: u32 = undefined; var x792: u1 = undefined; fiatP384AddcarryxU32(&x791, &x792, x790, x728, x766); var x793: u32 = undefined; var x794: u1 = undefined; fiatP384AddcarryxU32(&x793, &x794, x792, x730, x768); var x795: u32 = undefined; var x796: u1 = undefined; fiatP384AddcarryxU32(&x795, &x796, x794, x732, x770); var x797: u32 = undefined; var x798: u1 = undefined; fiatP384AddcarryxU32(&x797, &x798, x796, x734, x772); var x799: u32 = undefined; var x800: u1 = undefined; fiatP384AddcarryxU32(&x799, &x800, x798, x736, x774); var x801: u32 = undefined; var x802: u1 = undefined; fiatP384AddcarryxU32(&x801, &x802, x800, x738, x776); var x803: u32 = undefined; var x804: u1 = undefined; fiatP384AddcarryxU32(&x803, &x804, x802, x740, x778); var x805: u32 = undefined; var x806: u1 = undefined; fiatP384AddcarryxU32(&x805, &x806, x804, x742, x780); const x807: u32 = (@intCast(u32, x806) + @intCast(u32, x743)); var x808: u32 = undefined; var x809: u32 = undefined; fiatP384MulxU32(&x808, &x809, x6, (arg1[11])); var x810: u32 = undefined; var x811: u32 = undefined; fiatP384MulxU32(&x810, &x811, x6, (arg1[10])); var x812: u32 = undefined; var x813: u32 = undefined; fiatP384MulxU32(&x812, &x813, x6, (arg1[9])); var x814: u32 = undefined; var x815: u32 = undefined; fiatP384MulxU32(&x814, &x815, x6, (arg1[8])); var x816: u32 = undefined; var x817: u32 = undefined; fiatP384MulxU32(&x816, &x817, x6, (arg1[7])); var x818: u32 = undefined; var x819: u32 = undefined; fiatP384MulxU32(&x818, &x819, x6, (arg1[6])); var x820: u32 = undefined; var x821: u32 = undefined; fiatP384MulxU32(&x820, &x821, x6, (arg1[5])); var x822: u32 = undefined; var x823: u32 = undefined; fiatP384MulxU32(&x822, &x823, x6, (arg1[4])); var x824: u32 = undefined; var x825: u32 = undefined; fiatP384MulxU32(&x824, &x825, x6, (arg1[3])); var x826: u32 = undefined; var x827: u32 = undefined; fiatP384MulxU32(&x826, &x827, x6, (arg1[2])); var x828: u32 = undefined; var x829: u32 = undefined; fiatP384MulxU32(&x828, &x829, x6, (arg1[1])); var x830: u32 = undefined; var x831: u32 = undefined; fiatP384MulxU32(&x830, &x831, x6, (arg1[0])); var x832: u32 = undefined; var x833: u1 = undefined; fiatP384AddcarryxU32(&x832, &x833, 0x0, x831, x828); var x834: u32 = undefined; var x835: u1 = undefined; fiatP384AddcarryxU32(&x834, &x835, x833, x829, x826); var x836: u32 = undefined; var x837: u1 = undefined; fiatP384AddcarryxU32(&x836, &x837, x835, x827, x824); var x838: u32 = undefined; var x839: u1 = undefined; fiatP384AddcarryxU32(&x838, &x839, x837, x825, x822); var x840: u32 = undefined; var x841: u1 = undefined; fiatP384AddcarryxU32(&x840, &x841, x839, x823, x820); var x842: u32 = undefined; var x843: u1 = undefined; fiatP384AddcarryxU32(&x842, &x843, x841, x821, x818); var x844: u32 = undefined; var x845: u1 = undefined; fiatP384AddcarryxU32(&x844, &x845, x843, x819, x816); var x846: u32 = undefined; var x847: u1 = undefined; fiatP384AddcarryxU32(&x846, &x847, x845, x817, x814); var x848: u32 = undefined; var x849: u1 = undefined; fiatP384AddcarryxU32(&x848, &x849, x847, x815, x812); var x850: u32 = undefined; var x851: u1 = undefined; fiatP384AddcarryxU32(&x850, &x851, x849, x813, x810); var x852: u32 = undefined; var x853: u1 = undefined; fiatP384AddcarryxU32(&x852, &x853, x851, x811, x808); const x854: u32 = (@intCast(u32, x853) + x809); var x855: u32 = undefined; var x856: u1 = undefined; fiatP384AddcarryxU32(&x855, &x856, 0x0, x783, x830); var x857: u32 = undefined; var x858: u1 = undefined; fiatP384AddcarryxU32(&x857, &x858, x856, x785, x832); var x859: u32 = undefined; var x860: u1 = undefined; fiatP384AddcarryxU32(&x859, &x860, x858, x787, x834); var x861: u32 = undefined; var x862: u1 = undefined; fiatP384AddcarryxU32(&x861, &x862, x860, x789, x836); var x863: u32 = undefined; var x864: u1 = undefined; fiatP384AddcarryxU32(&x863, &x864, x862, x791, x838); var x865: u32 = undefined; var x866: u1 = undefined; fiatP384AddcarryxU32(&x865, &x866, x864, x793, x840); var x867: u32 = undefined; var x868: u1 = undefined; fiatP384AddcarryxU32(&x867, &x868, x866, x795, x842); var x869: u32 = undefined; var x870: u1 = undefined; fiatP384AddcarryxU32(&x869, &x870, x868, x797, x844); var x871: u32 = undefined; var x872: u1 = undefined; fiatP384AddcarryxU32(&x871, &x872, x870, x799, x846); var x873: u32 = undefined; var x874: u1 = undefined; fiatP384AddcarryxU32(&x873, &x874, x872, x801, x848); var x875: u32 = undefined; var x876: u1 = undefined; fiatP384AddcarryxU32(&x875, &x876, x874, x803, x850); var x877: u32 = undefined; var x878: u1 = undefined; fiatP384AddcarryxU32(&x877, &x878, x876, x805, x852); var x879: u32 = undefined; var x880: u1 = undefined; fiatP384AddcarryxU32(&x879, &x880, x878, x807, x854); var x881: u32 = undefined; var x882: u32 = undefined; fiatP384MulxU32(&x881, &x882, x855, 0xffffffff); var x883: u32 = undefined; var x884: u32 = undefined; fiatP384MulxU32(&x883, &x884, x855, 0xffffffff); var x885: u32 = undefined; var x886: u32 = undefined; fiatP384MulxU32(&x885, &x886, x855, 0xffffffff); var x887: u32 = undefined; var x888: u32 = undefined; fiatP384MulxU32(&x887, &x888, x855, 0xffffffff); var x889: u32 = undefined; var x890: u32 = undefined; fiatP384MulxU32(&x889, &x890, x855, 0xffffffff); var x891: u32 = undefined; var x892: u32 = undefined; fiatP384MulxU32(&x891, &x892, x855, 0xffffffff); var x893: u32 = undefined; var x894: u32 = undefined; fiatP384MulxU32(&x893, &x894, x855, 0xffffffff); var x895: u32 = undefined; var x896: u32 = undefined; fiatP384MulxU32(&x895, &x896, x855, 0xfffffffe); var x897: u32 = undefined; var x898: u32 = undefined; fiatP384MulxU32(&x897, &x898, x855, 0xffffffff); var x899: u32 = undefined; var x900: u32 = undefined; fiatP384MulxU32(&x899, &x900, x855, 0xffffffff); var x901: u32 = undefined; var x902: u1 = undefined; fiatP384AddcarryxU32(&x901, &x902, 0x0, x898, x895); var x903: u32 = undefined; var x904: u1 = undefined; fiatP384AddcarryxU32(&x903, &x904, x902, x896, x893); var x905: u32 = undefined; var x906: u1 = undefined; fiatP384AddcarryxU32(&x905, &x906, x904, x894, x891); var x907: u32 = undefined; var x908: u1 = undefined; fiatP384AddcarryxU32(&x907, &x908, x906, x892, x889); var x909: u32 = undefined; var x910: u1 = undefined; fiatP384AddcarryxU32(&x909, &x910, x908, x890, x887); var x911: u32 = undefined; var x912: u1 = undefined; fiatP384AddcarryxU32(&x911, &x912, x910, x888, x885); var x913: u32 = undefined; var x914: u1 = undefined; fiatP384AddcarryxU32(&x913, &x914, x912, x886, x883); var x915: u32 = undefined; var x916: u1 = undefined; fiatP384AddcarryxU32(&x915, &x916, x914, x884, x881); const x917: u32 = (@intCast(u32, x916) + x882); var x918: u32 = undefined; var x919: u1 = undefined; fiatP384AddcarryxU32(&x918, &x919, 0x0, x855, x899); var x920: u32 = undefined; var x921: u1 = undefined; fiatP384AddcarryxU32(&x920, &x921, x919, x857, x900); var x922: u32 = undefined; var x923: u1 = undefined; fiatP384AddcarryxU32(&x922, &x923, x921, x859, @intCast(u32, 0x0)); var x924: u32 = undefined; var x925: u1 = undefined; fiatP384AddcarryxU32(&x924, &x925, x923, x861, x897); var x926: u32 = undefined; var x927: u1 = undefined; fiatP384AddcarryxU32(&x926, &x927, x925, x863, x901); var x928: u32 = undefined; var x929: u1 = undefined; fiatP384AddcarryxU32(&x928, &x929, x927, x865, x903); var x930: u32 = undefined; var x931: u1 = undefined; fiatP384AddcarryxU32(&x930, &x931, x929, x867, x905); var x932: u32 = undefined; var x933: u1 = undefined; fiatP384AddcarryxU32(&x932, &x933, x931, x869, x907); var x934: u32 = undefined; var x935: u1 = undefined; fiatP384AddcarryxU32(&x934, &x935, x933, x871, x909); var x936: u32 = undefined; var x937: u1 = undefined; fiatP384AddcarryxU32(&x936, &x937, x935, x873, x911); var x938: u32 = undefined; var x939: u1 = undefined; fiatP384AddcarryxU32(&x938, &x939, x937, x875, x913); var x940: u32 = undefined; var x941: u1 = undefined; fiatP384AddcarryxU32(&x940, &x941, x939, x877, x915); var x942: u32 = undefined; var x943: u1 = undefined; fiatP384AddcarryxU32(&x942, &x943, x941, x879, x917); const x944: u32 = (@intCast(u32, x943) + @intCast(u32, x880)); var x945: u32 = undefined; var x946: u32 = undefined; fiatP384MulxU32(&x945, &x946, x7, (arg1[11])); var x947: u32 = undefined; var x948: u32 = undefined; fiatP384MulxU32(&x947, &x948, x7, (arg1[10])); var x949: u32 = undefined; var x950: u32 = undefined; fiatP384MulxU32(&x949, &x950, x7, (arg1[9])); var x951: u32 = undefined; var x952: u32 = undefined; fiatP384MulxU32(&x951, &x952, x7, (arg1[8])); var x953: u32 = undefined; var x954: u32 = undefined; fiatP384MulxU32(&x953, &x954, x7, (arg1[7])); var x955: u32 = undefined; var x956: u32 = undefined; fiatP384MulxU32(&x955, &x956, x7, (arg1[6])); var x957: u32 = undefined; var x958: u32 = undefined; fiatP384MulxU32(&x957, &x958, x7, (arg1[5])); var x959: u32 = undefined; var x960: u32 = undefined; fiatP384MulxU32(&x959, &x960, x7, (arg1[4])); var x961: u32 = undefined; var x962: u32 = undefined; fiatP384MulxU32(&x961, &x962, x7, (arg1[3])); var x963: u32 = undefined; var x964: u32 = undefined; fiatP384MulxU32(&x963, &x964, x7, (arg1[2])); var x965: u32 = undefined; var x966: u32 = undefined; fiatP384MulxU32(&x965, &x966, x7, (arg1[1])); var x967: u32 = undefined; var x968: u32 = undefined; fiatP384MulxU32(&x967, &x968, x7, (arg1[0])); var x969: u32 = undefined; var x970: u1 = undefined; fiatP384AddcarryxU32(&x969, &x970, 0x0, x968, x965); var x971: u32 = undefined; var x972: u1 = undefined; fiatP384AddcarryxU32(&x971, &x972, x970, x966, x963); var x973: u32 = undefined; var x974: u1 = undefined; fiatP384AddcarryxU32(&x973, &x974, x972, x964, x961); var x975: u32 = undefined; var x976: u1 = undefined; fiatP384AddcarryxU32(&x975, &x976, x974, x962, x959); var x977: u32 = undefined; var x978: u1 = undefined; fiatP384AddcarryxU32(&x977, &x978, x976, x960, x957); var x979: u32 = undefined; var x980: u1 = undefined; fiatP384AddcarryxU32(&x979, &x980, x978, x958, x955); var x981: u32 = undefined; var x982: u1 = undefined; fiatP384AddcarryxU32(&x981, &x982, x980, x956, x953); var x983: u32 = undefined; var x984: u1 = undefined; fiatP384AddcarryxU32(&x983, &x984, x982, x954, x951); var x985: u32 = undefined; var x986: u1 = undefined; fiatP384AddcarryxU32(&x985, &x986, x984, x952, x949); var x987: u32 = undefined; var x988: u1 = undefined; fiatP384AddcarryxU32(&x987, &x988, x986, x950, x947); var x989: u32 = undefined; var x990: u1 = undefined; fiatP384AddcarryxU32(&x989, &x990, x988, x948, x945); const x991: u32 = (@intCast(u32, x990) + x946); var x992: u32 = undefined; var x993: u1 = undefined; fiatP384AddcarryxU32(&x992, &x993, 0x0, x920, x967); var x994: u32 = undefined; var x995: u1 = undefined; fiatP384AddcarryxU32(&x994, &x995, x993, x922, x969); var x996: u32 = undefined; var x997: u1 = undefined; fiatP384AddcarryxU32(&x996, &x997, x995, x924, x971); var x998: u32 = undefined; var x999: u1 = undefined; fiatP384AddcarryxU32(&x998, &x999, x997, x926, x973); var x1000: u32 = undefined; var x1001: u1 = undefined; fiatP384AddcarryxU32(&x1000, &x1001, x999, x928, x975); var x1002: u32 = undefined; var x1003: u1 = undefined; fiatP384AddcarryxU32(&x1002, &x1003, x1001, x930, x977); var x1004: u32 = undefined; var x1005: u1 = undefined; fiatP384AddcarryxU32(&x1004, &x1005, x1003, x932, x979); var x1006: u32 = undefined; var x1007: u1 = undefined; fiatP384AddcarryxU32(&x1006, &x1007, x1005, x934, x981); var x1008: u32 = undefined; var x1009: u1 = undefined; fiatP384AddcarryxU32(&x1008, &x1009, x1007, x936, x983); var x1010: u32 = undefined; var x1011: u1 = undefined; fiatP384AddcarryxU32(&x1010, &x1011, x1009, x938, x985); var x1012: u32 = undefined; var x1013: u1 = undefined; fiatP384AddcarryxU32(&x1012, &x1013, x1011, x940, x987); var x1014: u32 = undefined; var x1015: u1 = undefined; fiatP384AddcarryxU32(&x1014, &x1015, x1013, x942, x989); var x1016: u32 = undefined; var x1017: u1 = undefined; fiatP384AddcarryxU32(&x1016, &x1017, x1015, x944, x991); var x1018: u32 = undefined; var x1019: u32 = undefined; fiatP384MulxU32(&x1018, &x1019, x992, 0xffffffff); var x1020: u32 = undefined; var x1021: u32 = undefined; fiatP384MulxU32(&x1020, &x1021, x992, 0xffffffff); var x1022: u32 = undefined; var x1023: u32 = undefined; fiatP384MulxU32(&x1022, &x1023, x992, 0xffffffff); var x1024: u32 = undefined; var x1025: u32 = undefined; fiatP384MulxU32(&x1024, &x1025, x992, 0xffffffff); var x1026: u32 = undefined; var x1027: u32 = undefined; fiatP384MulxU32(&x1026, &x1027, x992, 0xffffffff); var x1028: u32 = undefined; var x1029: u32 = undefined; fiatP384MulxU32(&x1028, &x1029, x992, 0xffffffff); var x1030: u32 = undefined; var x1031: u32 = undefined; fiatP384MulxU32(&x1030, &x1031, x992, 0xffffffff); var x1032: u32 = undefined; var x1033: u32 = undefined; fiatP384MulxU32(&x1032, &x1033, x992, 0xfffffffe); var x1034: u32 = undefined; var x1035: u32 = undefined; fiatP384MulxU32(&x1034, &x1035, x992, 0xffffffff); var x1036: u32 = undefined; var x1037: u32 = undefined; fiatP384MulxU32(&x1036, &x1037, x992, 0xffffffff); var x1038: u32 = undefined; var x1039: u1 = undefined; fiatP384AddcarryxU32(&x1038, &x1039, 0x0, x1035, x1032); var x1040: u32 = undefined; var x1041: u1 = undefined; fiatP384AddcarryxU32(&x1040, &x1041, x1039, x1033, x1030); var x1042: u32 = undefined; var x1043: u1 = undefined; fiatP384AddcarryxU32(&x1042, &x1043, x1041, x1031, x1028); var x1044: u32 = undefined; var x1045: u1 = undefined; fiatP384AddcarryxU32(&x1044, &x1045, x1043, x1029, x1026); var x1046: u32 = undefined; var x1047: u1 = undefined; fiatP384AddcarryxU32(&x1046, &x1047, x1045, x1027, x1024); var x1048: u32 = undefined; var x1049: u1 = undefined; fiatP384AddcarryxU32(&x1048, &x1049, x1047, x1025, x1022); var x1050: u32 = undefined; var x1051: u1 = undefined; fiatP384AddcarryxU32(&x1050, &x1051, x1049, x1023, x1020); var x1052: u32 = undefined; var x1053: u1 = undefined; fiatP384AddcarryxU32(&x1052, &x1053, x1051, x1021, x1018); const x1054: u32 = (@intCast(u32, x1053) + x1019); var x1055: u32 = undefined; var x1056: u1 = undefined; fiatP384AddcarryxU32(&x1055, &x1056, 0x0, x992, x1036); var x1057: u32 = undefined; var x1058: u1 = undefined; fiatP384AddcarryxU32(&x1057, &x1058, x1056, x994, x1037); var x1059: u32 = undefined; var x1060: u1 = undefined; fiatP384AddcarryxU32(&x1059, &x1060, x1058, x996, @intCast(u32, 0x0)); var x1061: u32 = undefined; var x1062: u1 = undefined; fiatP384AddcarryxU32(&x1061, &x1062, x1060, x998, x1034); var x1063: u32 = undefined; var x1064: u1 = undefined; fiatP384AddcarryxU32(&x1063, &x1064, x1062, x1000, x1038); var x1065: u32 = undefined; var x1066: u1 = undefined; fiatP384AddcarryxU32(&x1065, &x1066, x1064, x1002, x1040); var x1067: u32 = undefined; var x1068: u1 = undefined; fiatP384AddcarryxU32(&x1067, &x1068, x1066, x1004, x1042); var x1069: u32 = undefined; var x1070: u1 = undefined; fiatP384AddcarryxU32(&x1069, &x1070, x1068, x1006, x1044); var x1071: u32 = undefined; var x1072: u1 = undefined; fiatP384AddcarryxU32(&x1071, &x1072, x1070, x1008, x1046); var x1073: u32 = undefined; var x1074: u1 = undefined; fiatP384AddcarryxU32(&x1073, &x1074, x1072, x1010, x1048); var x1075: u32 = undefined; var x1076: u1 = undefined; fiatP384AddcarryxU32(&x1075, &x1076, x1074, x1012, x1050); var x1077: u32 = undefined; var x1078: u1 = undefined; fiatP384AddcarryxU32(&x1077, &x1078, x1076, x1014, x1052); var x1079: u32 = undefined; var x1080: u1 = undefined; fiatP384AddcarryxU32(&x1079, &x1080, x1078, x1016, x1054); const x1081: u32 = (@intCast(u32, x1080) + @intCast(u32, x1017)); var x1082: u32 = undefined; var x1083: u32 = undefined; fiatP384MulxU32(&x1082, &x1083, x8, (arg1[11])); var x1084: u32 = undefined; var x1085: u32 = undefined; fiatP384MulxU32(&x1084, &x1085, x8, (arg1[10])); var x1086: u32 = undefined; var x1087: u32 = undefined; fiatP384MulxU32(&x1086, &x1087, x8, (arg1[9])); var x1088: u32 = undefined; var x1089: u32 = undefined; fiatP384MulxU32(&x1088, &x1089, x8, (arg1[8])); var x1090: u32 = undefined; var x1091: u32 = undefined; fiatP384MulxU32(&x1090, &x1091, x8, (arg1[7])); var x1092: u32 = undefined; var x1093: u32 = undefined; fiatP384MulxU32(&x1092, &x1093, x8, (arg1[6])); var x1094: u32 = undefined; var x1095: u32 = undefined; fiatP384MulxU32(&x1094, &x1095, x8, (arg1[5])); var x1096: u32 = undefined; var x1097: u32 = undefined; fiatP384MulxU32(&x1096, &x1097, x8, (arg1[4])); var x1098: u32 = undefined; var x1099: u32 = undefined; fiatP384MulxU32(&x1098, &x1099, x8, (arg1[3])); var x1100: u32 = undefined; var x1101: u32 = undefined; fiatP384MulxU32(&x1100, &x1101, x8, (arg1[2])); var x1102: u32 = undefined; var x1103: u32 = undefined; fiatP384MulxU32(&x1102, &x1103, x8, (arg1[1])); var x1104: u32 = undefined; var x1105: u32 = undefined; fiatP384MulxU32(&x1104, &x1105, x8, (arg1[0])); var x1106: u32 = undefined; var x1107: u1 = undefined; fiatP384AddcarryxU32(&x1106, &x1107, 0x0, x1105, x1102); var x1108: u32 = undefined; var x1109: u1 = undefined; fiatP384AddcarryxU32(&x1108, &x1109, x1107, x1103, x1100); var x1110: u32 = undefined; var x1111: u1 = undefined; fiatP384AddcarryxU32(&x1110, &x1111, x1109, x1101, x1098); var x1112: u32 = undefined; var x1113: u1 = undefined; fiatP384AddcarryxU32(&x1112, &x1113, x1111, x1099, x1096); var x1114: u32 = undefined; var x1115: u1 = undefined; fiatP384AddcarryxU32(&x1114, &x1115, x1113, x1097, x1094); var x1116: u32 = undefined; var x1117: u1 = undefined; fiatP384AddcarryxU32(&x1116, &x1117, x1115, x1095, x1092); var x1118: u32 = undefined; var x1119: u1 = undefined; fiatP384AddcarryxU32(&x1118, &x1119, x1117, x1093, x1090); var x1120: u32 = undefined; var x1121: u1 = undefined; fiatP384AddcarryxU32(&x1120, &x1121, x1119, x1091, x1088); var x1122: u32 = undefined; var x1123: u1 = undefined; fiatP384AddcarryxU32(&x1122, &x1123, x1121, x1089, x1086); var x1124: u32 = undefined; var x1125: u1 = undefined; fiatP384AddcarryxU32(&x1124, &x1125, x1123, x1087, x1084); var x1126: u32 = undefined; var x1127: u1 = undefined; fiatP384AddcarryxU32(&x1126, &x1127, x1125, x1085, x1082); const x1128: u32 = (@intCast(u32, x1127) + x1083); var x1129: u32 = undefined; var x1130: u1 = undefined; fiatP384AddcarryxU32(&x1129, &x1130, 0x0, x1057, x1104); var x1131: u32 = undefined; var x1132: u1 = undefined; fiatP384AddcarryxU32(&x1131, &x1132, x1130, x1059, x1106); var x1133: u32 = undefined; var x1134: u1 = undefined; fiatP384AddcarryxU32(&x1133, &x1134, x1132, x1061, x1108); var x1135: u32 = undefined; var x1136: u1 = undefined; fiatP384AddcarryxU32(&x1135, &x1136, x1134, x1063, x1110); var x1137: u32 = undefined; var x1138: u1 = undefined; fiatP384AddcarryxU32(&x1137, &x1138, x1136, x1065, x1112); var x1139: u32 = undefined; var x1140: u1 = undefined; fiatP384AddcarryxU32(&x1139, &x1140, x1138, x1067, x1114); var x1141: u32 = undefined; var x1142: u1 = undefined; fiatP384AddcarryxU32(&x1141, &x1142, x1140, x1069, x1116); var x1143: u32 = undefined; var x1144: u1 = undefined; fiatP384AddcarryxU32(&x1143, &x1144, x1142, x1071, x1118); var x1145: u32 = undefined; var x1146: u1 = undefined; fiatP384AddcarryxU32(&x1145, &x1146, x1144, x1073, x1120); var x1147: u32 = undefined; var x1148: u1 = undefined; fiatP384AddcarryxU32(&x1147, &x1148, x1146, x1075, x1122); var x1149: u32 = undefined; var x1150: u1 = undefined; fiatP384AddcarryxU32(&x1149, &x1150, x1148, x1077, x1124); var x1151: u32 = undefined; var x1152: u1 = undefined; fiatP384AddcarryxU32(&x1151, &x1152, x1150, x1079, x1126); var x1153: u32 = undefined; var x1154: u1 = undefined; fiatP384AddcarryxU32(&x1153, &x1154, x1152, x1081, x1128); var x1155: u32 = undefined; var x1156: u32 = undefined; fiatP384MulxU32(&x1155, &x1156, x1129, 0xffffffff); var x1157: u32 = undefined; var x1158: u32 = undefined; fiatP384MulxU32(&x1157, &x1158, x1129, 0xffffffff); var x1159: u32 = undefined; var x1160: u32 = undefined; fiatP384MulxU32(&x1159, &x1160, x1129, 0xffffffff); var x1161: u32 = undefined; var x1162: u32 = undefined; fiatP384MulxU32(&x1161, &x1162, x1129, 0xffffffff); var x1163: u32 = undefined; var x1164: u32 = undefined; fiatP384MulxU32(&x1163, &x1164, x1129, 0xffffffff); var x1165: u32 = undefined; var x1166: u32 = undefined; fiatP384MulxU32(&x1165, &x1166, x1129, 0xffffffff); var x1167: u32 = undefined; var x1168: u32 = undefined; fiatP384MulxU32(&x1167, &x1168, x1129, 0xffffffff); var x1169: u32 = undefined; var x1170: u32 = undefined; fiatP384MulxU32(&x1169, &x1170, x1129, 0xfffffffe); var x1171: u32 = undefined; var x1172: u32 = undefined; fiatP384MulxU32(&x1171, &x1172, x1129, 0xffffffff); var x1173: u32 = undefined; var x1174: u32 = undefined; fiatP384MulxU32(&x1173, &x1174, x1129, 0xffffffff); var x1175: u32 = undefined; var x1176: u1 = undefined; fiatP384AddcarryxU32(&x1175, &x1176, 0x0, x1172, x1169); var x1177: u32 = undefined; var x1178: u1 = undefined; fiatP384AddcarryxU32(&x1177, &x1178, x1176, x1170, x1167); var x1179: u32 = undefined; var x1180: u1 = undefined; fiatP384AddcarryxU32(&x1179, &x1180, x1178, x1168, x1165); var x1181: u32 = undefined; var x1182: u1 = undefined; fiatP384AddcarryxU32(&x1181, &x1182, x1180, x1166, x1163); var x1183: u32 = undefined; var x1184: u1 = undefined; fiatP384AddcarryxU32(&x1183, &x1184, x1182, x1164, x1161); var x1185: u32 = undefined; var x1186: u1 = undefined; fiatP384AddcarryxU32(&x1185, &x1186, x1184, x1162, x1159); var x1187: u32 = undefined; var x1188: u1 = undefined; fiatP384AddcarryxU32(&x1187, &x1188, x1186, x1160, x1157); var x1189: u32 = undefined; var x1190: u1 = undefined; fiatP384AddcarryxU32(&x1189, &x1190, x1188, x1158, x1155); const x1191: u32 = (@intCast(u32, x1190) + x1156); var x1192: u32 = undefined; var x1193: u1 = undefined; fiatP384AddcarryxU32(&x1192, &x1193, 0x0, x1129, x1173); var x1194: u32 = undefined; var x1195: u1 = undefined; fiatP384AddcarryxU32(&x1194, &x1195, x1193, x1131, x1174); var x1196: u32 = undefined; var x1197: u1 = undefined; fiatP384AddcarryxU32(&x1196, &x1197, x1195, x1133, @intCast(u32, 0x0)); var x1198: u32 = undefined; var x1199: u1 = undefined; fiatP384AddcarryxU32(&x1198, &x1199, x1197, x1135, x1171); var x1200: u32 = undefined; var x1201: u1 = undefined; fiatP384AddcarryxU32(&x1200, &x1201, x1199, x1137, x1175); var x1202: u32 = undefined; var x1203: u1 = undefined; fiatP384AddcarryxU32(&x1202, &x1203, x1201, x1139, x1177); var x1204: u32 = undefined; var x1205: u1 = undefined; fiatP384AddcarryxU32(&x1204, &x1205, x1203, x1141, x1179); var x1206: u32 = undefined; var x1207: u1 = undefined; fiatP384AddcarryxU32(&x1206, &x1207, x1205, x1143, x1181); var x1208: u32 = undefined; var x1209: u1 = undefined; fiatP384AddcarryxU32(&x1208, &x1209, x1207, x1145, x1183); var x1210: u32 = undefined; var x1211: u1 = undefined; fiatP384AddcarryxU32(&x1210, &x1211, x1209, x1147, x1185); var x1212: u32 = undefined; var x1213: u1 = undefined; fiatP384AddcarryxU32(&x1212, &x1213, x1211, x1149, x1187); var x1214: u32 = undefined; var x1215: u1 = undefined; fiatP384AddcarryxU32(&x1214, &x1215, x1213, x1151, x1189); var x1216: u32 = undefined; var x1217: u1 = undefined; fiatP384AddcarryxU32(&x1216, &x1217, x1215, x1153, x1191); const x1218: u32 = (@intCast(u32, x1217) + @intCast(u32, x1154)); var x1219: u32 = undefined; var x1220: u32 = undefined; fiatP384MulxU32(&x1219, &x1220, x9, (arg1[11])); var x1221: u32 = undefined; var x1222: u32 = undefined; fiatP384MulxU32(&x1221, &x1222, x9, (arg1[10])); var x1223: u32 = undefined; var x1224: u32 = undefined; fiatP384MulxU32(&x1223, &x1224, x9, (arg1[9])); var x1225: u32 = undefined; var x1226: u32 = undefined; fiatP384MulxU32(&x1225, &x1226, x9, (arg1[8])); var x1227: u32 = undefined; var x1228: u32 = undefined; fiatP384MulxU32(&x1227, &x1228, x9, (arg1[7])); var x1229: u32 = undefined; var x1230: u32 = undefined; fiatP384MulxU32(&x1229, &x1230, x9, (arg1[6])); var x1231: u32 = undefined; var x1232: u32 = undefined; fiatP384MulxU32(&x1231, &x1232, x9, (arg1[5])); var x1233: u32 = undefined; var x1234: u32 = undefined; fiatP384MulxU32(&x1233, &x1234, x9, (arg1[4])); var x1235: u32 = undefined; var x1236: u32 = undefined; fiatP384MulxU32(&x1235, &x1236, x9, (arg1[3])); var x1237: u32 = undefined; var x1238: u32 = undefined; fiatP384MulxU32(&x1237, &x1238, x9, (arg1[2])); var x1239: u32 = undefined; var x1240: u32 = undefined; fiatP384MulxU32(&x1239, &x1240, x9, (arg1[1])); var x1241: u32 = undefined; var x1242: u32 = undefined; fiatP384MulxU32(&x1241, &x1242, x9, (arg1[0])); var x1243: u32 = undefined; var x1244: u1 = undefined; fiatP384AddcarryxU32(&x1243, &x1244, 0x0, x1242, x1239); var x1245: u32 = undefined; var x1246: u1 = undefined; fiatP384AddcarryxU32(&x1245, &x1246, x1244, x1240, x1237); var x1247: u32 = undefined; var x1248: u1 = undefined; fiatP384AddcarryxU32(&x1247, &x1248, x1246, x1238, x1235); var x1249: u32 = undefined; var x1250: u1 = undefined; fiatP384AddcarryxU32(&x1249, &x1250, x1248, x1236, x1233); var x1251: u32 = undefined; var x1252: u1 = undefined; fiatP384AddcarryxU32(&x1251, &x1252, x1250, x1234, x1231); var x1253: u32 = undefined; var x1254: u1 = undefined; fiatP384AddcarryxU32(&x1253, &x1254, x1252, x1232, x1229); var x1255: u32 = undefined; var x1256: u1 = undefined; fiatP384AddcarryxU32(&x1255, &x1256, x1254, x1230, x1227); var x1257: u32 = undefined; var x1258: u1 = undefined; fiatP384AddcarryxU32(&x1257, &x1258, x1256, x1228, x1225); var x1259: u32 = undefined; var x1260: u1 = undefined; fiatP384AddcarryxU32(&x1259, &x1260, x1258, x1226, x1223); var x1261: u32 = undefined; var x1262: u1 = undefined; fiatP384AddcarryxU32(&x1261, &x1262, x1260, x1224, x1221); var x1263: u32 = undefined; var x1264: u1 = undefined; fiatP384AddcarryxU32(&x1263, &x1264, x1262, x1222, x1219); const x1265: u32 = (@intCast(u32, x1264) + x1220); var x1266: u32 = undefined; var x1267: u1 = undefined; fiatP384AddcarryxU32(&x1266, &x1267, 0x0, x1194, x1241); var x1268: u32 = undefined; var x1269: u1 = undefined; fiatP384AddcarryxU32(&x1268, &x1269, x1267, x1196, x1243); var x1270: u32 = undefined; var x1271: u1 = undefined; fiatP384AddcarryxU32(&x1270, &x1271, x1269, x1198, x1245); var x1272: u32 = undefined; var x1273: u1 = undefined; fiatP384AddcarryxU32(&x1272, &x1273, x1271, x1200, x1247); var x1274: u32 = undefined; var x1275: u1 = undefined; fiatP384AddcarryxU32(&x1274, &x1275, x1273, x1202, x1249); var x1276: u32 = undefined; var x1277: u1 = undefined; fiatP384AddcarryxU32(&x1276, &x1277, x1275, x1204, x1251); var x1278: u32 = undefined; var x1279: u1 = undefined; fiatP384AddcarryxU32(&x1278, &x1279, x1277, x1206, x1253); var x1280: u32 = undefined; var x1281: u1 = undefined; fiatP384AddcarryxU32(&x1280, &x1281, x1279, x1208, x1255); var x1282: u32 = undefined; var x1283: u1 = undefined; fiatP384AddcarryxU32(&x1282, &x1283, x1281, x1210, x1257); var x1284: u32 = undefined; var x1285: u1 = undefined; fiatP384AddcarryxU32(&x1284, &x1285, x1283, x1212, x1259); var x1286: u32 = undefined; var x1287: u1 = undefined; fiatP384AddcarryxU32(&x1286, &x1287, x1285, x1214, x1261); var x1288: u32 = undefined; var x1289: u1 = undefined; fiatP384AddcarryxU32(&x1288, &x1289, x1287, x1216, x1263); var x1290: u32 = undefined; var x1291: u1 = undefined; fiatP384AddcarryxU32(&x1290, &x1291, x1289, x1218, x1265); var x1292: u32 = undefined; var x1293: u32 = undefined; fiatP384MulxU32(&x1292, &x1293, x1266, 0xffffffff); var x1294: u32 = undefined; var x1295: u32 = undefined; fiatP384MulxU32(&x1294, &x1295, x1266, 0xffffffff); var x1296: u32 = undefined; var x1297: u32 = undefined; fiatP384MulxU32(&x1296, &x1297, x1266, 0xffffffff); var x1298: u32 = undefined; var x1299: u32 = undefined; fiatP384MulxU32(&x1298, &x1299, x1266, 0xffffffff); var x1300: u32 = undefined; var x1301: u32 = undefined; fiatP384MulxU32(&x1300, &x1301, x1266, 0xffffffff); var x1302: u32 = undefined; var x1303: u32 = undefined; fiatP384MulxU32(&x1302, &x1303, x1266, 0xffffffff); var x1304: u32 = undefined; var x1305: u32 = undefined; fiatP384MulxU32(&x1304, &x1305, x1266, 0xffffffff); var x1306: u32 = undefined; var x1307: u32 = undefined; fiatP384MulxU32(&x1306, &x1307, x1266, 0xfffffffe); var x1308: u32 = undefined; var x1309: u32 = undefined; fiatP384MulxU32(&x1308, &x1309, x1266, 0xffffffff); var x1310: u32 = undefined; var x1311: u32 = undefined; fiatP384MulxU32(&x1310, &x1311, x1266, 0xffffffff); var x1312: u32 = undefined; var x1313: u1 = undefined; fiatP384AddcarryxU32(&x1312, &x1313, 0x0, x1309, x1306); var x1314: u32 = undefined; var x1315: u1 = undefined; fiatP384AddcarryxU32(&x1314, &x1315, x1313, x1307, x1304); var x1316: u32 = undefined; var x1317: u1 = undefined; fiatP384AddcarryxU32(&x1316, &x1317, x1315, x1305, x1302); var x1318: u32 = undefined; var x1319: u1 = undefined; fiatP384AddcarryxU32(&x1318, &x1319, x1317, x1303, x1300); var x1320: u32 = undefined; var x1321: u1 = undefined; fiatP384AddcarryxU32(&x1320, &x1321, x1319, x1301, x1298); var x1322: u32 = undefined; var x1323: u1 = undefined; fiatP384AddcarryxU32(&x1322, &x1323, x1321, x1299, x1296); var x1324: u32 = undefined; var x1325: u1 = undefined; fiatP384AddcarryxU32(&x1324, &x1325, x1323, x1297, x1294); var x1326: u32 = undefined; var x1327: u1 = undefined; fiatP384AddcarryxU32(&x1326, &x1327, x1325, x1295, x1292); const x1328: u32 = (@intCast(u32, x1327) + x1293); var x1329: u32 = undefined; var x1330: u1 = undefined; fiatP384AddcarryxU32(&x1329, &x1330, 0x0, x1266, x1310); var x1331: u32 = undefined; var x1332: u1 = undefined; fiatP384AddcarryxU32(&x1331, &x1332, x1330, x1268, x1311); var x1333: u32 = undefined; var x1334: u1 = undefined; fiatP384AddcarryxU32(&x1333, &x1334, x1332, x1270, @intCast(u32, 0x0)); var x1335: u32 = undefined; var x1336: u1 = undefined; fiatP384AddcarryxU32(&x1335, &x1336, x1334, x1272, x1308); var x1337: u32 = undefined; var x1338: u1 = undefined; fiatP384AddcarryxU32(&x1337, &x1338, x1336, x1274, x1312); var x1339: u32 = undefined; var x1340: u1 = undefined; fiatP384AddcarryxU32(&x1339, &x1340, x1338, x1276, x1314); var x1341: u32 = undefined; var x1342: u1 = undefined; fiatP384AddcarryxU32(&x1341, &x1342, x1340, x1278, x1316); var x1343: u32 = undefined; var x1344: u1 = undefined; fiatP384AddcarryxU32(&x1343, &x1344, x1342, x1280, x1318); var x1345: u32 = undefined; var x1346: u1 = undefined; fiatP384AddcarryxU32(&x1345, &x1346, x1344, x1282, x1320); var x1347: u32 = undefined; var x1348: u1 = undefined; fiatP384AddcarryxU32(&x1347, &x1348, x1346, x1284, x1322); var x1349: u32 = undefined; var x1350: u1 = undefined; fiatP384AddcarryxU32(&x1349, &x1350, x1348, x1286, x1324); var x1351: u32 = undefined; var x1352: u1 = undefined; fiatP384AddcarryxU32(&x1351, &x1352, x1350, x1288, x1326); var x1353: u32 = undefined; var x1354: u1 = undefined; fiatP384AddcarryxU32(&x1353, &x1354, x1352, x1290, x1328); const x1355: u32 = (@intCast(u32, x1354) + @intCast(u32, x1291)); var x1356: u32 = undefined; var x1357: u32 = undefined; fiatP384MulxU32(&x1356, &x1357, x10, (arg1[11])); var x1358: u32 = undefined; var x1359: u32 = undefined; fiatP384MulxU32(&x1358, &x1359, x10, (arg1[10])); var x1360: u32 = undefined; var x1361: u32 = undefined; fiatP384MulxU32(&x1360, &x1361, x10, (arg1[9])); var x1362: u32 = undefined; var x1363: u32 = undefined; fiatP384MulxU32(&x1362, &x1363, x10, (arg1[8])); var x1364: u32 = undefined; var x1365: u32 = undefined; fiatP384MulxU32(&x1364, &x1365, x10, (arg1[7])); var x1366: u32 = undefined; var x1367: u32 = undefined; fiatP384MulxU32(&x1366, &x1367, x10, (arg1[6])); var x1368: u32 = undefined; var x1369: u32 = undefined; fiatP384MulxU32(&x1368, &x1369, x10, (arg1[5])); var x1370: u32 = undefined; var x1371: u32 = undefined; fiatP384MulxU32(&x1370, &x1371, x10, (arg1[4])); var x1372: u32 = undefined; var x1373: u32 = undefined; fiatP384MulxU32(&x1372, &x1373, x10, (arg1[3])); var x1374: u32 = undefined; var x1375: u32 = undefined; fiatP384MulxU32(&x1374, &x1375, x10, (arg1[2])); var x1376: u32 = undefined; var x1377: u32 = undefined; fiatP384MulxU32(&x1376, &x1377, x10, (arg1[1])); var x1378: u32 = undefined; var x1379: u32 = undefined; fiatP384MulxU32(&x1378, &x1379, x10, (arg1[0])); var x1380: u32 = undefined; var x1381: u1 = undefined; fiatP384AddcarryxU32(&x1380, &x1381, 0x0, x1379, x1376); var x1382: u32 = undefined; var x1383: u1 = undefined; fiatP384AddcarryxU32(&x1382, &x1383, x1381, x1377, x1374); var x1384: u32 = undefined; var x1385: u1 = undefined; fiatP384AddcarryxU32(&x1384, &x1385, x1383, x1375, x1372); var x1386: u32 = undefined; var x1387: u1 = undefined; fiatP384AddcarryxU32(&x1386, &x1387, x1385, x1373, x1370); var x1388: u32 = undefined; var x1389: u1 = undefined; fiatP384AddcarryxU32(&x1388, &x1389, x1387, x1371, x1368); var x1390: u32 = undefined; var x1391: u1 = undefined; fiatP384AddcarryxU32(&x1390, &x1391, x1389, x1369, x1366); var x1392: u32 = undefined; var x1393: u1 = undefined; fiatP384AddcarryxU32(&x1392, &x1393, x1391, x1367, x1364); var x1394: u32 = undefined; var x1395: u1 = undefined; fiatP384AddcarryxU32(&x1394, &x1395, x1393, x1365, x1362); var x1396: u32 = undefined; var x1397: u1 = undefined; fiatP384AddcarryxU32(&x1396, &x1397, x1395, x1363, x1360); var x1398: u32 = undefined; var x1399: u1 = undefined; fiatP384AddcarryxU32(&x1398, &x1399, x1397, x1361, x1358); var x1400: u32 = undefined; var x1401: u1 = undefined; fiatP384AddcarryxU32(&x1400, &x1401, x1399, x1359, x1356); const x1402: u32 = (@intCast(u32, x1401) + x1357); var x1403: u32 = undefined; var x1404: u1 = undefined; fiatP384AddcarryxU32(&x1403, &x1404, 0x0, x1331, x1378); var x1405: u32 = undefined; var x1406: u1 = undefined; fiatP384AddcarryxU32(&x1405, &x1406, x1404, x1333, x1380); var x1407: u32 = undefined; var x1408: u1 = undefined; fiatP384AddcarryxU32(&x1407, &x1408, x1406, x1335, x1382); var x1409: u32 = undefined; var x1410: u1 = undefined; fiatP384AddcarryxU32(&x1409, &x1410, x1408, x1337, x1384); var x1411: u32 = undefined; var x1412: u1 = undefined; fiatP384AddcarryxU32(&x1411, &x1412, x1410, x1339, x1386); var x1413: u32 = undefined; var x1414: u1 = undefined; fiatP384AddcarryxU32(&x1413, &x1414, x1412, x1341, x1388); var x1415: u32 = undefined; var x1416: u1 = undefined; fiatP384AddcarryxU32(&x1415, &x1416, x1414, x1343, x1390); var x1417: u32 = undefined; var x1418: u1 = undefined; fiatP384AddcarryxU32(&x1417, &x1418, x1416, x1345, x1392); var x1419: u32 = undefined; var x1420: u1 = undefined; fiatP384AddcarryxU32(&x1419, &x1420, x1418, x1347, x1394); var x1421: u32 = undefined; var x1422: u1 = undefined; fiatP384AddcarryxU32(&x1421, &x1422, x1420, x1349, x1396); var x1423: u32 = undefined; var x1424: u1 = undefined; fiatP384AddcarryxU32(&x1423, &x1424, x1422, x1351, x1398); var x1425: u32 = undefined; var x1426: u1 = undefined; fiatP384AddcarryxU32(&x1425, &x1426, x1424, x1353, x1400); var x1427: u32 = undefined; var x1428: u1 = undefined; fiatP384AddcarryxU32(&x1427, &x1428, x1426, x1355, x1402); var x1429: u32 = undefined; var x1430: u32 = undefined; fiatP384MulxU32(&x1429, &x1430, x1403, 0xffffffff); var x1431: u32 = undefined; var x1432: u32 = undefined; fiatP384MulxU32(&x1431, &x1432, x1403, 0xffffffff); var x1433: u32 = undefined; var x1434: u32 = undefined; fiatP384MulxU32(&x1433, &x1434, x1403, 0xffffffff); var x1435: u32 = undefined; var x1436: u32 = undefined; fiatP384MulxU32(&x1435, &x1436, x1403, 0xffffffff); var x1437: u32 = undefined; var x1438: u32 = undefined; fiatP384MulxU32(&x1437, &x1438, x1403, 0xffffffff); var x1439: u32 = undefined; var x1440: u32 = undefined; fiatP384MulxU32(&x1439, &x1440, x1403, 0xffffffff); var x1441: u32 = undefined; var x1442: u32 = undefined; fiatP384MulxU32(&x1441, &x1442, x1403, 0xffffffff); var x1443: u32 = undefined; var x1444: u32 = undefined; fiatP384MulxU32(&x1443, &x1444, x1403, 0xfffffffe); var x1445: u32 = undefined; var x1446: u32 = undefined; fiatP384MulxU32(&x1445, &x1446, x1403, 0xffffffff); var x1447: u32 = undefined; var x1448: u32 = undefined; fiatP384MulxU32(&x1447, &x1448, x1403, 0xffffffff); var x1449: u32 = undefined; var x1450: u1 = undefined; fiatP384AddcarryxU32(&x1449, &x1450, 0x0, x1446, x1443); var x1451: u32 = undefined; var x1452: u1 = undefined; fiatP384AddcarryxU32(&x1451, &x1452, x1450, x1444, x1441); var x1453: u32 = undefined; var x1454: u1 = undefined; fiatP384AddcarryxU32(&x1453, &x1454, x1452, x1442, x1439); var x1455: u32 = undefined; var x1456: u1 = undefined; fiatP384AddcarryxU32(&x1455, &x1456, x1454, x1440, x1437); var x1457: u32 = undefined; var x1458: u1 = undefined; fiatP384AddcarryxU32(&x1457, &x1458, x1456, x1438, x1435); var x1459: u32 = undefined; var x1460: u1 = undefined; fiatP384AddcarryxU32(&x1459, &x1460, x1458, x1436, x1433); var x1461: u32 = undefined; var x1462: u1 = undefined; fiatP384AddcarryxU32(&x1461, &x1462, x1460, x1434, x1431); var x1463: u32 = undefined; var x1464: u1 = undefined; fiatP384AddcarryxU32(&x1463, &x1464, x1462, x1432, x1429); const x1465: u32 = (@intCast(u32, x1464) + x1430); var x1466: u32 = undefined; var x1467: u1 = undefined; fiatP384AddcarryxU32(&x1466, &x1467, 0x0, x1403, x1447); var x1468: u32 = undefined; var x1469: u1 = undefined; fiatP384AddcarryxU32(&x1468, &x1469, x1467, x1405, x1448); var x1470: u32 = undefined; var x1471: u1 = undefined; fiatP384AddcarryxU32(&x1470, &x1471, x1469, x1407, @intCast(u32, 0x0)); var x1472: u32 = undefined; var x1473: u1 = undefined; fiatP384AddcarryxU32(&x1472, &x1473, x1471, x1409, x1445); var x1474: u32 = undefined; var x1475: u1 = undefined; fiatP384AddcarryxU32(&x1474, &x1475, x1473, x1411, x1449); var x1476: u32 = undefined; var x1477: u1 = undefined; fiatP384AddcarryxU32(&x1476, &x1477, x1475, x1413, x1451); var x1478: u32 = undefined; var x1479: u1 = undefined; fiatP384AddcarryxU32(&x1478, &x1479, x1477, x1415, x1453); var x1480: u32 = undefined; var x1481: u1 = undefined; fiatP384AddcarryxU32(&x1480, &x1481, x1479, x1417, x1455); var x1482: u32 = undefined; var x1483: u1 = undefined; fiatP384AddcarryxU32(&x1482, &x1483, x1481, x1419, x1457); var x1484: u32 = undefined; var x1485: u1 = undefined; fiatP384AddcarryxU32(&x1484, &x1485, x1483, x1421, x1459); var x1486: u32 = undefined; var x1487: u1 = undefined; fiatP384AddcarryxU32(&x1486, &x1487, x1485, x1423, x1461); var x1488: u32 = undefined; var x1489: u1 = undefined; fiatP384AddcarryxU32(&x1488, &x1489, x1487, x1425, x1463); var x1490: u32 = undefined; var x1491: u1 = undefined; fiatP384AddcarryxU32(&x1490, &x1491, x1489, x1427, x1465); const x1492: u32 = (@intCast(u32, x1491) + @intCast(u32, x1428)); var x1493: u32 = undefined; var x1494: u32 = undefined; fiatP384MulxU32(&x1493, &x1494, x11, (arg1[11])); var x1495: u32 = undefined; var x1496: u32 = undefined; fiatP384MulxU32(&x1495, &x1496, x11, (arg1[10])); var x1497: u32 = undefined; var x1498: u32 = undefined; fiatP384MulxU32(&x1497, &x1498, x11, (arg1[9])); var x1499: u32 = undefined; var x1500: u32 = undefined; fiatP384MulxU32(&x1499, &x1500, x11, (arg1[8])); var x1501: u32 = undefined; var x1502: u32 = undefined; fiatP384MulxU32(&x1501, &x1502, x11, (arg1[7])); var x1503: u32 = undefined; var x1504: u32 = undefined; fiatP384MulxU32(&x1503, &x1504, x11, (arg1[6])); var x1505: u32 = undefined; var x1506: u32 = undefined; fiatP384MulxU32(&x1505, &x1506, x11, (arg1[5])); var x1507: u32 = undefined; var x1508: u32 = undefined; fiatP384MulxU32(&x1507, &x1508, x11, (arg1[4])); var x1509: u32 = undefined; var x1510: u32 = undefined; fiatP384MulxU32(&x1509, &x1510, x11, (arg1[3])); var x1511: u32 = undefined; var x1512: u32 = undefined; fiatP384MulxU32(&x1511, &x1512, x11, (arg1[2])); var x1513: u32 = undefined; var x1514: u32 = undefined; fiatP384MulxU32(&x1513, &x1514, x11, (arg1[1])); var x1515: u32 = undefined; var x1516: u32 = undefined; fiatP384MulxU32(&x1515, &x1516, x11, (arg1[0])); var x1517: u32 = undefined; var x1518: u1 = undefined; fiatP384AddcarryxU32(&x1517, &x1518, 0x0, x1516, x1513); var x1519: u32 = undefined; var x1520: u1 = undefined; fiatP384AddcarryxU32(&x1519, &x1520, x1518, x1514, x1511); var x1521: u32 = undefined; var x1522: u1 = undefined; fiatP384AddcarryxU32(&x1521, &x1522, x1520, x1512, x1509); var x1523: u32 = undefined; var x1524: u1 = undefined; fiatP384AddcarryxU32(&x1523, &x1524, x1522, x1510, x1507); var x1525: u32 = undefined; var x1526: u1 = undefined; fiatP384AddcarryxU32(&x1525, &x1526, x1524, x1508, x1505); var x1527: u32 = undefined; var x1528: u1 = undefined; fiatP384AddcarryxU32(&x1527, &x1528, x1526, x1506, x1503); var x1529: u32 = undefined; var x1530: u1 = undefined; fiatP384AddcarryxU32(&x1529, &x1530, x1528, x1504, x1501); var x1531: u32 = undefined; var x1532: u1 = undefined; fiatP384AddcarryxU32(&x1531, &x1532, x1530, x1502, x1499); var x1533: u32 = undefined; var x1534: u1 = undefined; fiatP384AddcarryxU32(&x1533, &x1534, x1532, x1500, x1497); var x1535: u32 = undefined; var x1536: u1 = undefined; fiatP384AddcarryxU32(&x1535, &x1536, x1534, x1498, x1495); var x1537: u32 = undefined; var x1538: u1 = undefined; fiatP384AddcarryxU32(&x1537, &x1538, x1536, x1496, x1493); const x1539: u32 = (@intCast(u32, x1538) + x1494); var x1540: u32 = undefined; var x1541: u1 = undefined; fiatP384AddcarryxU32(&x1540, &x1541, 0x0, x1468, x1515); var x1542: u32 = undefined; var x1543: u1 = undefined; fiatP384AddcarryxU32(&x1542, &x1543, x1541, x1470, x1517); var x1544: u32 = undefined; var x1545: u1 = undefined; fiatP384AddcarryxU32(&x1544, &x1545, x1543, x1472, x1519); var x1546: u32 = undefined; var x1547: u1 = undefined; fiatP384AddcarryxU32(&x1546, &x1547, x1545, x1474, x1521); var x1548: u32 = undefined; var x1549: u1 = undefined; fiatP384AddcarryxU32(&x1548, &x1549, x1547, x1476, x1523); var x1550: u32 = undefined; var x1551: u1 = undefined; fiatP384AddcarryxU32(&x1550, &x1551, x1549, x1478, x1525); var x1552: u32 = undefined; var x1553: u1 = undefined; fiatP384AddcarryxU32(&x1552, &x1553, x1551, x1480, x1527); var x1554: u32 = undefined; var x1555: u1 = undefined; fiatP384AddcarryxU32(&x1554, &x1555, x1553, x1482, x1529); var x1556: u32 = undefined; var x1557: u1 = undefined; fiatP384AddcarryxU32(&x1556, &x1557, x1555, x1484, x1531); var x1558: u32 = undefined; var x1559: u1 = undefined; fiatP384AddcarryxU32(&x1558, &x1559, x1557, x1486, x1533); var x1560: u32 = undefined; var x1561: u1 = undefined; fiatP384AddcarryxU32(&x1560, &x1561, x1559, x1488, x1535); var x1562: u32 = undefined; var x1563: u1 = undefined; fiatP384AddcarryxU32(&x1562, &x1563, x1561, x1490, x1537); var x1564: u32 = undefined; var x1565: u1 = undefined; fiatP384AddcarryxU32(&x1564, &x1565, x1563, x1492, x1539); var x1566: u32 = undefined; var x1567: u32 = undefined; fiatP384MulxU32(&x1566, &x1567, x1540, 0xffffffff); var x1568: u32 = undefined; var x1569: u32 = undefined; fiatP384MulxU32(&x1568, &x1569, x1540, 0xffffffff); var x1570: u32 = undefined; var x1571: u32 = undefined; fiatP384MulxU32(&x1570, &x1571, x1540, 0xffffffff); var x1572: u32 = undefined; var x1573: u32 = undefined; fiatP384MulxU32(&x1572, &x1573, x1540, 0xffffffff); var x1574: u32 = undefined; var x1575: u32 = undefined; fiatP384MulxU32(&x1574, &x1575, x1540, 0xffffffff); var x1576: u32 = undefined; var x1577: u32 = undefined; fiatP384MulxU32(&x1576, &x1577, x1540, 0xffffffff); var x1578: u32 = undefined; var x1579: u32 = undefined; fiatP384MulxU32(&x1578, &x1579, x1540, 0xffffffff); var x1580: u32 = undefined; var x1581: u32 = undefined; fiatP384MulxU32(&x1580, &x1581, x1540, 0xfffffffe); var x1582: u32 = undefined; var x1583: u32 = undefined; fiatP384MulxU32(&x1582, &x1583, x1540, 0xffffffff); var x1584: u32 = undefined; var x1585: u32 = undefined; fiatP384MulxU32(&x1584, &x1585, x1540, 0xffffffff); var x1586: u32 = undefined; var x1587: u1 = undefined; fiatP384AddcarryxU32(&x1586, &x1587, 0x0, x1583, x1580); var x1588: u32 = undefined; var x1589: u1 = undefined; fiatP384AddcarryxU32(&x1588, &x1589, x1587, x1581, x1578); var x1590: u32 = undefined; var x1591: u1 = undefined; fiatP384AddcarryxU32(&x1590, &x1591, x1589, x1579, x1576); var x1592: u32 = undefined; var x1593: u1 = undefined; fiatP384AddcarryxU32(&x1592, &x1593, x1591, x1577, x1574); var x1594: u32 = undefined; var x1595: u1 = undefined; fiatP384AddcarryxU32(&x1594, &x1595, x1593, x1575, x1572); var x1596: u32 = undefined; var x1597: u1 = undefined; fiatP384AddcarryxU32(&x1596, &x1597, x1595, x1573, x1570); var x1598: u32 = undefined; var x1599: u1 = undefined; fiatP384AddcarryxU32(&x1598, &x1599, x1597, x1571, x1568); var x1600: u32 = undefined; var x1601: u1 = undefined; fiatP384AddcarryxU32(&x1600, &x1601, x1599, x1569, x1566); const x1602: u32 = (@intCast(u32, x1601) + x1567); var x1603: u32 = undefined; var x1604: u1 = undefined; fiatP384AddcarryxU32(&x1603, &x1604, 0x0, x1540, x1584); var x1605: u32 = undefined; var x1606: u1 = undefined; fiatP384AddcarryxU32(&x1605, &x1606, x1604, x1542, x1585); var x1607: u32 = undefined; var x1608: u1 = undefined; fiatP384AddcarryxU32(&x1607, &x1608, x1606, x1544, @intCast(u32, 0x0)); var x1609: u32 = undefined; var x1610: u1 = undefined; fiatP384AddcarryxU32(&x1609, &x1610, x1608, x1546, x1582); var x1611: u32 = undefined; var x1612: u1 = undefined; fiatP384AddcarryxU32(&x1611, &x1612, x1610, x1548, x1586); var x1613: u32 = undefined; var x1614: u1 = undefined; fiatP384AddcarryxU32(&x1613, &x1614, x1612, x1550, x1588); var x1615: u32 = undefined; var x1616: u1 = undefined; fiatP384AddcarryxU32(&x1615, &x1616, x1614, x1552, x1590); var x1617: u32 = undefined; var x1618: u1 = undefined; fiatP384AddcarryxU32(&x1617, &x1618, x1616, x1554, x1592); var x1619: u32 = undefined; var x1620: u1 = undefined; fiatP384AddcarryxU32(&x1619, &x1620, x1618, x1556, x1594); var x1621: u32 = undefined; var x1622: u1 = undefined; fiatP384AddcarryxU32(&x1621, &x1622, x1620, x1558, x1596); var x1623: u32 = undefined; var x1624: u1 = undefined; fiatP384AddcarryxU32(&x1623, &x1624, x1622, x1560, x1598); var x1625: u32 = undefined; var x1626: u1 = undefined; fiatP384AddcarryxU32(&x1625, &x1626, x1624, x1562, x1600); var x1627: u32 = undefined; var x1628: u1 = undefined; fiatP384AddcarryxU32(&x1627, &x1628, x1626, x1564, x1602); const x1629: u32 = (@intCast(u32, x1628) + @intCast(u32, x1565)); var x1630: u32 = undefined; var x1631: u1 = undefined; fiatP384SubborrowxU32(&x1630, &x1631, 0x0, x1605, 0xffffffff); var x1632: u32 = undefined; var x1633: u1 = undefined; fiatP384SubborrowxU32(&x1632, &x1633, x1631, x1607, @intCast(u32, 0x0)); var x1634: u32 = undefined; var x1635: u1 = undefined; fiatP384SubborrowxU32(&x1634, &x1635, x1633, x1609, @intCast(u32, 0x0)); var x1636: u32 = undefined; var x1637: u1 = undefined; fiatP384SubborrowxU32(&x1636, &x1637, x1635, x1611, 0xffffffff); var x1638: u32 = undefined; var x1639: u1 = undefined; fiatP384SubborrowxU32(&x1638, &x1639, x1637, x1613, 0xfffffffe); var x1640: u32 = undefined; var x1641: u1 = undefined; fiatP384SubborrowxU32(&x1640, &x1641, x1639, x1615, 0xffffffff); var x1642: u32 = undefined; var x1643: u1 = undefined; fiatP384SubborrowxU32(&x1642, &x1643, x1641, x1617, 0xffffffff); var x1644: u32 = undefined; var x1645: u1 = undefined; fiatP384SubborrowxU32(&x1644, &x1645, x1643, x1619, 0xffffffff); var x1646: u32 = undefined; var x1647: u1 = undefined; fiatP384SubborrowxU32(&x1646, &x1647, x1645, x1621, 0xffffffff); var x1648: u32 = undefined; var x1649: u1 = undefined; fiatP384SubborrowxU32(&x1648, &x1649, x1647, x1623, 0xffffffff); var x1650: u32 = undefined; var x1651: u1 = undefined; fiatP384SubborrowxU32(&x1650, &x1651, x1649, x1625, 0xffffffff); var x1652: u32 = undefined; var x1653: u1 = undefined; fiatP384SubborrowxU32(&x1652, &x1653, x1651, x1627, 0xffffffff); var x1654: u32 = undefined; var x1655: u1 = undefined; fiatP384SubborrowxU32(&x1654, &x1655, x1653, x1629, @intCast(u32, 0x0)); var x1656: u32 = undefined; fiatP384CmovznzU32(&x1656, x1655, x1630, x1605); var x1657: u32 = undefined; fiatP384CmovznzU32(&x1657, x1655, x1632, x1607); var x1658: u32 = undefined; fiatP384CmovznzU32(&x1658, x1655, x1634, x1609); var x1659: u32 = undefined; fiatP384CmovznzU32(&x1659, x1655, x1636, x1611); var x1660: u32 = undefined; fiatP384CmovznzU32(&x1660, x1655, x1638, x1613); var x1661: u32 = undefined; fiatP384CmovznzU32(&x1661, x1655, x1640, x1615); var x1662: u32 = undefined; fiatP384CmovznzU32(&x1662, x1655, x1642, x1617); var x1663: u32 = undefined; fiatP384CmovznzU32(&x1663, x1655, x1644, x1619); var x1664: u32 = undefined; fiatP384CmovznzU32(&x1664, x1655, x1646, x1621); var x1665: u32 = undefined; fiatP384CmovznzU32(&x1665, x1655, x1648, x1623); var x1666: u32 = undefined; fiatP384CmovznzU32(&x1666, x1655, x1650, x1625); var x1667: u32 = undefined; fiatP384CmovznzU32(&x1667, x1655, x1652, x1627); out1[0] = x1656; out1[1] = x1657; out1[2] = x1658; out1[3] = x1659; out1[4] = x1660; out1[5] = x1661; out1[6] = x1662; out1[7] = x1663; out1[8] = x1664; out1[9] = x1665; out1[10] = x1666; out1[11] = x1667; } /// The function fiatP384Add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Add(out1: *[12]u32, arg1: [12]u32, arg2: [12]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatP384AddcarryxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatP384AddcarryxU32(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatP384AddcarryxU32(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatP384AddcarryxU32(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatP384AddcarryxU32(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatP384AddcarryxU32(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatP384AddcarryxU32(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatP384AddcarryxU32(&x15, &x16, x14, (arg1[7]), (arg2[7])); var x17: u32 = undefined; var x18: u1 = undefined; fiatP384AddcarryxU32(&x17, &x18, x16, (arg1[8]), (arg2[8])); var x19: u32 = undefined; var x20: u1 = undefined; fiatP384AddcarryxU32(&x19, &x20, x18, (arg1[9]), (arg2[9])); var x21: u32 = undefined; var x22: u1 = undefined; fiatP384AddcarryxU32(&x21, &x22, x20, (arg1[10]), (arg2[10])); var x23: u32 = undefined; var x24: u1 = undefined; fiatP384AddcarryxU32(&x23, &x24, x22, (arg1[11]), (arg2[11])); var x25: u32 = undefined; var x26: u1 = undefined; fiatP384SubborrowxU32(&x25, &x26, 0x0, x1, 0xffffffff); var x27: u32 = undefined; var x28: u1 = undefined; fiatP384SubborrowxU32(&x27, &x28, x26, x3, @intCast(u32, 0x0)); var x29: u32 = undefined; var x30: u1 = undefined; fiatP384SubborrowxU32(&x29, &x30, x28, x5, @intCast(u32, 0x0)); var x31: u32 = undefined; var x32: u1 = undefined; fiatP384SubborrowxU32(&x31, &x32, x30, x7, 0xffffffff); var x33: u32 = undefined; var x34: u1 = undefined; fiatP384SubborrowxU32(&x33, &x34, x32, x9, 0xfffffffe); var x35: u32 = undefined; var x36: u1 = undefined; fiatP384SubborrowxU32(&x35, &x36, x34, x11, 0xffffffff); var x37: u32 = undefined; var x38: u1 = undefined; fiatP384SubborrowxU32(&x37, &x38, x36, x13, 0xffffffff); var x39: u32 = undefined; var x40: u1 = undefined; fiatP384SubborrowxU32(&x39, &x40, x38, x15, 0xffffffff); var x41: u32 = undefined; var x42: u1 = undefined; fiatP384SubborrowxU32(&x41, &x42, x40, x17, 0xffffffff); var x43: u32 = undefined; var x44: u1 = undefined; fiatP384SubborrowxU32(&x43, &x44, x42, x19, 0xffffffff); var x45: u32 = undefined; var x46: u1 = undefined; fiatP384SubborrowxU32(&x45, &x46, x44, x21, 0xffffffff); var x47: u32 = undefined; var x48: u1 = undefined; fiatP384SubborrowxU32(&x47, &x48, x46, x23, 0xffffffff); var x49: u32 = undefined; var x50: u1 = undefined; fiatP384SubborrowxU32(&x49, &x50, x48, @intCast(u32, x24), @intCast(u32, 0x0)); var x51: u32 = undefined; fiatP384CmovznzU32(&x51, x50, x25, x1); var x52: u32 = undefined; fiatP384CmovznzU32(&x52, x50, x27, x3); var x53: u32 = undefined; fiatP384CmovznzU32(&x53, x50, x29, x5); var x54: u32 = undefined; fiatP384CmovznzU32(&x54, x50, x31, x7); var x55: u32 = undefined; fiatP384CmovznzU32(&x55, x50, x33, x9); var x56: u32 = undefined; fiatP384CmovznzU32(&x56, x50, x35, x11); var x57: u32 = undefined; fiatP384CmovznzU32(&x57, x50, x37, x13); var x58: u32 = undefined; fiatP384CmovznzU32(&x58, x50, x39, x15); var x59: u32 = undefined; fiatP384CmovznzU32(&x59, x50, x41, x17); var x60: u32 = undefined; fiatP384CmovznzU32(&x60, x50, x43, x19); var x61: u32 = undefined; fiatP384CmovznzU32(&x61, x50, x45, x21); var x62: u32 = undefined; fiatP384CmovznzU32(&x62, x50, x47, x23); out1[0] = x51; out1[1] = x52; out1[2] = x53; out1[3] = x54; out1[4] = x55; out1[5] = x56; out1[6] = x57; out1[7] = x58; out1[8] = x59; out1[9] = x60; out1[10] = x61; out1[11] = x62; } /// The function fiatP384Sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Sub(out1: *[12]u32, arg1: [12]u32, arg2: [12]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatP384SubborrowxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatP384SubborrowxU32(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatP384SubborrowxU32(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatP384SubborrowxU32(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatP384SubborrowxU32(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatP384SubborrowxU32(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatP384SubborrowxU32(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatP384SubborrowxU32(&x15, &x16, x14, (arg1[7]), (arg2[7])); var x17: u32 = undefined; var x18: u1 = undefined; fiatP384SubborrowxU32(&x17, &x18, x16, (arg1[8]), (arg2[8])); var x19: u32 = undefined; var x20: u1 = undefined; fiatP384SubborrowxU32(&x19, &x20, x18, (arg1[9]), (arg2[9])); var x21: u32 = undefined; var x22: u1 = undefined; fiatP384SubborrowxU32(&x21, &x22, x20, (arg1[10]), (arg2[10])); var x23: u32 = undefined; var x24: u1 = undefined; fiatP384SubborrowxU32(&x23, &x24, x22, (arg1[11]), (arg2[11])); var x25: u32 = undefined; fiatP384CmovznzU32(&x25, x24, @intCast(u32, 0x0), 0xffffffff); var x26: u32 = undefined; var x27: u1 = undefined; fiatP384AddcarryxU32(&x26, &x27, 0x0, x1, x25); var x28: u32 = undefined; var x29: u1 = undefined; fiatP384AddcarryxU32(&x28, &x29, x27, x3, @intCast(u32, 0x0)); var x30: u32 = undefined; var x31: u1 = undefined; fiatP384AddcarryxU32(&x30, &x31, x29, x5, @intCast(u32, 0x0)); var x32: u32 = undefined; var x33: u1 = undefined; fiatP384AddcarryxU32(&x32, &x33, x31, x7, x25); var x34: u32 = undefined; var x35: u1 = undefined; fiatP384AddcarryxU32(&x34, &x35, x33, x9, (x25 & 0xfffffffe)); var x36: u32 = undefined; var x37: u1 = undefined; fiatP384AddcarryxU32(&x36, &x37, x35, x11, x25); var x38: u32 = undefined; var x39: u1 = undefined; fiatP384AddcarryxU32(&x38, &x39, x37, x13, x25); var x40: u32 = undefined; var x41: u1 = undefined; fiatP384AddcarryxU32(&x40, &x41, x39, x15, x25); var x42: u32 = undefined; var x43: u1 = undefined; fiatP384AddcarryxU32(&x42, &x43, x41, x17, x25); var x44: u32 = undefined; var x45: u1 = undefined; fiatP384AddcarryxU32(&x44, &x45, x43, x19, x25); var x46: u32 = undefined; var x47: u1 = undefined; fiatP384AddcarryxU32(&x46, &x47, x45, x21, x25); var x48: u32 = undefined; var x49: u1 = undefined; fiatP384AddcarryxU32(&x48, &x49, x47, x23, x25); out1[0] = x26; out1[1] = x28; out1[2] = x30; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x38; out1[7] = x40; out1[8] = x42; out1[9] = x44; out1[10] = x46; out1[11] = x48; } /// The function fiatP384Opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Opp(out1: *[12]u32, arg1: [12]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatP384SubborrowxU32(&x1, &x2, 0x0, @intCast(u32, 0x0), (arg1[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatP384SubborrowxU32(&x3, &x4, x2, @intCast(u32, 0x0), (arg1[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatP384SubborrowxU32(&x5, &x6, x4, @intCast(u32, 0x0), (arg1[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatP384SubborrowxU32(&x7, &x8, x6, @intCast(u32, 0x0), (arg1[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatP384SubborrowxU32(&x9, &x10, x8, @intCast(u32, 0x0), (arg1[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatP384SubborrowxU32(&x11, &x12, x10, @intCast(u32, 0x0), (arg1[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatP384SubborrowxU32(&x13, &x14, x12, @intCast(u32, 0x0), (arg1[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatP384SubborrowxU32(&x15, &x16, x14, @intCast(u32, 0x0), (arg1[7])); var x17: u32 = undefined; var x18: u1 = undefined; fiatP384SubborrowxU32(&x17, &x18, x16, @intCast(u32, 0x0), (arg1[8])); var x19: u32 = undefined; var x20: u1 = undefined; fiatP384SubborrowxU32(&x19, &x20, x18, @intCast(u32, 0x0), (arg1[9])); var x21: u32 = undefined; var x22: u1 = undefined; fiatP384SubborrowxU32(&x21, &x22, x20, @intCast(u32, 0x0), (arg1[10])); var x23: u32 = undefined; var x24: u1 = undefined; fiatP384SubborrowxU32(&x23, &x24, x22, @intCast(u32, 0x0), (arg1[11])); var x25: u32 = undefined; fiatP384CmovznzU32(&x25, x24, @intCast(u32, 0x0), 0xffffffff); var x26: u32 = undefined; var x27: u1 = undefined; fiatP384AddcarryxU32(&x26, &x27, 0x0, x1, x25); var x28: u32 = undefined; var x29: u1 = undefined; fiatP384AddcarryxU32(&x28, &x29, x27, x3, @intCast(u32, 0x0)); var x30: u32 = undefined; var x31: u1 = undefined; fiatP384AddcarryxU32(&x30, &x31, x29, x5, @intCast(u32, 0x0)); var x32: u32 = undefined; var x33: u1 = undefined; fiatP384AddcarryxU32(&x32, &x33, x31, x7, x25); var x34: u32 = undefined; var x35: u1 = undefined; fiatP384AddcarryxU32(&x34, &x35, x33, x9, (x25 & 0xfffffffe)); var x36: u32 = undefined; var x37: u1 = undefined; fiatP384AddcarryxU32(&x36, &x37, x35, x11, x25); var x38: u32 = undefined; var x39: u1 = undefined; fiatP384AddcarryxU32(&x38, &x39, x37, x13, x25); var x40: u32 = undefined; var x41: u1 = undefined; fiatP384AddcarryxU32(&x40, &x41, x39, x15, x25); var x42: u32 = undefined; var x43: u1 = undefined; fiatP384AddcarryxU32(&x42, &x43, x41, x17, x25); var x44: u32 = undefined; var x45: u1 = undefined; fiatP384AddcarryxU32(&x44, &x45, x43, x19, x25); var x46: u32 = undefined; var x47: u1 = undefined; fiatP384AddcarryxU32(&x46, &x47, x45, x21, x25); var x48: u32 = undefined; var x49: u1 = undefined; fiatP384AddcarryxU32(&x48, &x49, x47, x23, x25); out1[0] = x26; out1[1] = x28; out1[2] = x30; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x38; out1[7] = x40; out1[8] = x42; out1[9] = x44; out1[10] = x46; out1[11] = x48; } /// The function fiatP384FromMontgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^12) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384FromMontgomery(out1: *[12]u32, arg1: [12]u32) void { const x1: u32 = (arg1[0]); var x2: u32 = undefined; var x3: u32 = undefined; fiatP384MulxU32(&x2, &x3, x1, 0xffffffff); var x4: u32 = undefined; var x5: u32 = undefined; fiatP384MulxU32(&x4, &x5, x1, 0xffffffff); var x6: u32 = undefined; var x7: u32 = undefined; fiatP384MulxU32(&x6, &x7, x1, 0xffffffff); var x8: u32 = undefined; var x9: u32 = undefined; fiatP384MulxU32(&x8, &x9, x1, 0xffffffff); var x10: u32 = undefined; var x11: u32 = undefined; fiatP384MulxU32(&x10, &x11, x1, 0xffffffff); var x12: u32 = undefined; var x13: u32 = undefined; fiatP384MulxU32(&x12, &x13, x1, 0xffffffff); var x14: u32 = undefined; var x15: u32 = undefined; fiatP384MulxU32(&x14, &x15, x1, 0xffffffff); var x16: u32 = undefined; var x17: u32 = undefined; fiatP384MulxU32(&x16, &x17, x1, 0xfffffffe); var x18: u32 = undefined; var x19: u32 = undefined; fiatP384MulxU32(&x18, &x19, x1, 0xffffffff); var x20: u32 = undefined; var x21: u32 = undefined; fiatP384MulxU32(&x20, &x21, x1, 0xffffffff); var x22: u32 = undefined; var x23: u1 = undefined; fiatP384AddcarryxU32(&x22, &x23, 0x0, x19, x16); var x24: u32 = undefined; var x25: u1 = undefined; fiatP384AddcarryxU32(&x24, &x25, x23, x17, x14); var x26: u32 = undefined; var x27: u1 = undefined; fiatP384AddcarryxU32(&x26, &x27, x25, x15, x12); var x28: u32 = undefined; var x29: u1 = undefined; fiatP384AddcarryxU32(&x28, &x29, x27, x13, x10); var x30: u32 = undefined; var x31: u1 = undefined; fiatP384AddcarryxU32(&x30, &x31, x29, x11, x8); var x32: u32 = undefined; var x33: u1 = undefined; fiatP384AddcarryxU32(&x32, &x33, x31, x9, x6); var x34: u32 = undefined; var x35: u1 = undefined; fiatP384AddcarryxU32(&x34, &x35, x33, x7, x4); var x36: u32 = undefined; var x37: u1 = undefined; fiatP384AddcarryxU32(&x36, &x37, x35, x5, x2); var x38: u32 = undefined; var x39: u1 = undefined; fiatP384AddcarryxU32(&x38, &x39, 0x0, x1, x20); var x40: u32 = undefined; var x41: u1 = undefined; fiatP384AddcarryxU32(&x40, &x41, 0x0, (@intCast(u32, x39) + x21), (arg1[1])); var x42: u32 = undefined; var x43: u32 = undefined; fiatP384MulxU32(&x42, &x43, x40, 0xffffffff); var x44: u32 = undefined; var x45: u32 = undefined; fiatP384MulxU32(&x44, &x45, x40, 0xffffffff); var x46: u32 = undefined; var x47: u32 = undefined; fiatP384MulxU32(&x46, &x47, x40, 0xffffffff); var x48: u32 = undefined; var x49: u32 = undefined; fiatP384MulxU32(&x48, &x49, x40, 0xffffffff); var x50: u32 = undefined; var x51: u32 = undefined; fiatP384MulxU32(&x50, &x51, x40, 0xffffffff); var x52: u32 = undefined; var x53: u32 = undefined; fiatP384MulxU32(&x52, &x53, x40, 0xffffffff); var x54: u32 = undefined; var x55: u32 = undefined; fiatP384MulxU32(&x54, &x55, x40, 0xffffffff); var x56: u32 = undefined; var x57: u32 = undefined; fiatP384MulxU32(&x56, &x57, x40, 0xfffffffe); var x58: u32 = undefined; var x59: u32 = undefined; fiatP384MulxU32(&x58, &x59, x40, 0xffffffff); var x60: u32 = undefined; var x61: u32 = undefined; fiatP384MulxU32(&x60, &x61, x40, 0xffffffff); var x62: u32 = undefined; var x63: u1 = undefined; fiatP384AddcarryxU32(&x62, &x63, 0x0, x59, x56); var x64: u32 = undefined; var x65: u1 = undefined; fiatP384AddcarryxU32(&x64, &x65, x63, x57, x54); var x66: u32 = undefined; var x67: u1 = undefined; fiatP384AddcarryxU32(&x66, &x67, x65, x55, x52); var x68: u32 = undefined; var x69: u1 = undefined; fiatP384AddcarryxU32(&x68, &x69, x67, x53, x50); var x70: u32 = undefined; var x71: u1 = undefined; fiatP384AddcarryxU32(&x70, &x71, x69, x51, x48); var x72: u32 = undefined; var x73: u1 = undefined; fiatP384AddcarryxU32(&x72, &x73, x71, x49, x46); var x74: u32 = undefined; var x75: u1 = undefined; fiatP384AddcarryxU32(&x74, &x75, x73, x47, x44); var x76: u32 = undefined; var x77: u1 = undefined; fiatP384AddcarryxU32(&x76, &x77, x75, x45, x42); var x78: u32 = undefined; var x79: u1 = undefined; fiatP384AddcarryxU32(&x78, &x79, 0x0, x40, x60); var x80: u32 = undefined; var x81: u1 = undefined; fiatP384AddcarryxU32(&x80, &x81, x79, @intCast(u32, x41), x61); var x82: u32 = undefined; var x83: u1 = undefined; fiatP384AddcarryxU32(&x82, &x83, x81, x18, @intCast(u32, 0x0)); var x84: u32 = undefined; var x85: u1 = undefined; fiatP384AddcarryxU32(&x84, &x85, x83, x22, x58); var x86: u32 = undefined; var x87: u1 = undefined; fiatP384AddcarryxU32(&x86, &x87, x85, x24, x62); var x88: u32 = undefined; var x89: u1 = undefined; fiatP384AddcarryxU32(&x88, &x89, x87, x26, x64); var x90: u32 = undefined; var x91: u1 = undefined; fiatP384AddcarryxU32(&x90, &x91, x89, x28, x66); var x92: u32 = undefined; var x93: u1 = undefined; fiatP384AddcarryxU32(&x92, &x93, x91, x30, x68); var x94: u32 = undefined; var x95: u1 = undefined; fiatP384AddcarryxU32(&x94, &x95, x93, x32, x70); var x96: u32 = undefined; var x97: u1 = undefined; fiatP384AddcarryxU32(&x96, &x97, x95, x34, x72); var x98: u32 = undefined; var x99: u1 = undefined; fiatP384AddcarryxU32(&x98, &x99, x97, x36, x74); var x100: u32 = undefined; var x101: u1 = undefined; fiatP384AddcarryxU32(&x100, &x101, x99, (@intCast(u32, x37) + x3), x76); var x102: u32 = undefined; var x103: u1 = undefined; fiatP384AddcarryxU32(&x102, &x103, x101, @intCast(u32, 0x0), (@intCast(u32, x77) + x43)); var x104: u32 = undefined; var x105: u1 = undefined; fiatP384AddcarryxU32(&x104, &x105, 0x0, x80, (arg1[2])); var x106: u32 = undefined; var x107: u1 = undefined; fiatP384AddcarryxU32(&x106, &x107, x105, x82, @intCast(u32, 0x0)); var x108: u32 = undefined; var x109: u1 = undefined; fiatP384AddcarryxU32(&x108, &x109, x107, x84, @intCast(u32, 0x0)); var x110: u32 = undefined; var x111: u1 = undefined; fiatP384AddcarryxU32(&x110, &x111, x109, x86, @intCast(u32, 0x0)); var x112: u32 = undefined; var x113: u1 = undefined; fiatP384AddcarryxU32(&x112, &x113, x111, x88, @intCast(u32, 0x0)); var x114: u32 = undefined; var x115: u1 = undefined; fiatP384AddcarryxU32(&x114, &x115, x113, x90, @intCast(u32, 0x0)); var x116: u32 = undefined; var x117: u1 = undefined; fiatP384AddcarryxU32(&x116, &x117, x115, x92, @intCast(u32, 0x0)); var x118: u32 = undefined; var x119: u1 = undefined; fiatP384AddcarryxU32(&x118, &x119, x117, x94, @intCast(u32, 0x0)); var x120: u32 = undefined; var x121: u1 = undefined; fiatP384AddcarryxU32(&x120, &x121, x119, x96, @intCast(u32, 0x0)); var x122: u32 = undefined; var x123: u1 = undefined; fiatP384AddcarryxU32(&x122, &x123, x121, x98, @intCast(u32, 0x0)); var x124: u32 = undefined; var x125: u1 = undefined; fiatP384AddcarryxU32(&x124, &x125, x123, x100, @intCast(u32, 0x0)); var x126: u32 = undefined; var x127: u1 = undefined; fiatP384AddcarryxU32(&x126, &x127, x125, x102, @intCast(u32, 0x0)); var x128: u32 = undefined; var x129: u32 = undefined; fiatP384MulxU32(&x128, &x129, x104, 0xffffffff); var x130: u32 = undefined; var x131: u32 = undefined; fiatP384MulxU32(&x130, &x131, x104, 0xffffffff); var x132: u32 = undefined; var x133: u32 = undefined; fiatP384MulxU32(&x132, &x133, x104, 0xffffffff); var x134: u32 = undefined; var x135: u32 = undefined; fiatP384MulxU32(&x134, &x135, x104, 0xffffffff); var x136: u32 = undefined; var x137: u32 = undefined; fiatP384MulxU32(&x136, &x137, x104, 0xffffffff); var x138: u32 = undefined; var x139: u32 = undefined; fiatP384MulxU32(&x138, &x139, x104, 0xffffffff); var x140: u32 = undefined; var x141: u32 = undefined; fiatP384MulxU32(&x140, &x141, x104, 0xffffffff); var x142: u32 = undefined; var x143: u32 = undefined; fiatP384MulxU32(&x142, &x143, x104, 0xfffffffe); var x144: u32 = undefined; var x145: u32 = undefined; fiatP384MulxU32(&x144, &x145, x104, 0xffffffff); var x146: u32 = undefined; var x147: u32 = undefined; fiatP384MulxU32(&x146, &x147, x104, 0xffffffff); var x148: u32 = undefined; var x149: u1 = undefined; fiatP384AddcarryxU32(&x148, &x149, 0x0, x145, x142); var x150: u32 = undefined; var x151: u1 = undefined; fiatP384AddcarryxU32(&x150, &x151, x149, x143, x140); var x152: u32 = undefined; var x153: u1 = undefined; fiatP384AddcarryxU32(&x152, &x153, x151, x141, x138); var x154: u32 = undefined; var x155: u1 = undefined; fiatP384AddcarryxU32(&x154, &x155, x153, x139, x136); var x156: u32 = undefined; var x157: u1 = undefined; fiatP384AddcarryxU32(&x156, &x157, x155, x137, x134); var x158: u32 = undefined; var x159: u1 = undefined; fiatP384AddcarryxU32(&x158, &x159, x157, x135, x132); var x160: u32 = undefined; var x161: u1 = undefined; fiatP384AddcarryxU32(&x160, &x161, x159, x133, x130); var x162: u32 = undefined; var x163: u1 = undefined; fiatP384AddcarryxU32(&x162, &x163, x161, x131, x128); var x164: u32 = undefined; var x165: u1 = undefined; fiatP384AddcarryxU32(&x164, &x165, 0x0, x104, x146); var x166: u32 = undefined; var x167: u1 = undefined; fiatP384AddcarryxU32(&x166, &x167, x165, x106, x147); var x168: u32 = undefined; var x169: u1 = undefined; fiatP384AddcarryxU32(&x168, &x169, x167, x108, @intCast(u32, 0x0)); var x170: u32 = undefined; var x171: u1 = undefined; fiatP384AddcarryxU32(&x170, &x171, x169, x110, x144); var x172: u32 = undefined; var x173: u1 = undefined; fiatP384AddcarryxU32(&x172, &x173, x171, x112, x148); var x174: u32 = undefined; var x175: u1 = undefined; fiatP384AddcarryxU32(&x174, &x175, x173, x114, x150); var x176: u32 = undefined; var x177: u1 = undefined; fiatP384AddcarryxU32(&x176, &x177, x175, x116, x152); var x178: u32 = undefined; var x179: u1 = undefined; fiatP384AddcarryxU32(&x178, &x179, x177, x118, x154); var x180: u32 = undefined; var x181: u1 = undefined; fiatP384AddcarryxU32(&x180, &x181, x179, x120, x156); var x182: u32 = undefined; var x183: u1 = undefined; fiatP384AddcarryxU32(&x182, &x183, x181, x122, x158); var x184: u32 = undefined; var x185: u1 = undefined; fiatP384AddcarryxU32(&x184, &x185, x183, x124, x160); var x186: u32 = undefined; var x187: u1 = undefined; fiatP384AddcarryxU32(&x186, &x187, x185, x126, x162); var x188: u32 = undefined; var x189: u1 = undefined; fiatP384AddcarryxU32(&x188, &x189, x187, (@intCast(u32, x127) + @intCast(u32, x103)), (@intCast(u32, x163) + x129)); var x190: u32 = undefined; var x191: u1 = undefined; fiatP384AddcarryxU32(&x190, &x191, 0x0, x166, (arg1[3])); var x192: u32 = undefined; var x193: u1 = undefined; fiatP384AddcarryxU32(&x192, &x193, x191, x168, @intCast(u32, 0x0)); var x194: u32 = undefined; var x195: u1 = undefined; fiatP384AddcarryxU32(&x194, &x195, x193, x170, @intCast(u32, 0x0)); var x196: u32 = undefined; var x197: u1 = undefined; fiatP384AddcarryxU32(&x196, &x197, x195, x172, @intCast(u32, 0x0)); var x198: u32 = undefined; var x199: u1 = undefined; fiatP384AddcarryxU32(&x198, &x199, x197, x174, @intCast(u32, 0x0)); var x200: u32 = undefined; var x201: u1 = undefined; fiatP384AddcarryxU32(&x200, &x201, x199, x176, @intCast(u32, 0x0)); var x202: u32 = undefined; var x203: u1 = undefined; fiatP384AddcarryxU32(&x202, &x203, x201, x178, @intCast(u32, 0x0)); var x204: u32 = undefined; var x205: u1 = undefined; fiatP384AddcarryxU32(&x204, &x205, x203, x180, @intCast(u32, 0x0)); var x206: u32 = undefined; var x207: u1 = undefined; fiatP384AddcarryxU32(&x206, &x207, x205, x182, @intCast(u32, 0x0)); var x208: u32 = undefined; var x209: u1 = undefined; fiatP384AddcarryxU32(&x208, &x209, x207, x184, @intCast(u32, 0x0)); var x210: u32 = undefined; var x211: u1 = undefined; fiatP384AddcarryxU32(&x210, &x211, x209, x186, @intCast(u32, 0x0)); var x212: u32 = undefined; var x213: u1 = undefined; fiatP384AddcarryxU32(&x212, &x213, x211, x188, @intCast(u32, 0x0)); var x214: u32 = undefined; var x215: u32 = undefined; fiatP384MulxU32(&x214, &x215, x190, 0xffffffff); var x216: u32 = undefined; var x217: u32 = undefined; fiatP384MulxU32(&x216, &x217, x190, 0xffffffff); var x218: u32 = undefined; var x219: u32 = undefined; fiatP384MulxU32(&x218, &x219, x190, 0xffffffff); var x220: u32 = undefined; var x221: u32 = undefined; fiatP384MulxU32(&x220, &x221, x190, 0xffffffff); var x222: u32 = undefined; var x223: u32 = undefined; fiatP384MulxU32(&x222, &x223, x190, 0xffffffff); var x224: u32 = undefined; var x225: u32 = undefined; fiatP384MulxU32(&x224, &x225, x190, 0xffffffff); var x226: u32 = undefined; var x227: u32 = undefined; fiatP384MulxU32(&x226, &x227, x190, 0xffffffff); var x228: u32 = undefined; var x229: u32 = undefined; fiatP384MulxU32(&x228, &x229, x190, 0xfffffffe); var x230: u32 = undefined; var x231: u32 = undefined; fiatP384MulxU32(&x230, &x231, x190, 0xffffffff); var x232: u32 = undefined; var x233: u32 = undefined; fiatP384MulxU32(&x232, &x233, x190, 0xffffffff); var x234: u32 = undefined; var x235: u1 = undefined; fiatP384AddcarryxU32(&x234, &x235, 0x0, x231, x228); var x236: u32 = undefined; var x237: u1 = undefined; fiatP384AddcarryxU32(&x236, &x237, x235, x229, x226); var x238: u32 = undefined; var x239: u1 = undefined; fiatP384AddcarryxU32(&x238, &x239, x237, x227, x224); var x240: u32 = undefined; var x241: u1 = undefined; fiatP384AddcarryxU32(&x240, &x241, x239, x225, x222); var x242: u32 = undefined; var x243: u1 = undefined; fiatP384AddcarryxU32(&x242, &x243, x241, x223, x220); var x244: u32 = undefined; var x245: u1 = undefined; fiatP384AddcarryxU32(&x244, &x245, x243, x221, x218); var x246: u32 = undefined; var x247: u1 = undefined; fiatP384AddcarryxU32(&x246, &x247, x245, x219, x216); var x248: u32 = undefined; var x249: u1 = undefined; fiatP384AddcarryxU32(&x248, &x249, x247, x217, x214); var x250: u32 = undefined; var x251: u1 = undefined; fiatP384AddcarryxU32(&x250, &x251, 0x0, x190, x232); var x252: u32 = undefined; var x253: u1 = undefined; fiatP384AddcarryxU32(&x252, &x253, x251, x192, x233); var x254: u32 = undefined; var x255: u1 = undefined; fiatP384AddcarryxU32(&x254, &x255, x253, x194, @intCast(u32, 0x0)); var x256: u32 = undefined; var x257: u1 = undefined; fiatP384AddcarryxU32(&x256, &x257, x255, x196, x230); var x258: u32 = undefined; var x259: u1 = undefined; fiatP384AddcarryxU32(&x258, &x259, x257, x198, x234); var x260: u32 = undefined; var x261: u1 = undefined; fiatP384AddcarryxU32(&x260, &x261, x259, x200, x236); var x262: u32 = undefined; var x263: u1 = undefined; fiatP384AddcarryxU32(&x262, &x263, x261, x202, x238); var x264: u32 = undefined; var x265: u1 = undefined; fiatP384AddcarryxU32(&x264, &x265, x263, x204, x240); var x266: u32 = undefined; var x267: u1 = undefined; fiatP384AddcarryxU32(&x266, &x267, x265, x206, x242); var x268: u32 = undefined; var x269: u1 = undefined; fiatP384AddcarryxU32(&x268, &x269, x267, x208, x244); var x270: u32 = undefined; var x271: u1 = undefined; fiatP384AddcarryxU32(&x270, &x271, x269, x210, x246); var x272: u32 = undefined; var x273: u1 = undefined; fiatP384AddcarryxU32(&x272, &x273, x271, x212, x248); var x274: u32 = undefined; var x275: u1 = undefined; fiatP384AddcarryxU32(&x274, &x275, x273, (@intCast(u32, x213) + @intCast(u32, x189)), (@intCast(u32, x249) + x215)); var x276: u32 = undefined; var x277: u1 = undefined; fiatP384AddcarryxU32(&x276, &x277, 0x0, x252, (arg1[4])); var x278: u32 = undefined; var x279: u1 = undefined; fiatP384AddcarryxU32(&x278, &x279, x277, x254, @intCast(u32, 0x0)); var x280: u32 = undefined; var x281: u1 = undefined; fiatP384AddcarryxU32(&x280, &x281, x279, x256, @intCast(u32, 0x0)); var x282: u32 = undefined; var x283: u1 = undefined; fiatP384AddcarryxU32(&x282, &x283, x281, x258, @intCast(u32, 0x0)); var x284: u32 = undefined; var x285: u1 = undefined; fiatP384AddcarryxU32(&x284, &x285, x283, x260, @intCast(u32, 0x0)); var x286: u32 = undefined; var x287: u1 = undefined; fiatP384AddcarryxU32(&x286, &x287, x285, x262, @intCast(u32, 0x0)); var x288: u32 = undefined; var x289: u1 = undefined; fiatP384AddcarryxU32(&x288, &x289, x287, x264, @intCast(u32, 0x0)); var x290: u32 = undefined; var x291: u1 = undefined; fiatP384AddcarryxU32(&x290, &x291, x289, x266, @intCast(u32, 0x0)); var x292: u32 = undefined; var x293: u1 = undefined; fiatP384AddcarryxU32(&x292, &x293, x291, x268, @intCast(u32, 0x0)); var x294: u32 = undefined; var x295: u1 = undefined; fiatP384AddcarryxU32(&x294, &x295, x293, x270, @intCast(u32, 0x0)); var x296: u32 = undefined; var x297: u1 = undefined; fiatP384AddcarryxU32(&x296, &x297, x295, x272, @intCast(u32, 0x0)); var x298: u32 = undefined; var x299: u1 = undefined; fiatP384AddcarryxU32(&x298, &x299, x297, x274, @intCast(u32, 0x0)); var x300: u32 = undefined; var x301: u32 = undefined; fiatP384MulxU32(&x300, &x301, x276, 0xffffffff); var x302: u32 = undefined; var x303: u32 = undefined; fiatP384MulxU32(&x302, &x303, x276, 0xffffffff); var x304: u32 = undefined; var x305: u32 = undefined; fiatP384MulxU32(&x304, &x305, x276, 0xffffffff); var x306: u32 = undefined; var x307: u32 = undefined; fiatP384MulxU32(&x306, &x307, x276, 0xffffffff); var x308: u32 = undefined; var x309: u32 = undefined; fiatP384MulxU32(&x308, &x309, x276, 0xffffffff); var x310: u32 = undefined; var x311: u32 = undefined; fiatP384MulxU32(&x310, &x311, x276, 0xffffffff); var x312: u32 = undefined; var x313: u32 = undefined; fiatP384MulxU32(&x312, &x313, x276, 0xffffffff); var x314: u32 = undefined; var x315: u32 = undefined; fiatP384MulxU32(&x314, &x315, x276, 0xfffffffe); var x316: u32 = undefined; var x317: u32 = undefined; fiatP384MulxU32(&x316, &x317, x276, 0xffffffff); var x318: u32 = undefined; var x319: u32 = undefined; fiatP384MulxU32(&x318, &x319, x276, 0xffffffff); var x320: u32 = undefined; var x321: u1 = undefined; fiatP384AddcarryxU32(&x320, &x321, 0x0, x317, x314); var x322: u32 = undefined; var x323: u1 = undefined; fiatP384AddcarryxU32(&x322, &x323, x321, x315, x312); var x324: u32 = undefined; var x325: u1 = undefined; fiatP384AddcarryxU32(&x324, &x325, x323, x313, x310); var x326: u32 = undefined; var x327: u1 = undefined; fiatP384AddcarryxU32(&x326, &x327, x325, x311, x308); var x328: u32 = undefined; var x329: u1 = undefined; fiatP384AddcarryxU32(&x328, &x329, x327, x309, x306); var x330: u32 = undefined; var x331: u1 = undefined; fiatP384AddcarryxU32(&x330, &x331, x329, x307, x304); var x332: u32 = undefined; var x333: u1 = undefined; fiatP384AddcarryxU32(&x332, &x333, x331, x305, x302); var x334: u32 = undefined; var x335: u1 = undefined; fiatP384AddcarryxU32(&x334, &x335, x333, x303, x300); var x336: u32 = undefined; var x337: u1 = undefined; fiatP384AddcarryxU32(&x336, &x337, 0x0, x276, x318); var x338: u32 = undefined; var x339: u1 = undefined; fiatP384AddcarryxU32(&x338, &x339, x337, x278, x319); var x340: u32 = undefined; var x341: u1 = undefined; fiatP384AddcarryxU32(&x340, &x341, x339, x280, @intCast(u32, 0x0)); var x342: u32 = undefined; var x343: u1 = undefined; fiatP384AddcarryxU32(&x342, &x343, x341, x282, x316); var x344: u32 = undefined; var x345: u1 = undefined; fiatP384AddcarryxU32(&x344, &x345, x343, x284, x320); var x346: u32 = undefined; var x347: u1 = undefined; fiatP384AddcarryxU32(&x346, &x347, x345, x286, x322); var x348: u32 = undefined; var x349: u1 = undefined; fiatP384AddcarryxU32(&x348, &x349, x347, x288, x324); var x350: u32 = undefined; var x351: u1 = undefined; fiatP384AddcarryxU32(&x350, &x351, x349, x290, x326); var x352: u32 = undefined; var x353: u1 = undefined; fiatP384AddcarryxU32(&x352, &x353, x351, x292, x328); var x354: u32 = undefined; var x355: u1 = undefined; fiatP384AddcarryxU32(&x354, &x355, x353, x294, x330); var x356: u32 = undefined; var x357: u1 = undefined; fiatP384AddcarryxU32(&x356, &x357, x355, x296, x332); var x358: u32 = undefined; var x359: u1 = undefined; fiatP384AddcarryxU32(&x358, &x359, x357, x298, x334); var x360: u32 = undefined; var x361: u1 = undefined; fiatP384AddcarryxU32(&x360, &x361, x359, (@intCast(u32, x299) + @intCast(u32, x275)), (@intCast(u32, x335) + x301)); var x362: u32 = undefined; var x363: u1 = undefined; fiatP384AddcarryxU32(&x362, &x363, 0x0, x338, (arg1[5])); var x364: u32 = undefined; var x365: u1 = undefined; fiatP384AddcarryxU32(&x364, &x365, x363, x340, @intCast(u32, 0x0)); var x366: u32 = undefined; var x367: u1 = undefined; fiatP384AddcarryxU32(&x366, &x367, x365, x342, @intCast(u32, 0x0)); var x368: u32 = undefined; var x369: u1 = undefined; fiatP384AddcarryxU32(&x368, &x369, x367, x344, @intCast(u32, 0x0)); var x370: u32 = undefined; var x371: u1 = undefined; fiatP384AddcarryxU32(&x370, &x371, x369, x346, @intCast(u32, 0x0)); var x372: u32 = undefined; var x373: u1 = undefined; fiatP384AddcarryxU32(&x372, &x373, x371, x348, @intCast(u32, 0x0)); var x374: u32 = undefined; var x375: u1 = undefined; fiatP384AddcarryxU32(&x374, &x375, x373, x350, @intCast(u32, 0x0)); var x376: u32 = undefined; var x377: u1 = undefined; fiatP384AddcarryxU32(&x376, &x377, x375, x352, @intCast(u32, 0x0)); var x378: u32 = undefined; var x379: u1 = undefined; fiatP384AddcarryxU32(&x378, &x379, x377, x354, @intCast(u32, 0x0)); var x380: u32 = undefined; var x381: u1 = undefined; fiatP384AddcarryxU32(&x380, &x381, x379, x356, @intCast(u32, 0x0)); var x382: u32 = undefined; var x383: u1 = undefined; fiatP384AddcarryxU32(&x382, &x383, x381, x358, @intCast(u32, 0x0)); var x384: u32 = undefined; var x385: u1 = undefined; fiatP384AddcarryxU32(&x384, &x385, x383, x360, @intCast(u32, 0x0)); var x386: u32 = undefined; var x387: u32 = undefined; fiatP384MulxU32(&x386, &x387, x362, 0xffffffff); var x388: u32 = undefined; var x389: u32 = undefined; fiatP384MulxU32(&x388, &x389, x362, 0xffffffff); var x390: u32 = undefined; var x391: u32 = undefined; fiatP384MulxU32(&x390, &x391, x362, 0xffffffff); var x392: u32 = undefined; var x393: u32 = undefined; fiatP384MulxU32(&x392, &x393, x362, 0xffffffff); var x394: u32 = undefined; var x395: u32 = undefined; fiatP384MulxU32(&x394, &x395, x362, 0xffffffff); var x396: u32 = undefined; var x397: u32 = undefined; fiatP384MulxU32(&x396, &x397, x362, 0xffffffff); var x398: u32 = undefined; var x399: u32 = undefined; fiatP384MulxU32(&x398, &x399, x362, 0xffffffff); var x400: u32 = undefined; var x401: u32 = undefined; fiatP384MulxU32(&x400, &x401, x362, 0xfffffffe); var x402: u32 = undefined; var x403: u32 = undefined; fiatP384MulxU32(&x402, &x403, x362, 0xffffffff); var x404: u32 = undefined; var x405: u32 = undefined; fiatP384MulxU32(&x404, &x405, x362, 0xffffffff); var x406: u32 = undefined; var x407: u1 = undefined; fiatP384AddcarryxU32(&x406, &x407, 0x0, x403, x400); var x408: u32 = undefined; var x409: u1 = undefined; fiatP384AddcarryxU32(&x408, &x409, x407, x401, x398); var x410: u32 = undefined; var x411: u1 = undefined; fiatP384AddcarryxU32(&x410, &x411, x409, x399, x396); var x412: u32 = undefined; var x413: u1 = undefined; fiatP384AddcarryxU32(&x412, &x413, x411, x397, x394); var x414: u32 = undefined; var x415: u1 = undefined; fiatP384AddcarryxU32(&x414, &x415, x413, x395, x392); var x416: u32 = undefined; var x417: u1 = undefined; fiatP384AddcarryxU32(&x416, &x417, x415, x393, x390); var x418: u32 = undefined; var x419: u1 = undefined; fiatP384AddcarryxU32(&x418, &x419, x417, x391, x388); var x420: u32 = undefined; var x421: u1 = undefined; fiatP384AddcarryxU32(&x420, &x421, x419, x389, x386); var x422: u32 = undefined; var x423: u1 = undefined; fiatP384AddcarryxU32(&x422, &x423, 0x0, x362, x404); var x424: u32 = undefined; var x425: u1 = undefined; fiatP384AddcarryxU32(&x424, &x425, x423, x364, x405); var x426: u32 = undefined; var x427: u1 = undefined; fiatP384AddcarryxU32(&x426, &x427, x425, x366, @intCast(u32, 0x0)); var x428: u32 = undefined; var x429: u1 = undefined; fiatP384AddcarryxU32(&x428, &x429, x427, x368, x402); var x430: u32 = undefined; var x431: u1 = undefined; fiatP384AddcarryxU32(&x430, &x431, x429, x370, x406); var x432: u32 = undefined; var x433: u1 = undefined; fiatP384AddcarryxU32(&x432, &x433, x431, x372, x408); var x434: u32 = undefined; var x435: u1 = undefined; fiatP384AddcarryxU32(&x434, &x435, x433, x374, x410); var x436: u32 = undefined; var x437: u1 = undefined; fiatP384AddcarryxU32(&x436, &x437, x435, x376, x412); var x438: u32 = undefined; var x439: u1 = undefined; fiatP384AddcarryxU32(&x438, &x439, x437, x378, x414); var x440: u32 = undefined; var x441: u1 = undefined; fiatP384AddcarryxU32(&x440, &x441, x439, x380, x416); var x442: u32 = undefined; var x443: u1 = undefined; fiatP384AddcarryxU32(&x442, &x443, x441, x382, x418); var x444: u32 = undefined; var x445: u1 = undefined; fiatP384AddcarryxU32(&x444, &x445, x443, x384, x420); var x446: u32 = undefined; var x447: u1 = undefined; fiatP384AddcarryxU32(&x446, &x447, x445, (@intCast(u32, x385) + @intCast(u32, x361)), (@intCast(u32, x421) + x387)); var x448: u32 = undefined; var x449: u1 = undefined; fiatP384AddcarryxU32(&x448, &x449, 0x0, x424, (arg1[6])); var x450: u32 = undefined; var x451: u1 = undefined; fiatP384AddcarryxU32(&x450, &x451, x449, x426, @intCast(u32, 0x0)); var x452: u32 = undefined; var x453: u1 = undefined; fiatP384AddcarryxU32(&x452, &x453, x451, x428, @intCast(u32, 0x0)); var x454: u32 = undefined; var x455: u1 = undefined; fiatP384AddcarryxU32(&x454, &x455, x453, x430, @intCast(u32, 0x0)); var x456: u32 = undefined; var x457: u1 = undefined; fiatP384AddcarryxU32(&x456, &x457, x455, x432, @intCast(u32, 0x0)); var x458: u32 = undefined; var x459: u1 = undefined; fiatP384AddcarryxU32(&x458, &x459, x457, x434, @intCast(u32, 0x0)); var x460: u32 = undefined; var x461: u1 = undefined; fiatP384AddcarryxU32(&x460, &x461, x459, x436, @intCast(u32, 0x0)); var x462: u32 = undefined; var x463: u1 = undefined; fiatP384AddcarryxU32(&x462, &x463, x461, x438, @intCast(u32, 0x0)); var x464: u32 = undefined; var x465: u1 = undefined; fiatP384AddcarryxU32(&x464, &x465, x463, x440, @intCast(u32, 0x0)); var x466: u32 = undefined; var x467: u1 = undefined; fiatP384AddcarryxU32(&x466, &x467, x465, x442, @intCast(u32, 0x0)); var x468: u32 = undefined; var x469: u1 = undefined; fiatP384AddcarryxU32(&x468, &x469, x467, x444, @intCast(u32, 0x0)); var x470: u32 = undefined; var x471: u1 = undefined; fiatP384AddcarryxU32(&x470, &x471, x469, x446, @intCast(u32, 0x0)); var x472: u32 = undefined; var x473: u32 = undefined; fiatP384MulxU32(&x472, &x473, x448, 0xffffffff); var x474: u32 = undefined; var x475: u32 = undefined; fiatP384MulxU32(&x474, &x475, x448, 0xffffffff); var x476: u32 = undefined; var x477: u32 = undefined; fiatP384MulxU32(&x476, &x477, x448, 0xffffffff); var x478: u32 = undefined; var x479: u32 = undefined; fiatP384MulxU32(&x478, &x479, x448, 0xffffffff); var x480: u32 = undefined; var x481: u32 = undefined; fiatP384MulxU32(&x480, &x481, x448, 0xffffffff); var x482: u32 = undefined; var x483: u32 = undefined; fiatP384MulxU32(&x482, &x483, x448, 0xffffffff); var x484: u32 = undefined; var x485: u32 = undefined; fiatP384MulxU32(&x484, &x485, x448, 0xffffffff); var x486: u32 = undefined; var x487: u32 = undefined; fiatP384MulxU32(&x486, &x487, x448, 0xfffffffe); var x488: u32 = undefined; var x489: u32 = undefined; fiatP384MulxU32(&x488, &x489, x448, 0xffffffff); var x490: u32 = undefined; var x491: u32 = undefined; fiatP384MulxU32(&x490, &x491, x448, 0xffffffff); var x492: u32 = undefined; var x493: u1 = undefined; fiatP384AddcarryxU32(&x492, &x493, 0x0, x489, x486); var x494: u32 = undefined; var x495: u1 = undefined; fiatP384AddcarryxU32(&x494, &x495, x493, x487, x484); var x496: u32 = undefined; var x497: u1 = undefined; fiatP384AddcarryxU32(&x496, &x497, x495, x485, x482); var x498: u32 = undefined; var x499: u1 = undefined; fiatP384AddcarryxU32(&x498, &x499, x497, x483, x480); var x500: u32 = undefined; var x501: u1 = undefined; fiatP384AddcarryxU32(&x500, &x501, x499, x481, x478); var x502: u32 = undefined; var x503: u1 = undefined; fiatP384AddcarryxU32(&x502, &x503, x501, x479, x476); var x504: u32 = undefined; var x505: u1 = undefined; fiatP384AddcarryxU32(&x504, &x505, x503, x477, x474); var x506: u32 = undefined; var x507: u1 = undefined; fiatP384AddcarryxU32(&x506, &x507, x505, x475, x472); var x508: u32 = undefined; var x509: u1 = undefined; fiatP384AddcarryxU32(&x508, &x509, 0x0, x448, x490); var x510: u32 = undefined; var x511: u1 = undefined; fiatP384AddcarryxU32(&x510, &x511, x509, x450, x491); var x512: u32 = undefined; var x513: u1 = undefined; fiatP384AddcarryxU32(&x512, &x513, x511, x452, @intCast(u32, 0x0)); var x514: u32 = undefined; var x515: u1 = undefined; fiatP384AddcarryxU32(&x514, &x515, x513, x454, x488); var x516: u32 = undefined; var x517: u1 = undefined; fiatP384AddcarryxU32(&x516, &x517, x515, x456, x492); var x518: u32 = undefined; var x519: u1 = undefined; fiatP384AddcarryxU32(&x518, &x519, x517, x458, x494); var x520: u32 = undefined; var x521: u1 = undefined; fiatP384AddcarryxU32(&x520, &x521, x519, x460, x496); var x522: u32 = undefined; var x523: u1 = undefined; fiatP384AddcarryxU32(&x522, &x523, x521, x462, x498); var x524: u32 = undefined; var x525: u1 = undefined; fiatP384AddcarryxU32(&x524, &x525, x523, x464, x500); var x526: u32 = undefined; var x527: u1 = undefined; fiatP384AddcarryxU32(&x526, &x527, x525, x466, x502); var x528: u32 = undefined; var x529: u1 = undefined; fiatP384AddcarryxU32(&x528, &x529, x527, x468, x504); var x530: u32 = undefined; var x531: u1 = undefined; fiatP384AddcarryxU32(&x530, &x531, x529, x470, x506); var x532: u32 = undefined; var x533: u1 = undefined; fiatP384AddcarryxU32(&x532, &x533, x531, (@intCast(u32, x471) + @intCast(u32, x447)), (@intCast(u32, x507) + x473)); var x534: u32 = undefined; var x535: u1 = undefined; fiatP384AddcarryxU32(&x534, &x535, 0x0, x510, (arg1[7])); var x536: u32 = undefined; var x537: u1 = undefined; fiatP384AddcarryxU32(&x536, &x537, x535, x512, @intCast(u32, 0x0)); var x538: u32 = undefined; var x539: u1 = undefined; fiatP384AddcarryxU32(&x538, &x539, x537, x514, @intCast(u32, 0x0)); var x540: u32 = undefined; var x541: u1 = undefined; fiatP384AddcarryxU32(&x540, &x541, x539, x516, @intCast(u32, 0x0)); var x542: u32 = undefined; var x543: u1 = undefined; fiatP384AddcarryxU32(&x542, &x543, x541, x518, @intCast(u32, 0x0)); var x544: u32 = undefined; var x545: u1 = undefined; fiatP384AddcarryxU32(&x544, &x545, x543, x520, @intCast(u32, 0x0)); var x546: u32 = undefined; var x547: u1 = undefined; fiatP384AddcarryxU32(&x546, &x547, x545, x522, @intCast(u32, 0x0)); var x548: u32 = undefined; var x549: u1 = undefined; fiatP384AddcarryxU32(&x548, &x549, x547, x524, @intCast(u32, 0x0)); var x550: u32 = undefined; var x551: u1 = undefined; fiatP384AddcarryxU32(&x550, &x551, x549, x526, @intCast(u32, 0x0)); var x552: u32 = undefined; var x553: u1 = undefined; fiatP384AddcarryxU32(&x552, &x553, x551, x528, @intCast(u32, 0x0)); var x554: u32 = undefined; var x555: u1 = undefined; fiatP384AddcarryxU32(&x554, &x555, x553, x530, @intCast(u32, 0x0)); var x556: u32 = undefined; var x557: u1 = undefined; fiatP384AddcarryxU32(&x556, &x557, x555, x532, @intCast(u32, 0x0)); var x558: u32 = undefined; var x559: u32 = undefined; fiatP384MulxU32(&x558, &x559, x534, 0xffffffff); var x560: u32 = undefined; var x561: u32 = undefined; fiatP384MulxU32(&x560, &x561, x534, 0xffffffff); var x562: u32 = undefined; var x563: u32 = undefined; fiatP384MulxU32(&x562, &x563, x534, 0xffffffff); var x564: u32 = undefined; var x565: u32 = undefined; fiatP384MulxU32(&x564, &x565, x534, 0xffffffff); var x566: u32 = undefined; var x567: u32 = undefined; fiatP384MulxU32(&x566, &x567, x534, 0xffffffff); var x568: u32 = undefined; var x569: u32 = undefined; fiatP384MulxU32(&x568, &x569, x534, 0xffffffff); var x570: u32 = undefined; var x571: u32 = undefined; fiatP384MulxU32(&x570, &x571, x534, 0xffffffff); var x572: u32 = undefined; var x573: u32 = undefined; fiatP384MulxU32(&x572, &x573, x534, 0xfffffffe); var x574: u32 = undefined; var x575: u32 = undefined; fiatP384MulxU32(&x574, &x575, x534, 0xffffffff); var x576: u32 = undefined; var x577: u32 = undefined; fiatP384MulxU32(&x576, &x577, x534, 0xffffffff); var x578: u32 = undefined; var x579: u1 = undefined; fiatP384AddcarryxU32(&x578, &x579, 0x0, x575, x572); var x580: u32 = undefined; var x581: u1 = undefined; fiatP384AddcarryxU32(&x580, &x581, x579, x573, x570); var x582: u32 = undefined; var x583: u1 = undefined; fiatP384AddcarryxU32(&x582, &x583, x581, x571, x568); var x584: u32 = undefined; var x585: u1 = undefined; fiatP384AddcarryxU32(&x584, &x585, x583, x569, x566); var x586: u32 = undefined; var x587: u1 = undefined; fiatP384AddcarryxU32(&x586, &x587, x585, x567, x564); var x588: u32 = undefined; var x589: u1 = undefined; fiatP384AddcarryxU32(&x588, &x589, x587, x565, x562); var x590: u32 = undefined; var x591: u1 = undefined; fiatP384AddcarryxU32(&x590, &x591, x589, x563, x560); var x592: u32 = undefined; var x593: u1 = undefined; fiatP384AddcarryxU32(&x592, &x593, x591, x561, x558); var x594: u32 = undefined; var x595: u1 = undefined; fiatP384AddcarryxU32(&x594, &x595, 0x0, x534, x576); var x596: u32 = undefined; var x597: u1 = undefined; fiatP384AddcarryxU32(&x596, &x597, x595, x536, x577); var x598: u32 = undefined; var x599: u1 = undefined; fiatP384AddcarryxU32(&x598, &x599, x597, x538, @intCast(u32, 0x0)); var x600: u32 = undefined; var x601: u1 = undefined; fiatP384AddcarryxU32(&x600, &x601, x599, x540, x574); var x602: u32 = undefined; var x603: u1 = undefined; fiatP384AddcarryxU32(&x602, &x603, x601, x542, x578); var x604: u32 = undefined; var x605: u1 = undefined; fiatP384AddcarryxU32(&x604, &x605, x603, x544, x580); var x606: u32 = undefined; var x607: u1 = undefined; fiatP384AddcarryxU32(&x606, &x607, x605, x546, x582); var x608: u32 = undefined; var x609: u1 = undefined; fiatP384AddcarryxU32(&x608, &x609, x607, x548, x584); var x610: u32 = undefined; var x611: u1 = undefined; fiatP384AddcarryxU32(&x610, &x611, x609, x550, x586); var x612: u32 = undefined; var x613: u1 = undefined; fiatP384AddcarryxU32(&x612, &x613, x611, x552, x588); var x614: u32 = undefined; var x615: u1 = undefined; fiatP384AddcarryxU32(&x614, &x615, x613, x554, x590); var x616: u32 = undefined; var x617: u1 = undefined; fiatP384AddcarryxU32(&x616, &x617, x615, x556, x592); var x618: u32 = undefined; var x619: u1 = undefined; fiatP384AddcarryxU32(&x618, &x619, x617, (@intCast(u32, x557) + @intCast(u32, x533)), (@intCast(u32, x593) + x559)); var x620: u32 = undefined; var x621: u1 = undefined; fiatP384AddcarryxU32(&x620, &x621, 0x0, x596, (arg1[8])); var x622: u32 = undefined; var x623: u1 = undefined; fiatP384AddcarryxU32(&x622, &x623, x621, x598, @intCast(u32, 0x0)); var x624: u32 = undefined; var x625: u1 = undefined; fiatP384AddcarryxU32(&x624, &x625, x623, x600, @intCast(u32, 0x0)); var x626: u32 = undefined; var x627: u1 = undefined; fiatP384AddcarryxU32(&x626, &x627, x625, x602, @intCast(u32, 0x0)); var x628: u32 = undefined; var x629: u1 = undefined; fiatP384AddcarryxU32(&x628, &x629, x627, x604, @intCast(u32, 0x0)); var x630: u32 = undefined; var x631: u1 = undefined; fiatP384AddcarryxU32(&x630, &x631, x629, x606, @intCast(u32, 0x0)); var x632: u32 = undefined; var x633: u1 = undefined; fiatP384AddcarryxU32(&x632, &x633, x631, x608, @intCast(u32, 0x0)); var x634: u32 = undefined; var x635: u1 = undefined; fiatP384AddcarryxU32(&x634, &x635, x633, x610, @intCast(u32, 0x0)); var x636: u32 = undefined; var x637: u1 = undefined; fiatP384AddcarryxU32(&x636, &x637, x635, x612, @intCast(u32, 0x0)); var x638: u32 = undefined; var x639: u1 = undefined; fiatP384AddcarryxU32(&x638, &x639, x637, x614, @intCast(u32, 0x0)); var x640: u32 = undefined; var x641: u1 = undefined; fiatP384AddcarryxU32(&x640, &x641, x639, x616, @intCast(u32, 0x0)); var x642: u32 = undefined; var x643: u1 = undefined; fiatP384AddcarryxU32(&x642, &x643, x641, x618, @intCast(u32, 0x0)); var x644: u32 = undefined; var x645: u32 = undefined; fiatP384MulxU32(&x644, &x645, x620, 0xffffffff); var x646: u32 = undefined; var x647: u32 = undefined; fiatP384MulxU32(&x646, &x647, x620, 0xffffffff); var x648: u32 = undefined; var x649: u32 = undefined; fiatP384MulxU32(&x648, &x649, x620, 0xffffffff); var x650: u32 = undefined; var x651: u32 = undefined; fiatP384MulxU32(&x650, &x651, x620, 0xffffffff); var x652: u32 = undefined; var x653: u32 = undefined; fiatP384MulxU32(&x652, &x653, x620, 0xffffffff); var x654: u32 = undefined; var x655: u32 = undefined; fiatP384MulxU32(&x654, &x655, x620, 0xffffffff); var x656: u32 = undefined; var x657: u32 = undefined; fiatP384MulxU32(&x656, &x657, x620, 0xffffffff); var x658: u32 = undefined; var x659: u32 = undefined; fiatP384MulxU32(&x658, &x659, x620, 0xfffffffe); var x660: u32 = undefined; var x661: u32 = undefined; fiatP384MulxU32(&x660, &x661, x620, 0xffffffff); var x662: u32 = undefined; var x663: u32 = undefined; fiatP384MulxU32(&x662, &x663, x620, 0xffffffff); var x664: u32 = undefined; var x665: u1 = undefined; fiatP384AddcarryxU32(&x664, &x665, 0x0, x661, x658); var x666: u32 = undefined; var x667: u1 = undefined; fiatP384AddcarryxU32(&x666, &x667, x665, x659, x656); var x668: u32 = undefined; var x669: u1 = undefined; fiatP384AddcarryxU32(&x668, &x669, x667, x657, x654); var x670: u32 = undefined; var x671: u1 = undefined; fiatP384AddcarryxU32(&x670, &x671, x669, x655, x652); var x672: u32 = undefined; var x673: u1 = undefined; fiatP384AddcarryxU32(&x672, &x673, x671, x653, x650); var x674: u32 = undefined; var x675: u1 = undefined; fiatP384AddcarryxU32(&x674, &x675, x673, x651, x648); var x676: u32 = undefined; var x677: u1 = undefined; fiatP384AddcarryxU32(&x676, &x677, x675, x649, x646); var x678: u32 = undefined; var x679: u1 = undefined; fiatP384AddcarryxU32(&x678, &x679, x677, x647, x644); var x680: u32 = undefined; var x681: u1 = undefined; fiatP384AddcarryxU32(&x680, &x681, 0x0, x620, x662); var x682: u32 = undefined; var x683: u1 = undefined; fiatP384AddcarryxU32(&x682, &x683, x681, x622, x663); var x684: u32 = undefined; var x685: u1 = undefined; fiatP384AddcarryxU32(&x684, &x685, x683, x624, @intCast(u32, 0x0)); var x686: u32 = undefined; var x687: u1 = undefined; fiatP384AddcarryxU32(&x686, &x687, x685, x626, x660); var x688: u32 = undefined; var x689: u1 = undefined; fiatP384AddcarryxU32(&x688, &x689, x687, x628, x664); var x690: u32 = undefined; var x691: u1 = undefined; fiatP384AddcarryxU32(&x690, &x691, x689, x630, x666); var x692: u32 = undefined; var x693: u1 = undefined; fiatP384AddcarryxU32(&x692, &x693, x691, x632, x668); var x694: u32 = undefined; var x695: u1 = undefined; fiatP384AddcarryxU32(&x694, &x695, x693, x634, x670); var x696: u32 = undefined; var x697: u1 = undefined; fiatP384AddcarryxU32(&x696, &x697, x695, x636, x672); var x698: u32 = undefined; var x699: u1 = undefined; fiatP384AddcarryxU32(&x698, &x699, x697, x638, x674); var x700: u32 = undefined; var x701: u1 = undefined; fiatP384AddcarryxU32(&x700, &x701, x699, x640, x676); var x702: u32 = undefined; var x703: u1 = undefined; fiatP384AddcarryxU32(&x702, &x703, x701, x642, x678); var x704: u32 = undefined; var x705: u1 = undefined; fiatP384AddcarryxU32(&x704, &x705, x703, (@intCast(u32, x643) + @intCast(u32, x619)), (@intCast(u32, x679) + x645)); var x706: u32 = undefined; var x707: u1 = undefined; fiatP384AddcarryxU32(&x706, &x707, 0x0, x682, (arg1[9])); var x708: u32 = undefined; var x709: u1 = undefined; fiatP384AddcarryxU32(&x708, &x709, x707, x684, @intCast(u32, 0x0)); var x710: u32 = undefined; var x711: u1 = undefined; fiatP384AddcarryxU32(&x710, &x711, x709, x686, @intCast(u32, 0x0)); var x712: u32 = undefined; var x713: u1 = undefined; fiatP384AddcarryxU32(&x712, &x713, x711, x688, @intCast(u32, 0x0)); var x714: u32 = undefined; var x715: u1 = undefined; fiatP384AddcarryxU32(&x714, &x715, x713, x690, @intCast(u32, 0x0)); var x716: u32 = undefined; var x717: u1 = undefined; fiatP384AddcarryxU32(&x716, &x717, x715, x692, @intCast(u32, 0x0)); var x718: u32 = undefined; var x719: u1 = undefined; fiatP384AddcarryxU32(&x718, &x719, x717, x694, @intCast(u32, 0x0)); var x720: u32 = undefined; var x721: u1 = undefined; fiatP384AddcarryxU32(&x720, &x721, x719, x696, @intCast(u32, 0x0)); var x722: u32 = undefined; var x723: u1 = undefined; fiatP384AddcarryxU32(&x722, &x723, x721, x698, @intCast(u32, 0x0)); var x724: u32 = undefined; var x725: u1 = undefined; fiatP384AddcarryxU32(&x724, &x725, x723, x700, @intCast(u32, 0x0)); var x726: u32 = undefined; var x727: u1 = undefined; fiatP384AddcarryxU32(&x726, &x727, x725, x702, @intCast(u32, 0x0)); var x728: u32 = undefined; var x729: u1 = undefined; fiatP384AddcarryxU32(&x728, &x729, x727, x704, @intCast(u32, 0x0)); var x730: u32 = undefined; var x731: u32 = undefined; fiatP384MulxU32(&x730, &x731, x706, 0xffffffff); var x732: u32 = undefined; var x733: u32 = undefined; fiatP384MulxU32(&x732, &x733, x706, 0xffffffff); var x734: u32 = undefined; var x735: u32 = undefined; fiatP384MulxU32(&x734, &x735, x706, 0xffffffff); var x736: u32 = undefined; var x737: u32 = undefined; fiatP384MulxU32(&x736, &x737, x706, 0xffffffff); var x738: u32 = undefined; var x739: u32 = undefined; fiatP384MulxU32(&x738, &x739, x706, 0xffffffff); var x740: u32 = undefined; var x741: u32 = undefined; fiatP384MulxU32(&x740, &x741, x706, 0xffffffff); var x742: u32 = undefined; var x743: u32 = undefined; fiatP384MulxU32(&x742, &x743, x706, 0xffffffff); var x744: u32 = undefined; var x745: u32 = undefined; fiatP384MulxU32(&x744, &x745, x706, 0xfffffffe); var x746: u32 = undefined; var x747: u32 = undefined; fiatP384MulxU32(&x746, &x747, x706, 0xffffffff); var x748: u32 = undefined; var x749: u32 = undefined; fiatP384MulxU32(&x748, &x749, x706, 0xffffffff); var x750: u32 = undefined; var x751: u1 = undefined; fiatP384AddcarryxU32(&x750, &x751, 0x0, x747, x744); var x752: u32 = undefined; var x753: u1 = undefined; fiatP384AddcarryxU32(&x752, &x753, x751, x745, x742); var x754: u32 = undefined; var x755: u1 = undefined; fiatP384AddcarryxU32(&x754, &x755, x753, x743, x740); var x756: u32 = undefined; var x757: u1 = undefined; fiatP384AddcarryxU32(&x756, &x757, x755, x741, x738); var x758: u32 = undefined; var x759: u1 = undefined; fiatP384AddcarryxU32(&x758, &x759, x757, x739, x736); var x760: u32 = undefined; var x761: u1 = undefined; fiatP384AddcarryxU32(&x760, &x761, x759, x737, x734); var x762: u32 = undefined; var x763: u1 = undefined; fiatP384AddcarryxU32(&x762, &x763, x761, x735, x732); var x764: u32 = undefined; var x765: u1 = undefined; fiatP384AddcarryxU32(&x764, &x765, x763, x733, x730); var x766: u32 = undefined; var x767: u1 = undefined; fiatP384AddcarryxU32(&x766, &x767, 0x0, x706, x748); var x768: u32 = undefined; var x769: u1 = undefined; fiatP384AddcarryxU32(&x768, &x769, x767, x708, x749); var x770: u32 = undefined; var x771: u1 = undefined; fiatP384AddcarryxU32(&x770, &x771, x769, x710, @intCast(u32, 0x0)); var x772: u32 = undefined; var x773: u1 = undefined; fiatP384AddcarryxU32(&x772, &x773, x771, x712, x746); var x774: u32 = undefined; var x775: u1 = undefined; fiatP384AddcarryxU32(&x774, &x775, x773, x714, x750); var x776: u32 = undefined; var x777: u1 = undefined; fiatP384AddcarryxU32(&x776, &x777, x775, x716, x752); var x778: u32 = undefined; var x779: u1 = undefined; fiatP384AddcarryxU32(&x778, &x779, x777, x718, x754); var x780: u32 = undefined; var x781: u1 = undefined; fiatP384AddcarryxU32(&x780, &x781, x779, x720, x756); var x782: u32 = undefined; var x783: u1 = undefined; fiatP384AddcarryxU32(&x782, &x783, x781, x722, x758); var x784: u32 = undefined; var x785: u1 = undefined; fiatP384AddcarryxU32(&x784, &x785, x783, x724, x760); var x786: u32 = undefined; var x787: u1 = undefined; fiatP384AddcarryxU32(&x786, &x787, x785, x726, x762); var x788: u32 = undefined; var x789: u1 = undefined; fiatP384AddcarryxU32(&x788, &x789, x787, x728, x764); var x790: u32 = undefined; var x791: u1 = undefined; fiatP384AddcarryxU32(&x790, &x791, x789, (@intCast(u32, x729) + @intCast(u32, x705)), (@intCast(u32, x765) + x731)); var x792: u32 = undefined; var x793: u1 = undefined; fiatP384AddcarryxU32(&x792, &x793, 0x0, x768, (arg1[10])); var x794: u32 = undefined; var x795: u1 = undefined; fiatP384AddcarryxU32(&x794, &x795, x793, x770, @intCast(u32, 0x0)); var x796: u32 = undefined; var x797: u1 = undefined; fiatP384AddcarryxU32(&x796, &x797, x795, x772, @intCast(u32, 0x0)); var x798: u32 = undefined; var x799: u1 = undefined; fiatP384AddcarryxU32(&x798, &x799, x797, x774, @intCast(u32, 0x0)); var x800: u32 = undefined; var x801: u1 = undefined; fiatP384AddcarryxU32(&x800, &x801, x799, x776, @intCast(u32, 0x0)); var x802: u32 = undefined; var x803: u1 = undefined; fiatP384AddcarryxU32(&x802, &x803, x801, x778, @intCast(u32, 0x0)); var x804: u32 = undefined; var x805: u1 = undefined; fiatP384AddcarryxU32(&x804, &x805, x803, x780, @intCast(u32, 0x0)); var x806: u32 = undefined; var x807: u1 = undefined; fiatP384AddcarryxU32(&x806, &x807, x805, x782, @intCast(u32, 0x0)); var x808: u32 = undefined; var x809: u1 = undefined; fiatP384AddcarryxU32(&x808, &x809, x807, x784, @intCast(u32, 0x0)); var x810: u32 = undefined; var x811: u1 = undefined; fiatP384AddcarryxU32(&x810, &x811, x809, x786, @intCast(u32, 0x0)); var x812: u32 = undefined; var x813: u1 = undefined; fiatP384AddcarryxU32(&x812, &x813, x811, x788, @intCast(u32, 0x0)); var x814: u32 = undefined; var x815: u1 = undefined; fiatP384AddcarryxU32(&x814, &x815, x813, x790, @intCast(u32, 0x0)); var x816: u32 = undefined; var x817: u32 = undefined; fiatP384MulxU32(&x816, &x817, x792, 0xffffffff); var x818: u32 = undefined; var x819: u32 = undefined; fiatP384MulxU32(&x818, &x819, x792, 0xffffffff); var x820: u32 = undefined; var x821: u32 = undefined; fiatP384MulxU32(&x820, &x821, x792, 0xffffffff); var x822: u32 = undefined; var x823: u32 = undefined; fiatP384MulxU32(&x822, &x823, x792, 0xffffffff); var x824: u32 = undefined; var x825: u32 = undefined; fiatP384MulxU32(&x824, &x825, x792, 0xffffffff); var x826: u32 = undefined; var x827: u32 = undefined; fiatP384MulxU32(&x826, &x827, x792, 0xffffffff); var x828: u32 = undefined; var x829: u32 = undefined; fiatP384MulxU32(&x828, &x829, x792, 0xffffffff); var x830: u32 = undefined; var x831: u32 = undefined; fiatP384MulxU32(&x830, &x831, x792, 0xfffffffe); var x832: u32 = undefined; var x833: u32 = undefined; fiatP384MulxU32(&x832, &x833, x792, 0xffffffff); var x834: u32 = undefined; var x835: u32 = undefined; fiatP384MulxU32(&x834, &x835, x792, 0xffffffff); var x836: u32 = undefined; var x837: u1 = undefined; fiatP384AddcarryxU32(&x836, &x837, 0x0, x833, x830); var x838: u32 = undefined; var x839: u1 = undefined; fiatP384AddcarryxU32(&x838, &x839, x837, x831, x828); var x840: u32 = undefined; var x841: u1 = undefined; fiatP384AddcarryxU32(&x840, &x841, x839, x829, x826); var x842: u32 = undefined; var x843: u1 = undefined; fiatP384AddcarryxU32(&x842, &x843, x841, x827, x824); var x844: u32 = undefined; var x845: u1 = undefined; fiatP384AddcarryxU32(&x844, &x845, x843, x825, x822); var x846: u32 = undefined; var x847: u1 = undefined; fiatP384AddcarryxU32(&x846, &x847, x845, x823, x820); var x848: u32 = undefined; var x849: u1 = undefined; fiatP384AddcarryxU32(&x848, &x849, x847, x821, x818); var x850: u32 = undefined; var x851: u1 = undefined; fiatP384AddcarryxU32(&x850, &x851, x849, x819, x816); var x852: u32 = undefined; var x853: u1 = undefined; fiatP384AddcarryxU32(&x852, &x853, 0x0, x792, x834); var x854: u32 = undefined; var x855: u1 = undefined; fiatP384AddcarryxU32(&x854, &x855, x853, x794, x835); var x856: u32 = undefined; var x857: u1 = undefined; fiatP384AddcarryxU32(&x856, &x857, x855, x796, @intCast(u32, 0x0)); var x858: u32 = undefined; var x859: u1 = undefined; fiatP384AddcarryxU32(&x858, &x859, x857, x798, x832); var x860: u32 = undefined; var x861: u1 = undefined; fiatP384AddcarryxU32(&x860, &x861, x859, x800, x836); var x862: u32 = undefined; var x863: u1 = undefined; fiatP384AddcarryxU32(&x862, &x863, x861, x802, x838); var x864: u32 = undefined; var x865: u1 = undefined; fiatP384AddcarryxU32(&x864, &x865, x863, x804, x840); var x866: u32 = undefined; var x867: u1 = undefined; fiatP384AddcarryxU32(&x866, &x867, x865, x806, x842); var x868: u32 = undefined; var x869: u1 = undefined; fiatP384AddcarryxU32(&x868, &x869, x867, x808, x844); var x870: u32 = undefined; var x871: u1 = undefined; fiatP384AddcarryxU32(&x870, &x871, x869, x810, x846); var x872: u32 = undefined; var x873: u1 = undefined; fiatP384AddcarryxU32(&x872, &x873, x871, x812, x848); var x874: u32 = undefined; var x875: u1 = undefined; fiatP384AddcarryxU32(&x874, &x875, x873, x814, x850); var x876: u32 = undefined; var x877: u1 = undefined; fiatP384AddcarryxU32(&x876, &x877, x875, (@intCast(u32, x815) + @intCast(u32, x791)), (@intCast(u32, x851) + x817)); var x878: u32 = undefined; var x879: u1 = undefined; fiatP384AddcarryxU32(&x878, &x879, 0x0, x854, (arg1[11])); var x880: u32 = undefined; var x881: u1 = undefined; fiatP384AddcarryxU32(&x880, &x881, x879, x856, @intCast(u32, 0x0)); var x882: u32 = undefined; var x883: u1 = undefined; fiatP384AddcarryxU32(&x882, &x883, x881, x858, @intCast(u32, 0x0)); var x884: u32 = undefined; var x885: u1 = undefined; fiatP384AddcarryxU32(&x884, &x885, x883, x860, @intCast(u32, 0x0)); var x886: u32 = undefined; var x887: u1 = undefined; fiatP384AddcarryxU32(&x886, &x887, x885, x862, @intCast(u32, 0x0)); var x888: u32 = undefined; var x889: u1 = undefined; fiatP384AddcarryxU32(&x888, &x889, x887, x864, @intCast(u32, 0x0)); var x890: u32 = undefined; var x891: u1 = undefined; fiatP384AddcarryxU32(&x890, &x891, x889, x866, @intCast(u32, 0x0)); var x892: u32 = undefined; var x893: u1 = undefined; fiatP384AddcarryxU32(&x892, &x893, x891, x868, @intCast(u32, 0x0)); var x894: u32 = undefined; var x895: u1 = undefined; fiatP384AddcarryxU32(&x894, &x895, x893, x870, @intCast(u32, 0x0)); var x896: u32 = undefined; var x897: u1 = undefined; fiatP384AddcarryxU32(&x896, &x897, x895, x872, @intCast(u32, 0x0)); var x898: u32 = undefined; var x899: u1 = undefined; fiatP384AddcarryxU32(&x898, &x899, x897, x874, @intCast(u32, 0x0)); var x900: u32 = undefined; var x901: u1 = undefined; fiatP384AddcarryxU32(&x900, &x901, x899, x876, @intCast(u32, 0x0)); var x902: u32 = undefined; var x903: u32 = undefined; fiatP384MulxU32(&x902, &x903, x878, 0xffffffff); var x904: u32 = undefined; var x905: u32 = undefined; fiatP384MulxU32(&x904, &x905, x878, 0xffffffff); var x906: u32 = undefined; var x907: u32 = undefined; fiatP384MulxU32(&x906, &x907, x878, 0xffffffff); var x908: u32 = undefined; var x909: u32 = undefined; fiatP384MulxU32(&x908, &x909, x878, 0xffffffff); var x910: u32 = undefined; var x911: u32 = undefined; fiatP384MulxU32(&x910, &x911, x878, 0xffffffff); var x912: u32 = undefined; var x913: u32 = undefined; fiatP384MulxU32(&x912, &x913, x878, 0xffffffff); var x914: u32 = undefined; var x915: u32 = undefined; fiatP384MulxU32(&x914, &x915, x878, 0xffffffff); var x916: u32 = undefined; var x917: u32 = undefined; fiatP384MulxU32(&x916, &x917, x878, 0xfffffffe); var x918: u32 = undefined; var x919: u32 = undefined; fiatP384MulxU32(&x918, &x919, x878, 0xffffffff); var x920: u32 = undefined; var x921: u32 = undefined; fiatP384MulxU32(&x920, &x921, x878, 0xffffffff); var x922: u32 = undefined; var x923: u1 = undefined; fiatP384AddcarryxU32(&x922, &x923, 0x0, x919, x916); var x924: u32 = undefined; var x925: u1 = undefined; fiatP384AddcarryxU32(&x924, &x925, x923, x917, x914); var x926: u32 = undefined; var x927: u1 = undefined; fiatP384AddcarryxU32(&x926, &x927, x925, x915, x912); var x928: u32 = undefined; var x929: u1 = undefined; fiatP384AddcarryxU32(&x928, &x929, x927, x913, x910); var x930: u32 = undefined; var x931: u1 = undefined; fiatP384AddcarryxU32(&x930, &x931, x929, x911, x908); var x932: u32 = undefined; var x933: u1 = undefined; fiatP384AddcarryxU32(&x932, &x933, x931, x909, x906); var x934: u32 = undefined; var x935: u1 = undefined; fiatP384AddcarryxU32(&x934, &x935, x933, x907, x904); var x936: u32 = undefined; var x937: u1 = undefined; fiatP384AddcarryxU32(&x936, &x937, x935, x905, x902); var x938: u32 = undefined; var x939: u1 = undefined; fiatP384AddcarryxU32(&x938, &x939, 0x0, x878, x920); var x940: u32 = undefined; var x941: u1 = undefined; fiatP384AddcarryxU32(&x940, &x941, x939, x880, x921); var x942: u32 = undefined; var x943: u1 = undefined; fiatP384AddcarryxU32(&x942, &x943, x941, x882, @intCast(u32, 0x0)); var x944: u32 = undefined; var x945: u1 = undefined; fiatP384AddcarryxU32(&x944, &x945, x943, x884, x918); var x946: u32 = undefined; var x947: u1 = undefined; fiatP384AddcarryxU32(&x946, &x947, x945, x886, x922); var x948: u32 = undefined; var x949: u1 = undefined; fiatP384AddcarryxU32(&x948, &x949, x947, x888, x924); var x950: u32 = undefined; var x951: u1 = undefined; fiatP384AddcarryxU32(&x950, &x951, x949, x890, x926); var x952: u32 = undefined; var x953: u1 = undefined; fiatP384AddcarryxU32(&x952, &x953, x951, x892, x928); var x954: u32 = undefined; var x955: u1 = undefined; fiatP384AddcarryxU32(&x954, &x955, x953, x894, x930); var x956: u32 = undefined; var x957: u1 = undefined; fiatP384AddcarryxU32(&x956, &x957, x955, x896, x932); var x958: u32 = undefined; var x959: u1 = undefined; fiatP384AddcarryxU32(&x958, &x959, x957, x898, x934); var x960: u32 = undefined; var x961: u1 = undefined; fiatP384AddcarryxU32(&x960, &x961, x959, x900, x936); var x962: u32 = undefined; var x963: u1 = undefined; fiatP384AddcarryxU32(&x962, &x963, x961, (@intCast(u32, x901) + @intCast(u32, x877)), (@intCast(u32, x937) + x903)); var x964: u32 = undefined; var x965: u1 = undefined; fiatP384SubborrowxU32(&x964, &x965, 0x0, x940, 0xffffffff); var x966: u32 = undefined; var x967: u1 = undefined; fiatP384SubborrowxU32(&x966, &x967, x965, x942, @intCast(u32, 0x0)); var x968: u32 = undefined; var x969: u1 = undefined; fiatP384SubborrowxU32(&x968, &x969, x967, x944, @intCast(u32, 0x0)); var x970: u32 = undefined; var x971: u1 = undefined; fiatP384SubborrowxU32(&x970, &x971, x969, x946, 0xffffffff); var x972: u32 = undefined; var x973: u1 = undefined; fiatP384SubborrowxU32(&x972, &x973, x971, x948, 0xfffffffe); var x974: u32 = undefined; var x975: u1 = undefined; fiatP384SubborrowxU32(&x974, &x975, x973, x950, 0xffffffff); var x976: u32 = undefined; var x977: u1 = undefined; fiatP384SubborrowxU32(&x976, &x977, x975, x952, 0xffffffff); var x978: u32 = undefined; var x979: u1 = undefined; fiatP384SubborrowxU32(&x978, &x979, x977, x954, 0xffffffff); var x980: u32 = undefined; var x981: u1 = undefined; fiatP384SubborrowxU32(&x980, &x981, x979, x956, 0xffffffff); var x982: u32 = undefined; var x983: u1 = undefined; fiatP384SubborrowxU32(&x982, &x983, x981, x958, 0xffffffff); var x984: u32 = undefined; var x985: u1 = undefined; fiatP384SubborrowxU32(&x984, &x985, x983, x960, 0xffffffff); var x986: u32 = undefined; var x987: u1 = undefined; fiatP384SubborrowxU32(&x986, &x987, x985, x962, 0xffffffff); var x988: u32 = undefined; var x989: u1 = undefined; fiatP384SubborrowxU32(&x988, &x989, x987, @intCast(u32, x963), @intCast(u32, 0x0)); var x990: u32 = undefined; fiatP384CmovznzU32(&x990, x989, x964, x940); var x991: u32 = undefined; fiatP384CmovznzU32(&x991, x989, x966, x942); var x992: u32 = undefined; fiatP384CmovznzU32(&x992, x989, x968, x944); var x993: u32 = undefined; fiatP384CmovznzU32(&x993, x989, x970, x946); var x994: u32 = undefined; fiatP384CmovznzU32(&x994, x989, x972, x948); var x995: u32 = undefined; fiatP384CmovznzU32(&x995, x989, x974, x950); var x996: u32 = undefined; fiatP384CmovznzU32(&x996, x989, x976, x952); var x997: u32 = undefined; fiatP384CmovznzU32(&x997, x989, x978, x954); var x998: u32 = undefined; fiatP384CmovznzU32(&x998, x989, x980, x956); var x999: u32 = undefined; fiatP384CmovznzU32(&x999, x989, x982, x958); var x1000: u32 = undefined; fiatP384CmovznzU32(&x1000, x989, x984, x960); var x1001: u32 = undefined; fiatP384CmovznzU32(&x1001, x989, x986, x962); out1[0] = x990; out1[1] = x991; out1[2] = x992; out1[3] = x993; out1[4] = x994; out1[5] = x995; out1[6] = x996; out1[7] = x997; out1[8] = x998; out1[9] = x999; out1[10] = x1000; out1[11] = x1001; } /// The function fiatP384ToMontgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384ToMontgomery(out1: *[12]u32, arg1: [12]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[8]); const x9: u32 = (arg1[9]); const x10: u32 = (arg1[10]); const x11: u32 = (arg1[11]); const x12: u32 = (arg1[0]); var x13: u32 = undefined; var x14: u32 = undefined; fiatP384MulxU32(&x13, &x14, x12, 0x2); var x15: u32 = undefined; var x16: u32 = undefined; fiatP384MulxU32(&x15, &x16, x12, 0xfffffffe); var x17: u32 = undefined; var x18: u32 = undefined; fiatP384MulxU32(&x17, &x18, x12, 0x2); var x19: u32 = undefined; var x20: u32 = undefined; fiatP384MulxU32(&x19, &x20, x12, 0xfffffffe); var x21: u32 = undefined; var x22: u1 = undefined; fiatP384AddcarryxU32(&x21, &x22, 0x0, @intCast(u32, @intCast(u1, x14)), x12); var x23: u32 = undefined; var x24: u32 = undefined; fiatP384MulxU32(&x23, &x24, x12, 0xffffffff); var x25: u32 = undefined; var x26: u32 = undefined; fiatP384MulxU32(&x25, &x26, x12, 0xffffffff); var x27: u32 = undefined; var x28: u32 = undefined; fiatP384MulxU32(&x27, &x28, x12, 0xffffffff); var x29: u32 = undefined; var x30: u32 = undefined; fiatP384MulxU32(&x29, &x30, x12, 0xffffffff); var x31: u32 = undefined; var x32: u32 = undefined; fiatP384MulxU32(&x31, &x32, x12, 0xffffffff); var x33: u32 = undefined; var x34: u32 = undefined; fiatP384MulxU32(&x33, &x34, x12, 0xffffffff); var x35: u32 = undefined; var x36: u32 = undefined; fiatP384MulxU32(&x35, &x36, x12, 0xffffffff); var x37: u32 = undefined; var x38: u32 = undefined; fiatP384MulxU32(&x37, &x38, x12, 0xfffffffe); var x39: u32 = undefined; var x40: u32 = undefined; fiatP384MulxU32(&x39, &x40, x12, 0xffffffff); var x41: u32 = undefined; var x42: u32 = undefined; fiatP384MulxU32(&x41, &x42, x12, 0xffffffff); var x43: u32 = undefined; var x44: u1 = undefined; fiatP384AddcarryxU32(&x43, &x44, 0x0, x40, x37); var x45: u32 = undefined; var x46: u1 = undefined; fiatP384AddcarryxU32(&x45, &x46, x44, x38, x35); var x47: u32 = undefined; var x48: u1 = undefined; fiatP384AddcarryxU32(&x47, &x48, x46, x36, x33); var x49: u32 = undefined; var x50: u1 = undefined; fiatP384AddcarryxU32(&x49, &x50, x48, x34, x31); var x51: u32 = undefined; var x52: u1 = undefined; fiatP384AddcarryxU32(&x51, &x52, x50, x32, x29); var x53: u32 = undefined; var x54: u1 = undefined; fiatP384AddcarryxU32(&x53, &x54, x52, x30, x27); var x55: u32 = undefined; var x56: u1 = undefined; fiatP384AddcarryxU32(&x55, &x56, x54, x28, x25); var x57: u32 = undefined; var x58: u1 = undefined; fiatP384AddcarryxU32(&x57, &x58, x56, x26, x23); var x59: u32 = undefined; var x60: u1 = undefined; fiatP384AddcarryxU32(&x59, &x60, 0x0, x12, x41); var x61: u32 = undefined; var x62: u1 = undefined; fiatP384AddcarryxU32(&x61, &x62, x60, x19, x42); var x63: u32 = undefined; var x64: u1 = undefined; fiatP384AddcarryxU32(&x63, &x64, 0x0, x17, x39); var x65: u32 = undefined; var x66: u1 = undefined; fiatP384AddcarryxU32(&x65, &x66, x64, @intCast(u32, @intCast(u1, x18)), x43); var x67: u32 = undefined; var x68: u1 = undefined; fiatP384AddcarryxU32(&x67, &x68, x66, x15, x45); var x69: u32 = undefined; var x70: u1 = undefined; fiatP384AddcarryxU32(&x69, &x70, x68, x16, x47); var x71: u32 = undefined; var x72: u1 = undefined; fiatP384AddcarryxU32(&x71, &x72, x70, x13, x49); var x73: u32 = undefined; var x74: u1 = undefined; fiatP384AddcarryxU32(&x73, &x74, x72, x21, x51); var x75: u32 = undefined; var x76: u1 = undefined; fiatP384AddcarryxU32(&x75, &x76, x74, @intCast(u32, x22), x53); var x77: u32 = undefined; var x78: u1 = undefined; fiatP384AddcarryxU32(&x77, &x78, x76, @intCast(u32, 0x0), x55); var x79: u32 = undefined; var x80: u1 = undefined; fiatP384AddcarryxU32(&x79, &x80, x78, @intCast(u32, 0x0), x57); var x81: u32 = undefined; var x82: u1 = undefined; fiatP384AddcarryxU32(&x81, &x82, x80, @intCast(u32, 0x0), (@intCast(u32, x58) + x24)); var x83: u32 = undefined; var x84: u32 = undefined; fiatP384MulxU32(&x83, &x84, x1, 0x2); var x85: u32 = undefined; var x86: u32 = undefined; fiatP384MulxU32(&x85, &x86, x1, 0xfffffffe); var x87: u32 = undefined; var x88: u32 = undefined; fiatP384MulxU32(&x87, &x88, x1, 0x2); var x89: u32 = undefined; var x90: u32 = undefined; fiatP384MulxU32(&x89, &x90, x1, 0xfffffffe); var x91: u32 = undefined; var x92: u1 = undefined; fiatP384AddcarryxU32(&x91, &x92, 0x0, @intCast(u32, @intCast(u1, x84)), x1); var x93: u32 = undefined; var x94: u1 = undefined; fiatP384AddcarryxU32(&x93, &x94, 0x0, x61, x1); var x95: u32 = undefined; var x96: u1 = undefined; fiatP384AddcarryxU32(&x95, &x96, x94, (@intCast(u32, x62) + x20), x89); var x97: u32 = undefined; var x98: u1 = undefined; fiatP384AddcarryxU32(&x97, &x98, x96, x63, x90); var x99: u32 = undefined; var x100: u1 = undefined; fiatP384AddcarryxU32(&x99, &x100, x98, x65, x87); var x101: u32 = undefined; var x102: u1 = undefined; fiatP384AddcarryxU32(&x101, &x102, x100, x67, @intCast(u32, @intCast(u1, x88))); var x103: u32 = undefined; var x104: u1 = undefined; fiatP384AddcarryxU32(&x103, &x104, x102, x69, x85); var x105: u32 = undefined; var x106: u1 = undefined; fiatP384AddcarryxU32(&x105, &x106, x104, x71, x86); var x107: u32 = undefined; var x108: u1 = undefined; fiatP384AddcarryxU32(&x107, &x108, x106, x73, x83); var x109: u32 = undefined; var x110: u1 = undefined; fiatP384AddcarryxU32(&x109, &x110, x108, x75, x91); var x111: u32 = undefined; var x112: u1 = undefined; fiatP384AddcarryxU32(&x111, &x112, x110, x77, @intCast(u32, x92)); var x113: u32 = undefined; var x114: u1 = undefined; fiatP384AddcarryxU32(&x113, &x114, x112, x79, @intCast(u32, 0x0)); var x115: u32 = undefined; var x116: u1 = undefined; fiatP384AddcarryxU32(&x115, &x116, x114, x81, @intCast(u32, 0x0)); var x117: u32 = undefined; var x118: u32 = undefined; fiatP384MulxU32(&x117, &x118, x93, 0xffffffff); var x119: u32 = undefined; var x120: u32 = undefined; fiatP384MulxU32(&x119, &x120, x93, 0xffffffff); var x121: u32 = undefined; var x122: u32 = undefined; fiatP384MulxU32(&x121, &x122, x93, 0xffffffff); var x123: u32 = undefined; var x124: u32 = undefined; fiatP384MulxU32(&x123, &x124, x93, 0xffffffff); var x125: u32 = undefined; var x126: u32 = undefined; fiatP384MulxU32(&x125, &x126, x93, 0xffffffff); var x127: u32 = undefined; var x128: u32 = undefined; fiatP384MulxU32(&x127, &x128, x93, 0xffffffff); var x129: u32 = undefined; var x130: u32 = undefined; fiatP384MulxU32(&x129, &x130, x93, 0xffffffff); var x131: u32 = undefined; var x132: u32 = undefined; fiatP384MulxU32(&x131, &x132, x93, 0xfffffffe); var x133: u32 = undefined; var x134: u32 = undefined; fiatP384MulxU32(&x133, &x134, x93, 0xffffffff); var x135: u32 = undefined; var x136: u32 = undefined; fiatP384MulxU32(&x135, &x136, x93, 0xffffffff); var x137: u32 = undefined; var x138: u1 = undefined; fiatP384AddcarryxU32(&x137, &x138, 0x0, x134, x131); var x139: u32 = undefined; var x140: u1 = undefined; fiatP384AddcarryxU32(&x139, &x140, x138, x132, x129); var x141: u32 = undefined; var x142: u1 = undefined; fiatP384AddcarryxU32(&x141, &x142, x140, x130, x127); var x143: u32 = undefined; var x144: u1 = undefined; fiatP384AddcarryxU32(&x143, &x144, x142, x128, x125); var x145: u32 = undefined; var x146: u1 = undefined; fiatP384AddcarryxU32(&x145, &x146, x144, x126, x123); var x147: u32 = undefined; var x148: u1 = undefined; fiatP384AddcarryxU32(&x147, &x148, x146, x124, x121); var x149: u32 = undefined; var x150: u1 = undefined; fiatP384AddcarryxU32(&x149, &x150, x148, x122, x119); var x151: u32 = undefined; var x152: u1 = undefined; fiatP384AddcarryxU32(&x151, &x152, x150, x120, x117); var x153: u32 = undefined; var x154: u1 = undefined; fiatP384AddcarryxU32(&x153, &x154, 0x0, x93, x135); var x155: u32 = undefined; var x156: u1 = undefined; fiatP384AddcarryxU32(&x155, &x156, x154, x95, x136); var x157: u32 = undefined; var x158: u1 = undefined; fiatP384AddcarryxU32(&x157, &x158, x156, x97, @intCast(u32, 0x0)); var x159: u32 = undefined; var x160: u1 = undefined; fiatP384AddcarryxU32(&x159, &x160, x158, x99, x133); var x161: u32 = undefined; var x162: u1 = undefined; fiatP384AddcarryxU32(&x161, &x162, x160, x101, x137); var x163: u32 = undefined; var x164: u1 = undefined; fiatP384AddcarryxU32(&x163, &x164, x162, x103, x139); var x165: u32 = undefined; var x166: u1 = undefined; fiatP384AddcarryxU32(&x165, &x166, x164, x105, x141); var x167: u32 = undefined; var x168: u1 = undefined; fiatP384AddcarryxU32(&x167, &x168, x166, x107, x143); var x169: u32 = undefined; var x170: u1 = undefined; fiatP384AddcarryxU32(&x169, &x170, x168, x109, x145); var x171: u32 = undefined; var x172: u1 = undefined; fiatP384AddcarryxU32(&x171, &x172, x170, x111, x147); var x173: u32 = undefined; var x174: u1 = undefined; fiatP384AddcarryxU32(&x173, &x174, x172, x113, x149); var x175: u32 = undefined; var x176: u1 = undefined; fiatP384AddcarryxU32(&x175, &x176, x174, x115, x151); var x177: u32 = undefined; var x178: u1 = undefined; fiatP384AddcarryxU32(&x177, &x178, x176, (@intCast(u32, x116) + @intCast(u32, x82)), (@intCast(u32, x152) + x118)); var x179: u32 = undefined; var x180: u32 = undefined; fiatP384MulxU32(&x179, &x180, x2, 0x2); var x181: u32 = undefined; var x182: u32 = undefined; fiatP384MulxU32(&x181, &x182, x2, 0xfffffffe); var x183: u32 = undefined; var x184: u32 = undefined; fiatP384MulxU32(&x183, &x184, x2, 0x2); var x185: u32 = undefined; var x186: u32 = undefined; fiatP384MulxU32(&x185, &x186, x2, 0xfffffffe); var x187: u32 = undefined; var x188: u1 = undefined; fiatP384AddcarryxU32(&x187, &x188, 0x0, @intCast(u32, @intCast(u1, x180)), x2); var x189: u32 = undefined; var x190: u1 = undefined; fiatP384AddcarryxU32(&x189, &x190, 0x0, x155, x2); var x191: u32 = undefined; var x192: u1 = undefined; fiatP384AddcarryxU32(&x191, &x192, x190, x157, x185); var x193: u32 = undefined; var x194: u1 = undefined; fiatP384AddcarryxU32(&x193, &x194, x192, x159, x186); var x195: u32 = undefined; var x196: u1 = undefined; fiatP384AddcarryxU32(&x195, &x196, x194, x161, x183); var x197: u32 = undefined; var x198: u1 = undefined; fiatP384AddcarryxU32(&x197, &x198, x196, x163, @intCast(u32, @intCast(u1, x184))); var x199: u32 = undefined; var x200: u1 = undefined; fiatP384AddcarryxU32(&x199, &x200, x198, x165, x181); var x201: u32 = undefined; var x202: u1 = undefined; fiatP384AddcarryxU32(&x201, &x202, x200, x167, x182); var x203: u32 = undefined; var x204: u1 = undefined; fiatP384AddcarryxU32(&x203, &x204, x202, x169, x179); var x205: u32 = undefined; var x206: u1 = undefined; fiatP384AddcarryxU32(&x205, &x206, x204, x171, x187); var x207: u32 = undefined; var x208: u1 = undefined; fiatP384AddcarryxU32(&x207, &x208, x206, x173, @intCast(u32, x188)); var x209: u32 = undefined; var x210: u1 = undefined; fiatP384AddcarryxU32(&x209, &x210, x208, x175, @intCast(u32, 0x0)); var x211: u32 = undefined; var x212: u1 = undefined; fiatP384AddcarryxU32(&x211, &x212, x210, x177, @intCast(u32, 0x0)); var x213: u32 = undefined; var x214: u32 = undefined; fiatP384MulxU32(&x213, &x214, x189, 0xffffffff); var x215: u32 = undefined; var x216: u32 = undefined; fiatP384MulxU32(&x215, &x216, x189, 0xffffffff); var x217: u32 = undefined; var x218: u32 = undefined; fiatP384MulxU32(&x217, &x218, x189, 0xffffffff); var x219: u32 = undefined; var x220: u32 = undefined; fiatP384MulxU32(&x219, &x220, x189, 0xffffffff); var x221: u32 = undefined; var x222: u32 = undefined; fiatP384MulxU32(&x221, &x222, x189, 0xffffffff); var x223: u32 = undefined; var x224: u32 = undefined; fiatP384MulxU32(&x223, &x224, x189, 0xffffffff); var x225: u32 = undefined; var x226: u32 = undefined; fiatP384MulxU32(&x225, &x226, x189, 0xffffffff); var x227: u32 = undefined; var x228: u32 = undefined; fiatP384MulxU32(&x227, &x228, x189, 0xfffffffe); var x229: u32 = undefined; var x230: u32 = undefined; fiatP384MulxU32(&x229, &x230, x189, 0xffffffff); var x231: u32 = undefined; var x232: u32 = undefined; fiatP384MulxU32(&x231, &x232, x189, 0xffffffff); var x233: u32 = undefined; var x234: u1 = undefined; fiatP384AddcarryxU32(&x233, &x234, 0x0, x230, x227); var x235: u32 = undefined; var x236: u1 = undefined; fiatP384AddcarryxU32(&x235, &x236, x234, x228, x225); var x237: u32 = undefined; var x238: u1 = undefined; fiatP384AddcarryxU32(&x237, &x238, x236, x226, x223); var x239: u32 = undefined; var x240: u1 = undefined; fiatP384AddcarryxU32(&x239, &x240, x238, x224, x221); var x241: u32 = undefined; var x242: u1 = undefined; fiatP384AddcarryxU32(&x241, &x242, x240, x222, x219); var x243: u32 = undefined; var x244: u1 = undefined; fiatP384AddcarryxU32(&x243, &x244, x242, x220, x217); var x245: u32 = undefined; var x246: u1 = undefined; fiatP384AddcarryxU32(&x245, &x246, x244, x218, x215); var x247: u32 = undefined; var x248: u1 = undefined; fiatP384AddcarryxU32(&x247, &x248, x246, x216, x213); var x249: u32 = undefined; var x250: u1 = undefined; fiatP384AddcarryxU32(&x249, &x250, 0x0, x189, x231); var x251: u32 = undefined; var x252: u1 = undefined; fiatP384AddcarryxU32(&x251, &x252, x250, x191, x232); var x253: u32 = undefined; var x254: u1 = undefined; fiatP384AddcarryxU32(&x253, &x254, x252, x193, @intCast(u32, 0x0)); var x255: u32 = undefined; var x256: u1 = undefined; fiatP384AddcarryxU32(&x255, &x256, x254, x195, x229); var x257: u32 = undefined; var x258: u1 = undefined; fiatP384AddcarryxU32(&x257, &x258, x256, x197, x233); var x259: u32 = undefined; var x260: u1 = undefined; fiatP384AddcarryxU32(&x259, &x260, x258, x199, x235); var x261: u32 = undefined; var x262: u1 = undefined; fiatP384AddcarryxU32(&x261, &x262, x260, x201, x237); var x263: u32 = undefined; var x264: u1 = undefined; fiatP384AddcarryxU32(&x263, &x264, x262, x203, x239); var x265: u32 = undefined; var x266: u1 = undefined; fiatP384AddcarryxU32(&x265, &x266, x264, x205, x241); var x267: u32 = undefined; var x268: u1 = undefined; fiatP384AddcarryxU32(&x267, &x268, x266, x207, x243); var x269: u32 = undefined; var x270: u1 = undefined; fiatP384AddcarryxU32(&x269, &x270, x268, x209, x245); var x271: u32 = undefined; var x272: u1 = undefined; fiatP384AddcarryxU32(&x271, &x272, x270, x211, x247); var x273: u32 = undefined; var x274: u1 = undefined; fiatP384AddcarryxU32(&x273, &x274, x272, (@intCast(u32, x212) + @intCast(u32, x178)), (@intCast(u32, x248) + x214)); var x275: u32 = undefined; var x276: u32 = undefined; fiatP384MulxU32(&x275, &x276, x3, 0x2); var x277: u32 = undefined; var x278: u32 = undefined; fiatP384MulxU32(&x277, &x278, x3, 0xfffffffe); var x279: u32 = undefined; var x280: u32 = undefined; fiatP384MulxU32(&x279, &x280, x3, 0x2); var x281: u32 = undefined; var x282: u32 = undefined; fiatP384MulxU32(&x281, &x282, x3, 0xfffffffe); var x283: u32 = undefined; var x284: u1 = undefined; fiatP384AddcarryxU32(&x283, &x284, 0x0, @intCast(u32, @intCast(u1, x276)), x3); var x285: u32 = undefined; var x286: u1 = undefined; fiatP384AddcarryxU32(&x285, &x286, 0x0, x251, x3); var x287: u32 = undefined; var x288: u1 = undefined; fiatP384AddcarryxU32(&x287, &x288, x286, x253, x281); var x289: u32 = undefined; var x290: u1 = undefined; fiatP384AddcarryxU32(&x289, &x290, x288, x255, x282); var x291: u32 = undefined; var x292: u1 = undefined; fiatP384AddcarryxU32(&x291, &x292, x290, x257, x279); var x293: u32 = undefined; var x294: u1 = undefined; fiatP384AddcarryxU32(&x293, &x294, x292, x259, @intCast(u32, @intCast(u1, x280))); var x295: u32 = undefined; var x296: u1 = undefined; fiatP384AddcarryxU32(&x295, &x296, x294, x261, x277); var x297: u32 = undefined; var x298: u1 = undefined; fiatP384AddcarryxU32(&x297, &x298, x296, x263, x278); var x299: u32 = undefined; var x300: u1 = undefined; fiatP384AddcarryxU32(&x299, &x300, x298, x265, x275); var x301: u32 = undefined; var x302: u1 = undefined; fiatP384AddcarryxU32(&x301, &x302, x300, x267, x283); var x303: u32 = undefined; var x304: u1 = undefined; fiatP384AddcarryxU32(&x303, &x304, x302, x269, @intCast(u32, x284)); var x305: u32 = undefined; var x306: u1 = undefined; fiatP384AddcarryxU32(&x305, &x306, x304, x271, @intCast(u32, 0x0)); var x307: u32 = undefined; var x308: u1 = undefined; fiatP384AddcarryxU32(&x307, &x308, x306, x273, @intCast(u32, 0x0)); var x309: u32 = undefined; var x310: u32 = undefined; fiatP384MulxU32(&x309, &x310, x285, 0xffffffff); var x311: u32 = undefined; var x312: u32 = undefined; fiatP384MulxU32(&x311, &x312, x285, 0xffffffff); var x313: u32 = undefined; var x314: u32 = undefined; fiatP384MulxU32(&x313, &x314, x285, 0xffffffff); var x315: u32 = undefined; var x316: u32 = undefined; fiatP384MulxU32(&x315, &x316, x285, 0xffffffff); var x317: u32 = undefined; var x318: u32 = undefined; fiatP384MulxU32(&x317, &x318, x285, 0xffffffff); var x319: u32 = undefined; var x320: u32 = undefined; fiatP384MulxU32(&x319, &x320, x285, 0xffffffff); var x321: u32 = undefined; var x322: u32 = undefined; fiatP384MulxU32(&x321, &x322, x285, 0xffffffff); var x323: u32 = undefined; var x324: u32 = undefined; fiatP384MulxU32(&x323, &x324, x285, 0xfffffffe); var x325: u32 = undefined; var x326: u32 = undefined; fiatP384MulxU32(&x325, &x326, x285, 0xffffffff); var x327: u32 = undefined; var x328: u32 = undefined; fiatP384MulxU32(&x327, &x328, x285, 0xffffffff); var x329: u32 = undefined; var x330: u1 = undefined; fiatP384AddcarryxU32(&x329, &x330, 0x0, x326, x323); var x331: u32 = undefined; var x332: u1 = undefined; fiatP384AddcarryxU32(&x331, &x332, x330, x324, x321); var x333: u32 = undefined; var x334: u1 = undefined; fiatP384AddcarryxU32(&x333, &x334, x332, x322, x319); var x335: u32 = undefined; var x336: u1 = undefined; fiatP384AddcarryxU32(&x335, &x336, x334, x320, x317); var x337: u32 = undefined; var x338: u1 = undefined; fiatP384AddcarryxU32(&x337, &x338, x336, x318, x315); var x339: u32 = undefined; var x340: u1 = undefined; fiatP384AddcarryxU32(&x339, &x340, x338, x316, x313); var x341: u32 = undefined; var x342: u1 = undefined; fiatP384AddcarryxU32(&x341, &x342, x340, x314, x311); var x343: u32 = undefined; var x344: u1 = undefined; fiatP384AddcarryxU32(&x343, &x344, x342, x312, x309); var x345: u32 = undefined; var x346: u1 = undefined; fiatP384AddcarryxU32(&x345, &x346, 0x0, x285, x327); var x347: u32 = undefined; var x348: u1 = undefined; fiatP384AddcarryxU32(&x347, &x348, x346, x287, x328); var x349: u32 = undefined; var x350: u1 = undefined; fiatP384AddcarryxU32(&x349, &x350, x348, x289, @intCast(u32, 0x0)); var x351: u32 = undefined; var x352: u1 = undefined; fiatP384AddcarryxU32(&x351, &x352, x350, x291, x325); var x353: u32 = undefined; var x354: u1 = undefined; fiatP384AddcarryxU32(&x353, &x354, x352, x293, x329); var x355: u32 = undefined; var x356: u1 = undefined; fiatP384AddcarryxU32(&x355, &x356, x354, x295, x331); var x357: u32 = undefined; var x358: u1 = undefined; fiatP384AddcarryxU32(&x357, &x358, x356, x297, x333); var x359: u32 = undefined; var x360: u1 = undefined; fiatP384AddcarryxU32(&x359, &x360, x358, x299, x335); var x361: u32 = undefined; var x362: u1 = undefined; fiatP384AddcarryxU32(&x361, &x362, x360, x301, x337); var x363: u32 = undefined; var x364: u1 = undefined; fiatP384AddcarryxU32(&x363, &x364, x362, x303, x339); var x365: u32 = undefined; var x366: u1 = undefined; fiatP384AddcarryxU32(&x365, &x366, x364, x305, x341); var x367: u32 = undefined; var x368: u1 = undefined; fiatP384AddcarryxU32(&x367, &x368, x366, x307, x343); var x369: u32 = undefined; var x370: u1 = undefined; fiatP384AddcarryxU32(&x369, &x370, x368, (@intCast(u32, x308) + @intCast(u32, x274)), (@intCast(u32, x344) + x310)); var x371: u32 = undefined; var x372: u32 = undefined; fiatP384MulxU32(&x371, &x372, x4, 0x2); var x373: u32 = undefined; var x374: u32 = undefined; fiatP384MulxU32(&x373, &x374, x4, 0xfffffffe); var x375: u32 = undefined; var x376: u32 = undefined; fiatP384MulxU32(&x375, &x376, x4, 0x2); var x377: u32 = undefined; var x378: u32 = undefined; fiatP384MulxU32(&x377, &x378, x4, 0xfffffffe); var x379: u32 = undefined; var x380: u1 = undefined; fiatP384AddcarryxU32(&x379, &x380, 0x0, @intCast(u32, @intCast(u1, x372)), x4); var x381: u32 = undefined; var x382: u1 = undefined; fiatP384AddcarryxU32(&x381, &x382, 0x0, x347, x4); var x383: u32 = undefined; var x384: u1 = undefined; fiatP384AddcarryxU32(&x383, &x384, x382, x349, x377); var x385: u32 = undefined; var x386: u1 = undefined; fiatP384AddcarryxU32(&x385, &x386, x384, x351, x378); var x387: u32 = undefined; var x388: u1 = undefined; fiatP384AddcarryxU32(&x387, &x388, x386, x353, x375); var x389: u32 = undefined; var x390: u1 = undefined; fiatP384AddcarryxU32(&x389, &x390, x388, x355, @intCast(u32, @intCast(u1, x376))); var x391: u32 = undefined; var x392: u1 = undefined; fiatP384AddcarryxU32(&x391, &x392, x390, x357, x373); var x393: u32 = undefined; var x394: u1 = undefined; fiatP384AddcarryxU32(&x393, &x394, x392, x359, x374); var x395: u32 = undefined; var x396: u1 = undefined; fiatP384AddcarryxU32(&x395, &x396, x394, x361, x371); var x397: u32 = undefined; var x398: u1 = undefined; fiatP384AddcarryxU32(&x397, &x398, x396, x363, x379); var x399: u32 = undefined; var x400: u1 = undefined; fiatP384AddcarryxU32(&x399, &x400, x398, x365, @intCast(u32, x380)); var x401: u32 = undefined; var x402: u1 = undefined; fiatP384AddcarryxU32(&x401, &x402, x400, x367, @intCast(u32, 0x0)); var x403: u32 = undefined; var x404: u1 = undefined; fiatP384AddcarryxU32(&x403, &x404, x402, x369, @intCast(u32, 0x0)); var x405: u32 = undefined; var x406: u32 = undefined; fiatP384MulxU32(&x405, &x406, x381, 0xffffffff); var x407: u32 = undefined; var x408: u32 = undefined; fiatP384MulxU32(&x407, &x408, x381, 0xffffffff); var x409: u32 = undefined; var x410: u32 = undefined; fiatP384MulxU32(&x409, &x410, x381, 0xffffffff); var x411: u32 = undefined; var x412: u32 = undefined; fiatP384MulxU32(&x411, &x412, x381, 0xffffffff); var x413: u32 = undefined; var x414: u32 = undefined; fiatP384MulxU32(&x413, &x414, x381, 0xffffffff); var x415: u32 = undefined; var x416: u32 = undefined; fiatP384MulxU32(&x415, &x416, x381, 0xffffffff); var x417: u32 = undefined; var x418: u32 = undefined; fiatP384MulxU32(&x417, &x418, x381, 0xffffffff); var x419: u32 = undefined; var x420: u32 = undefined; fiatP384MulxU32(&x419, &x420, x381, 0xfffffffe); var x421: u32 = undefined; var x422: u32 = undefined; fiatP384MulxU32(&x421, &x422, x381, 0xffffffff); var x423: u32 = undefined; var x424: u32 = undefined; fiatP384MulxU32(&x423, &x424, x381, 0xffffffff); var x425: u32 = undefined; var x426: u1 = undefined; fiatP384AddcarryxU32(&x425, &x426, 0x0, x422, x419); var x427: u32 = undefined; var x428: u1 = undefined; fiatP384AddcarryxU32(&x427, &x428, x426, x420, x417); var x429: u32 = undefined; var x430: u1 = undefined; fiatP384AddcarryxU32(&x429, &x430, x428, x418, x415); var x431: u32 = undefined; var x432: u1 = undefined; fiatP384AddcarryxU32(&x431, &x432, x430, x416, x413); var x433: u32 = undefined; var x434: u1 = undefined; fiatP384AddcarryxU32(&x433, &x434, x432, x414, x411); var x435: u32 = undefined; var x436: u1 = undefined; fiatP384AddcarryxU32(&x435, &x436, x434, x412, x409); var x437: u32 = undefined; var x438: u1 = undefined; fiatP384AddcarryxU32(&x437, &x438, x436, x410, x407); var x439: u32 = undefined; var x440: u1 = undefined; fiatP384AddcarryxU32(&x439, &x440, x438, x408, x405); var x441: u32 = undefined; var x442: u1 = undefined; fiatP384AddcarryxU32(&x441, &x442, 0x0, x381, x423); var x443: u32 = undefined; var x444: u1 = undefined; fiatP384AddcarryxU32(&x443, &x444, x442, x383, x424); var x445: u32 = undefined; var x446: u1 = undefined; fiatP384AddcarryxU32(&x445, &x446, x444, x385, @intCast(u32, 0x0)); var x447: u32 = undefined; var x448: u1 = undefined; fiatP384AddcarryxU32(&x447, &x448, x446, x387, x421); var x449: u32 = undefined; var x450: u1 = undefined; fiatP384AddcarryxU32(&x449, &x450, x448, x389, x425); var x451: u32 = undefined; var x452: u1 = undefined; fiatP384AddcarryxU32(&x451, &x452, x450, x391, x427); var x453: u32 = undefined; var x454: u1 = undefined; fiatP384AddcarryxU32(&x453, &x454, x452, x393, x429); var x455: u32 = undefined; var x456: u1 = undefined; fiatP384AddcarryxU32(&x455, &x456, x454, x395, x431); var x457: u32 = undefined; var x458: u1 = undefined; fiatP384AddcarryxU32(&x457, &x458, x456, x397, x433); var x459: u32 = undefined; var x460: u1 = undefined; fiatP384AddcarryxU32(&x459, &x460, x458, x399, x435); var x461: u32 = undefined; var x462: u1 = undefined; fiatP384AddcarryxU32(&x461, &x462, x460, x401, x437); var x463: u32 = undefined; var x464: u1 = undefined; fiatP384AddcarryxU32(&x463, &x464, x462, x403, x439); var x465: u32 = undefined; var x466: u1 = undefined; fiatP384AddcarryxU32(&x465, &x466, x464, (@intCast(u32, x404) + @intCast(u32, x370)), (@intCast(u32, x440) + x406)); var x467: u32 = undefined; var x468: u32 = undefined; fiatP384MulxU32(&x467, &x468, x5, 0x2); var x469: u32 = undefined; var x470: u32 = undefined; fiatP384MulxU32(&x469, &x470, x5, 0xfffffffe); var x471: u32 = undefined; var x472: u32 = undefined; fiatP384MulxU32(&x471, &x472, x5, 0x2); var x473: u32 = undefined; var x474: u32 = undefined; fiatP384MulxU32(&x473, &x474, x5, 0xfffffffe); var x475: u32 = undefined; var x476: u1 = undefined; fiatP384AddcarryxU32(&x475, &x476, 0x0, @intCast(u32, @intCast(u1, x468)), x5); var x477: u32 = undefined; var x478: u1 = undefined; fiatP384AddcarryxU32(&x477, &x478, 0x0, x443, x5); var x479: u32 = undefined; var x480: u1 = undefined; fiatP384AddcarryxU32(&x479, &x480, x478, x445, x473); var x481: u32 = undefined; var x482: u1 = undefined; fiatP384AddcarryxU32(&x481, &x482, x480, x447, x474); var x483: u32 = undefined; var x484: u1 = undefined; fiatP384AddcarryxU32(&x483, &x484, x482, x449, x471); var x485: u32 = undefined; var x486: u1 = undefined; fiatP384AddcarryxU32(&x485, &x486, x484, x451, @intCast(u32, @intCast(u1, x472))); var x487: u32 = undefined; var x488: u1 = undefined; fiatP384AddcarryxU32(&x487, &x488, x486, x453, x469); var x489: u32 = undefined; var x490: u1 = undefined; fiatP384AddcarryxU32(&x489, &x490, x488, x455, x470); var x491: u32 = undefined; var x492: u1 = undefined; fiatP384AddcarryxU32(&x491, &x492, x490, x457, x467); var x493: u32 = undefined; var x494: u1 = undefined; fiatP384AddcarryxU32(&x493, &x494, x492, x459, x475); var x495: u32 = undefined; var x496: u1 = undefined; fiatP384AddcarryxU32(&x495, &x496, x494, x461, @intCast(u32, x476)); var x497: u32 = undefined; var x498: u1 = undefined; fiatP384AddcarryxU32(&x497, &x498, x496, x463, @intCast(u32, 0x0)); var x499: u32 = undefined; var x500: u1 = undefined; fiatP384AddcarryxU32(&x499, &x500, x498, x465, @intCast(u32, 0x0)); var x501: u32 = undefined; var x502: u32 = undefined; fiatP384MulxU32(&x501, &x502, x477, 0xffffffff); var x503: u32 = undefined; var x504: u32 = undefined; fiatP384MulxU32(&x503, &x504, x477, 0xffffffff); var x505: u32 = undefined; var x506: u32 = undefined; fiatP384MulxU32(&x505, &x506, x477, 0xffffffff); var x507: u32 = undefined; var x508: u32 = undefined; fiatP384MulxU32(&x507, &x508, x477, 0xffffffff); var x509: u32 = undefined; var x510: u32 = undefined; fiatP384MulxU32(&x509, &x510, x477, 0xffffffff); var x511: u32 = undefined; var x512: u32 = undefined; fiatP384MulxU32(&x511, &x512, x477, 0xffffffff); var x513: u32 = undefined; var x514: u32 = undefined; fiatP384MulxU32(&x513, &x514, x477, 0xffffffff); var x515: u32 = undefined; var x516: u32 = undefined; fiatP384MulxU32(&x515, &x516, x477, 0xfffffffe); var x517: u32 = undefined; var x518: u32 = undefined; fiatP384MulxU32(&x517, &x518, x477, 0xffffffff); var x519: u32 = undefined; var x520: u32 = undefined; fiatP384MulxU32(&x519, &x520, x477, 0xffffffff); var x521: u32 = undefined; var x522: u1 = undefined; fiatP384AddcarryxU32(&x521, &x522, 0x0, x518, x515); var x523: u32 = undefined; var x524: u1 = undefined; fiatP384AddcarryxU32(&x523, &x524, x522, x516, x513); var x525: u32 = undefined; var x526: u1 = undefined; fiatP384AddcarryxU32(&x525, &x526, x524, x514, x511); var x527: u32 = undefined; var x528: u1 = undefined; fiatP384AddcarryxU32(&x527, &x528, x526, x512, x509); var x529: u32 = undefined; var x530: u1 = undefined; fiatP384AddcarryxU32(&x529, &x530, x528, x510, x507); var x531: u32 = undefined; var x532: u1 = undefined; fiatP384AddcarryxU32(&x531, &x532, x530, x508, x505); var x533: u32 = undefined; var x534: u1 = undefined; fiatP384AddcarryxU32(&x533, &x534, x532, x506, x503); var x535: u32 = undefined; var x536: u1 = undefined; fiatP384AddcarryxU32(&x535, &x536, x534, x504, x501); var x537: u32 = undefined; var x538: u1 = undefined; fiatP384AddcarryxU32(&x537, &x538, 0x0, x477, x519); var x539: u32 = undefined; var x540: u1 = undefined; fiatP384AddcarryxU32(&x539, &x540, x538, x479, x520); var x541: u32 = undefined; var x542: u1 = undefined; fiatP384AddcarryxU32(&x541, &x542, x540, x481, @intCast(u32, 0x0)); var x543: u32 = undefined; var x544: u1 = undefined; fiatP384AddcarryxU32(&x543, &x544, x542, x483, x517); var x545: u32 = undefined; var x546: u1 = undefined; fiatP384AddcarryxU32(&x545, &x546, x544, x485, x521); var x547: u32 = undefined; var x548: u1 = undefined; fiatP384AddcarryxU32(&x547, &x548, x546, x487, x523); var x549: u32 = undefined; var x550: u1 = undefined; fiatP384AddcarryxU32(&x549, &x550, x548, x489, x525); var x551: u32 = undefined; var x552: u1 = undefined; fiatP384AddcarryxU32(&x551, &x552, x550, x491, x527); var x553: u32 = undefined; var x554: u1 = undefined; fiatP384AddcarryxU32(&x553, &x554, x552, x493, x529); var x555: u32 = undefined; var x556: u1 = undefined; fiatP384AddcarryxU32(&x555, &x556, x554, x495, x531); var x557: u32 = undefined; var x558: u1 = undefined; fiatP384AddcarryxU32(&x557, &x558, x556, x497, x533); var x559: u32 = undefined; var x560: u1 = undefined; fiatP384AddcarryxU32(&x559, &x560, x558, x499, x535); var x561: u32 = undefined; var x562: u1 = undefined; fiatP384AddcarryxU32(&x561, &x562, x560, (@intCast(u32, x500) + @intCast(u32, x466)), (@intCast(u32, x536) + x502)); var x563: u32 = undefined; var x564: u32 = undefined; fiatP384MulxU32(&x563, &x564, x6, 0x2); var x565: u32 = undefined; var x566: u32 = undefined; fiatP384MulxU32(&x565, &x566, x6, 0xfffffffe); var x567: u32 = undefined; var x568: u32 = undefined; fiatP384MulxU32(&x567, &x568, x6, 0x2); var x569: u32 = undefined; var x570: u32 = undefined; fiatP384MulxU32(&x569, &x570, x6, 0xfffffffe); var x571: u32 = undefined; var x572: u1 = undefined; fiatP384AddcarryxU32(&x571, &x572, 0x0, @intCast(u32, @intCast(u1, x564)), x6); var x573: u32 = undefined; var x574: u1 = undefined; fiatP384AddcarryxU32(&x573, &x574, 0x0, x539, x6); var x575: u32 = undefined; var x576: u1 = undefined; fiatP384AddcarryxU32(&x575, &x576, x574, x541, x569); var x577: u32 = undefined; var x578: u1 = undefined; fiatP384AddcarryxU32(&x577, &x578, x576, x543, x570); var x579: u32 = undefined; var x580: u1 = undefined; fiatP384AddcarryxU32(&x579, &x580, x578, x545, x567); var x581: u32 = undefined; var x582: u1 = undefined; fiatP384AddcarryxU32(&x581, &x582, x580, x547, @intCast(u32, @intCast(u1, x568))); var x583: u32 = undefined; var x584: u1 = undefined; fiatP384AddcarryxU32(&x583, &x584, x582, x549, x565); var x585: u32 = undefined; var x586: u1 = undefined; fiatP384AddcarryxU32(&x585, &x586, x584, x551, x566); var x587: u32 = undefined; var x588: u1 = undefined; fiatP384AddcarryxU32(&x587, &x588, x586, x553, x563); var x589: u32 = undefined; var x590: u1 = undefined; fiatP384AddcarryxU32(&x589, &x590, x588, x555, x571); var x591: u32 = undefined; var x592: u1 = undefined; fiatP384AddcarryxU32(&x591, &x592, x590, x557, @intCast(u32, x572)); var x593: u32 = undefined; var x594: u1 = undefined; fiatP384AddcarryxU32(&x593, &x594, x592, x559, @intCast(u32, 0x0)); var x595: u32 = undefined; var x596: u1 = undefined; fiatP384AddcarryxU32(&x595, &x596, x594, x561, @intCast(u32, 0x0)); var x597: u32 = undefined; var x598: u32 = undefined; fiatP384MulxU32(&x597, &x598, x573, 0xffffffff); var x599: u32 = undefined; var x600: u32 = undefined; fiatP384MulxU32(&x599, &x600, x573, 0xffffffff); var x601: u32 = undefined; var x602: u32 = undefined; fiatP384MulxU32(&x601, &x602, x573, 0xffffffff); var x603: u32 = undefined; var x604: u32 = undefined; fiatP384MulxU32(&x603, &x604, x573, 0xffffffff); var x605: u32 = undefined; var x606: u32 = undefined; fiatP384MulxU32(&x605, &x606, x573, 0xffffffff); var x607: u32 = undefined; var x608: u32 = undefined; fiatP384MulxU32(&x607, &x608, x573, 0xffffffff); var x609: u32 = undefined; var x610: u32 = undefined; fiatP384MulxU32(&x609, &x610, x573, 0xffffffff); var x611: u32 = undefined; var x612: u32 = undefined; fiatP384MulxU32(&x611, &x612, x573, 0xfffffffe); var x613: u32 = undefined; var x614: u32 = undefined; fiatP384MulxU32(&x613, &x614, x573, 0xffffffff); var x615: u32 = undefined; var x616: u32 = undefined; fiatP384MulxU32(&x615, &x616, x573, 0xffffffff); var x617: u32 = undefined; var x618: u1 = undefined; fiatP384AddcarryxU32(&x617, &x618, 0x0, x614, x611); var x619: u32 = undefined; var x620: u1 = undefined; fiatP384AddcarryxU32(&x619, &x620, x618, x612, x609); var x621: u32 = undefined; var x622: u1 = undefined; fiatP384AddcarryxU32(&x621, &x622, x620, x610, x607); var x623: u32 = undefined; var x624: u1 = undefined; fiatP384AddcarryxU32(&x623, &x624, x622, x608, x605); var x625: u32 = undefined; var x626: u1 = undefined; fiatP384AddcarryxU32(&x625, &x626, x624, x606, x603); var x627: u32 = undefined; var x628: u1 = undefined; fiatP384AddcarryxU32(&x627, &x628, x626, x604, x601); var x629: u32 = undefined; var x630: u1 = undefined; fiatP384AddcarryxU32(&x629, &x630, x628, x602, x599); var x631: u32 = undefined; var x632: u1 = undefined; fiatP384AddcarryxU32(&x631, &x632, x630, x600, x597); var x633: u32 = undefined; var x634: u1 = undefined; fiatP384AddcarryxU32(&x633, &x634, 0x0, x573, x615); var x635: u32 = undefined; var x636: u1 = undefined; fiatP384AddcarryxU32(&x635, &x636, x634, x575, x616); var x637: u32 = undefined; var x638: u1 = undefined; fiatP384AddcarryxU32(&x637, &x638, x636, x577, @intCast(u32, 0x0)); var x639: u32 = undefined; var x640: u1 = undefined; fiatP384AddcarryxU32(&x639, &x640, x638, x579, x613); var x641: u32 = undefined; var x642: u1 = undefined; fiatP384AddcarryxU32(&x641, &x642, x640, x581, x617); var x643: u32 = undefined; var x644: u1 = undefined; fiatP384AddcarryxU32(&x643, &x644, x642, x583, x619); var x645: u32 = undefined; var x646: u1 = undefined; fiatP384AddcarryxU32(&x645, &x646, x644, x585, x621); var x647: u32 = undefined; var x648: u1 = undefined; fiatP384AddcarryxU32(&x647, &x648, x646, x587, x623); var x649: u32 = undefined; var x650: u1 = undefined; fiatP384AddcarryxU32(&x649, &x650, x648, x589, x625); var x651: u32 = undefined; var x652: u1 = undefined; fiatP384AddcarryxU32(&x651, &x652, x650, x591, x627); var x653: u32 = undefined; var x654: u1 = undefined; fiatP384AddcarryxU32(&x653, &x654, x652, x593, x629); var x655: u32 = undefined; var x656: u1 = undefined; fiatP384AddcarryxU32(&x655, &x656, x654, x595, x631); var x657: u32 = undefined; var x658: u1 = undefined; fiatP384AddcarryxU32(&x657, &x658, x656, (@intCast(u32, x596) + @intCast(u32, x562)), (@intCast(u32, x632) + x598)); var x659: u32 = undefined; var x660: u32 = undefined; fiatP384MulxU32(&x659, &x660, x7, 0x2); var x661: u32 = undefined; var x662: u32 = undefined; fiatP384MulxU32(&x661, &x662, x7, 0xfffffffe); var x663: u32 = undefined; var x664: u32 = undefined; fiatP384MulxU32(&x663, &x664, x7, 0x2); var x665: u32 = undefined; var x666: u32 = undefined; fiatP384MulxU32(&x665, &x666, x7, 0xfffffffe); var x667: u32 = undefined; var x668: u1 = undefined; fiatP384AddcarryxU32(&x667, &x668, 0x0, @intCast(u32, @intCast(u1, x660)), x7); var x669: u32 = undefined; var x670: u1 = undefined; fiatP384AddcarryxU32(&x669, &x670, 0x0, x635, x7); var x671: u32 = undefined; var x672: u1 = undefined; fiatP384AddcarryxU32(&x671, &x672, x670, x637, x665); var x673: u32 = undefined; var x674: u1 = undefined; fiatP384AddcarryxU32(&x673, &x674, x672, x639, x666); var x675: u32 = undefined; var x676: u1 = undefined; fiatP384AddcarryxU32(&x675, &x676, x674, x641, x663); var x677: u32 = undefined; var x678: u1 = undefined; fiatP384AddcarryxU32(&x677, &x678, x676, x643, @intCast(u32, @intCast(u1, x664))); var x679: u32 = undefined; var x680: u1 = undefined; fiatP384AddcarryxU32(&x679, &x680, x678, x645, x661); var x681: u32 = undefined; var x682: u1 = undefined; fiatP384AddcarryxU32(&x681, &x682, x680, x647, x662); var x683: u32 = undefined; var x684: u1 = undefined; fiatP384AddcarryxU32(&x683, &x684, x682, x649, x659); var x685: u32 = undefined; var x686: u1 = undefined; fiatP384AddcarryxU32(&x685, &x686, x684, x651, x667); var x687: u32 = undefined; var x688: u1 = undefined; fiatP384AddcarryxU32(&x687, &x688, x686, x653, @intCast(u32, x668)); var x689: u32 = undefined; var x690: u1 = undefined; fiatP384AddcarryxU32(&x689, &x690, x688, x655, @intCast(u32, 0x0)); var x691: u32 = undefined; var x692: u1 = undefined; fiatP384AddcarryxU32(&x691, &x692, x690, x657, @intCast(u32, 0x0)); var x693: u32 = undefined; var x694: u32 = undefined; fiatP384MulxU32(&x693, &x694, x669, 0xffffffff); var x695: u32 = undefined; var x696: u32 = undefined; fiatP384MulxU32(&x695, &x696, x669, 0xffffffff); var x697: u32 = undefined; var x698: u32 = undefined; fiatP384MulxU32(&x697, &x698, x669, 0xffffffff); var x699: u32 = undefined; var x700: u32 = undefined; fiatP384MulxU32(&x699, &x700, x669, 0xffffffff); var x701: u32 = undefined; var x702: u32 = undefined; fiatP384MulxU32(&x701, &x702, x669, 0xffffffff); var x703: u32 = undefined; var x704: u32 = undefined; fiatP384MulxU32(&x703, &x704, x669, 0xffffffff); var x705: u32 = undefined; var x706: u32 = undefined; fiatP384MulxU32(&x705, &x706, x669, 0xffffffff); var x707: u32 = undefined; var x708: u32 = undefined; fiatP384MulxU32(&x707, &x708, x669, 0xfffffffe); var x709: u32 = undefined; var x710: u32 = undefined; fiatP384MulxU32(&x709, &x710, x669, 0xffffffff); var x711: u32 = undefined; var x712: u32 = undefined; fiatP384MulxU32(&x711, &x712, x669, 0xffffffff); var x713: u32 = undefined; var x714: u1 = undefined; fiatP384AddcarryxU32(&x713, &x714, 0x0, x710, x707); var x715: u32 = undefined; var x716: u1 = undefined; fiatP384AddcarryxU32(&x715, &x716, x714, x708, x705); var x717: u32 = undefined; var x718: u1 = undefined; fiatP384AddcarryxU32(&x717, &x718, x716, x706, x703); var x719: u32 = undefined; var x720: u1 = undefined; fiatP384AddcarryxU32(&x719, &x720, x718, x704, x701); var x721: u32 = undefined; var x722: u1 = undefined; fiatP384AddcarryxU32(&x721, &x722, x720, x702, x699); var x723: u32 = undefined; var x724: u1 = undefined; fiatP384AddcarryxU32(&x723, &x724, x722, x700, x697); var x725: u32 = undefined; var x726: u1 = undefined; fiatP384AddcarryxU32(&x725, &x726, x724, x698, x695); var x727: u32 = undefined; var x728: u1 = undefined; fiatP384AddcarryxU32(&x727, &x728, x726, x696, x693); var x729: u32 = undefined; var x730: u1 = undefined; fiatP384AddcarryxU32(&x729, &x730, 0x0, x669, x711); var x731: u32 = undefined; var x732: u1 = undefined; fiatP384AddcarryxU32(&x731, &x732, x730, x671, x712); var x733: u32 = undefined; var x734: u1 = undefined; fiatP384AddcarryxU32(&x733, &x734, x732, x673, @intCast(u32, 0x0)); var x735: u32 = undefined; var x736: u1 = undefined; fiatP384AddcarryxU32(&x735, &x736, x734, x675, x709); var x737: u32 = undefined; var x738: u1 = undefined; fiatP384AddcarryxU32(&x737, &x738, x736, x677, x713); var x739: u32 = undefined; var x740: u1 = undefined; fiatP384AddcarryxU32(&x739, &x740, x738, x679, x715); var x741: u32 = undefined; var x742: u1 = undefined; fiatP384AddcarryxU32(&x741, &x742, x740, x681, x717); var x743: u32 = undefined; var x744: u1 = undefined; fiatP384AddcarryxU32(&x743, &x744, x742, x683, x719); var x745: u32 = undefined; var x746: u1 = undefined; fiatP384AddcarryxU32(&x745, &x746, x744, x685, x721); var x747: u32 = undefined; var x748: u1 = undefined; fiatP384AddcarryxU32(&x747, &x748, x746, x687, x723); var x749: u32 = undefined; var x750: u1 = undefined; fiatP384AddcarryxU32(&x749, &x750, x748, x689, x725); var x751: u32 = undefined; var x752: u1 = undefined; fiatP384AddcarryxU32(&x751, &x752, x750, x691, x727); var x753: u32 = undefined; var x754: u1 = undefined; fiatP384AddcarryxU32(&x753, &x754, x752, (@intCast(u32, x692) + @intCast(u32, x658)), (@intCast(u32, x728) + x694)); var x755: u32 = undefined; var x756: u32 = undefined; fiatP384MulxU32(&x755, &x756, x8, 0x2); var x757: u32 = undefined; var x758: u32 = undefined; fiatP384MulxU32(&x757, &x758, x8, 0xfffffffe); var x759: u32 = undefined; var x760: u32 = undefined; fiatP384MulxU32(&x759, &x760, x8, 0x2); var x761: u32 = undefined; var x762: u32 = undefined; fiatP384MulxU32(&x761, &x762, x8, 0xfffffffe); var x763: u32 = undefined; var x764: u1 = undefined; fiatP384AddcarryxU32(&x763, &x764, 0x0, @intCast(u32, @intCast(u1, x756)), x8); var x765: u32 = undefined; var x766: u1 = undefined; fiatP384AddcarryxU32(&x765, &x766, 0x0, x731, x8); var x767: u32 = undefined; var x768: u1 = undefined; fiatP384AddcarryxU32(&x767, &x768, x766, x733, x761); var x769: u32 = undefined; var x770: u1 = undefined; fiatP384AddcarryxU32(&x769, &x770, x768, x735, x762); var x771: u32 = undefined; var x772: u1 = undefined; fiatP384AddcarryxU32(&x771, &x772, x770, x737, x759); var x773: u32 = undefined; var x774: u1 = undefined; fiatP384AddcarryxU32(&x773, &x774, x772, x739, @intCast(u32, @intCast(u1, x760))); var x775: u32 = undefined; var x776: u1 = undefined; fiatP384AddcarryxU32(&x775, &x776, x774, x741, x757); var x777: u32 = undefined; var x778: u1 = undefined; fiatP384AddcarryxU32(&x777, &x778, x776, x743, x758); var x779: u32 = undefined; var x780: u1 = undefined; fiatP384AddcarryxU32(&x779, &x780, x778, x745, x755); var x781: u32 = undefined; var x782: u1 = undefined; fiatP384AddcarryxU32(&x781, &x782, x780, x747, x763); var x783: u32 = undefined; var x784: u1 = undefined; fiatP384AddcarryxU32(&x783, &x784, x782, x749, @intCast(u32, x764)); var x785: u32 = undefined; var x786: u1 = undefined; fiatP384AddcarryxU32(&x785, &x786, x784, x751, @intCast(u32, 0x0)); var x787: u32 = undefined; var x788: u1 = undefined; fiatP384AddcarryxU32(&x787, &x788, x786, x753, @intCast(u32, 0x0)); var x789: u32 = undefined; var x790: u32 = undefined; fiatP384MulxU32(&x789, &x790, x765, 0xffffffff); var x791: u32 = undefined; var x792: u32 = undefined; fiatP384MulxU32(&x791, &x792, x765, 0xffffffff); var x793: u32 = undefined; var x794: u32 = undefined; fiatP384MulxU32(&x793, &x794, x765, 0xffffffff); var x795: u32 = undefined; var x796: u32 = undefined; fiatP384MulxU32(&x795, &x796, x765, 0xffffffff); var x797: u32 = undefined; var x798: u32 = undefined; fiatP384MulxU32(&x797, &x798, x765, 0xffffffff); var x799: u32 = undefined; var x800: u32 = undefined; fiatP384MulxU32(&x799, &x800, x765, 0xffffffff); var x801: u32 = undefined; var x802: u32 = undefined; fiatP384MulxU32(&x801, &x802, x765, 0xffffffff); var x803: u32 = undefined; var x804: u32 = undefined; fiatP384MulxU32(&x803, &x804, x765, 0xfffffffe); var x805: u32 = undefined; var x806: u32 = undefined; fiatP384MulxU32(&x805, &x806, x765, 0xffffffff); var x807: u32 = undefined; var x808: u32 = undefined; fiatP384MulxU32(&x807, &x808, x765, 0xffffffff); var x809: u32 = undefined; var x810: u1 = undefined; fiatP384AddcarryxU32(&x809, &x810, 0x0, x806, x803); var x811: u32 = undefined; var x812: u1 = undefined; fiatP384AddcarryxU32(&x811, &x812, x810, x804, x801); var x813: u32 = undefined; var x814: u1 = undefined; fiatP384AddcarryxU32(&x813, &x814, x812, x802, x799); var x815: u32 = undefined; var x816: u1 = undefined; fiatP384AddcarryxU32(&x815, &x816, x814, x800, x797); var x817: u32 = undefined; var x818: u1 = undefined; fiatP384AddcarryxU32(&x817, &x818, x816, x798, x795); var x819: u32 = undefined; var x820: u1 = undefined; fiatP384AddcarryxU32(&x819, &x820, x818, x796, x793); var x821: u32 = undefined; var x822: u1 = undefined; fiatP384AddcarryxU32(&x821, &x822, x820, x794, x791); var x823: u32 = undefined; var x824: u1 = undefined; fiatP384AddcarryxU32(&x823, &x824, x822, x792, x789); var x825: u32 = undefined; var x826: u1 = undefined; fiatP384AddcarryxU32(&x825, &x826, 0x0, x765, x807); var x827: u32 = undefined; var x828: u1 = undefined; fiatP384AddcarryxU32(&x827, &x828, x826, x767, x808); var x829: u32 = undefined; var x830: u1 = undefined; fiatP384AddcarryxU32(&x829, &x830, x828, x769, @intCast(u32, 0x0)); var x831: u32 = undefined; var x832: u1 = undefined; fiatP384AddcarryxU32(&x831, &x832, x830, x771, x805); var x833: u32 = undefined; var x834: u1 = undefined; fiatP384AddcarryxU32(&x833, &x834, x832, x773, x809); var x835: u32 = undefined; var x836: u1 = undefined; fiatP384AddcarryxU32(&x835, &x836, x834, x775, x811); var x837: u32 = undefined; var x838: u1 = undefined; fiatP384AddcarryxU32(&x837, &x838, x836, x777, x813); var x839: u32 = undefined; var x840: u1 = undefined; fiatP384AddcarryxU32(&x839, &x840, x838, x779, x815); var x841: u32 = undefined; var x842: u1 = undefined; fiatP384AddcarryxU32(&x841, &x842, x840, x781, x817); var x843: u32 = undefined; var x844: u1 = undefined; fiatP384AddcarryxU32(&x843, &x844, x842, x783, x819); var x845: u32 = undefined; var x846: u1 = undefined; fiatP384AddcarryxU32(&x845, &x846, x844, x785, x821); var x847: u32 = undefined; var x848: u1 = undefined; fiatP384AddcarryxU32(&x847, &x848, x846, x787, x823); var x849: u32 = undefined; var x850: u1 = undefined; fiatP384AddcarryxU32(&x849, &x850, x848, (@intCast(u32, x788) + @intCast(u32, x754)), (@intCast(u32, x824) + x790)); var x851: u32 = undefined; var x852: u32 = undefined; fiatP384MulxU32(&x851, &x852, x9, 0x2); var x853: u32 = undefined; var x854: u32 = undefined; fiatP384MulxU32(&x853, &x854, x9, 0xfffffffe); var x855: u32 = undefined; var x856: u32 = undefined; fiatP384MulxU32(&x855, &x856, x9, 0x2); var x857: u32 = undefined; var x858: u32 = undefined; fiatP384MulxU32(&x857, &x858, x9, 0xfffffffe); var x859: u32 = undefined; var x860: u1 = undefined; fiatP384AddcarryxU32(&x859, &x860, 0x0, @intCast(u32, @intCast(u1, x852)), x9); var x861: u32 = undefined; var x862: u1 = undefined; fiatP384AddcarryxU32(&x861, &x862, 0x0, x827, x9); var x863: u32 = undefined; var x864: u1 = undefined; fiatP384AddcarryxU32(&x863, &x864, x862, x829, x857); var x865: u32 = undefined; var x866: u1 = undefined; fiatP384AddcarryxU32(&x865, &x866, x864, x831, x858); var x867: u32 = undefined; var x868: u1 = undefined; fiatP384AddcarryxU32(&x867, &x868, x866, x833, x855); var x869: u32 = undefined; var x870: u1 = undefined; fiatP384AddcarryxU32(&x869, &x870, x868, x835, @intCast(u32, @intCast(u1, x856))); var x871: u32 = undefined; var x872: u1 = undefined; fiatP384AddcarryxU32(&x871, &x872, x870, x837, x853); var x873: u32 = undefined; var x874: u1 = undefined; fiatP384AddcarryxU32(&x873, &x874, x872, x839, x854); var x875: u32 = undefined; var x876: u1 = undefined; fiatP384AddcarryxU32(&x875, &x876, x874, x841, x851); var x877: u32 = undefined; var x878: u1 = undefined; fiatP384AddcarryxU32(&x877, &x878, x876, x843, x859); var x879: u32 = undefined; var x880: u1 = undefined; fiatP384AddcarryxU32(&x879, &x880, x878, x845, @intCast(u32, x860)); var x881: u32 = undefined; var x882: u1 = undefined; fiatP384AddcarryxU32(&x881, &x882, x880, x847, @intCast(u32, 0x0)); var x883: u32 = undefined; var x884: u1 = undefined; fiatP384AddcarryxU32(&x883, &x884, x882, x849, @intCast(u32, 0x0)); var x885: u32 = undefined; var x886: u32 = undefined; fiatP384MulxU32(&x885, &x886, x861, 0xffffffff); var x887: u32 = undefined; var x888: u32 = undefined; fiatP384MulxU32(&x887, &x888, x861, 0xffffffff); var x889: u32 = undefined; var x890: u32 = undefined; fiatP384MulxU32(&x889, &x890, x861, 0xffffffff); var x891: u32 = undefined; var x892: u32 = undefined; fiatP384MulxU32(&x891, &x892, x861, 0xffffffff); var x893: u32 = undefined; var x894: u32 = undefined; fiatP384MulxU32(&x893, &x894, x861, 0xffffffff); var x895: u32 = undefined; var x896: u32 = undefined; fiatP384MulxU32(&x895, &x896, x861, 0xffffffff); var x897: u32 = undefined; var x898: u32 = undefined; fiatP384MulxU32(&x897, &x898, x861, 0xffffffff); var x899: u32 = undefined; var x900: u32 = undefined; fiatP384MulxU32(&x899, &x900, x861, 0xfffffffe); var x901: u32 = undefined; var x902: u32 = undefined; fiatP384MulxU32(&x901, &x902, x861, 0xffffffff); var x903: u32 = undefined; var x904: u32 = undefined; fiatP384MulxU32(&x903, &x904, x861, 0xffffffff); var x905: u32 = undefined; var x906: u1 = undefined; fiatP384AddcarryxU32(&x905, &x906, 0x0, x902, x899); var x907: u32 = undefined; var x908: u1 = undefined; fiatP384AddcarryxU32(&x907, &x908, x906, x900, x897); var x909: u32 = undefined; var x910: u1 = undefined; fiatP384AddcarryxU32(&x909, &x910, x908, x898, x895); var x911: u32 = undefined; var x912: u1 = undefined; fiatP384AddcarryxU32(&x911, &x912, x910, x896, x893); var x913: u32 = undefined; var x914: u1 = undefined; fiatP384AddcarryxU32(&x913, &x914, x912, x894, x891); var x915: u32 = undefined; var x916: u1 = undefined; fiatP384AddcarryxU32(&x915, &x916, x914, x892, x889); var x917: u32 = undefined; var x918: u1 = undefined; fiatP384AddcarryxU32(&x917, &x918, x916, x890, x887); var x919: u32 = undefined; var x920: u1 = undefined; fiatP384AddcarryxU32(&x919, &x920, x918, x888, x885); var x921: u32 = undefined; var x922: u1 = undefined; fiatP384AddcarryxU32(&x921, &x922, 0x0, x861, x903); var x923: u32 = undefined; var x924: u1 = undefined; fiatP384AddcarryxU32(&x923, &x924, x922, x863, x904); var x925: u32 = undefined; var x926: u1 = undefined; fiatP384AddcarryxU32(&x925, &x926, x924, x865, @intCast(u32, 0x0)); var x927: u32 = undefined; var x928: u1 = undefined; fiatP384AddcarryxU32(&x927, &x928, x926, x867, x901); var x929: u32 = undefined; var x930: u1 = undefined; fiatP384AddcarryxU32(&x929, &x930, x928, x869, x905); var x931: u32 = undefined; var x932: u1 = undefined; fiatP384AddcarryxU32(&x931, &x932, x930, x871, x907); var x933: u32 = undefined; var x934: u1 = undefined; fiatP384AddcarryxU32(&x933, &x934, x932, x873, x909); var x935: u32 = undefined; var x936: u1 = undefined; fiatP384AddcarryxU32(&x935, &x936, x934, x875, x911); var x937: u32 = undefined; var x938: u1 = undefined; fiatP384AddcarryxU32(&x937, &x938, x936, x877, x913); var x939: u32 = undefined; var x940: u1 = undefined; fiatP384AddcarryxU32(&x939, &x940, x938, x879, x915); var x941: u32 = undefined; var x942: u1 = undefined; fiatP384AddcarryxU32(&x941, &x942, x940, x881, x917); var x943: u32 = undefined; var x944: u1 = undefined; fiatP384AddcarryxU32(&x943, &x944, x942, x883, x919); var x945: u32 = undefined; var x946: u1 = undefined; fiatP384AddcarryxU32(&x945, &x946, x944, (@intCast(u32, x884) + @intCast(u32, x850)), (@intCast(u32, x920) + x886)); var x947: u32 = undefined; var x948: u32 = undefined; fiatP384MulxU32(&x947, &x948, x10, 0x2); var x949: u32 = undefined; var x950: u32 = undefined; fiatP384MulxU32(&x949, &x950, x10, 0xfffffffe); var x951: u32 = undefined; var x952: u32 = undefined; fiatP384MulxU32(&x951, &x952, x10, 0x2); var x953: u32 = undefined; var x954: u32 = undefined; fiatP384MulxU32(&x953, &x954, x10, 0xfffffffe); var x955: u32 = undefined; var x956: u1 = undefined; fiatP384AddcarryxU32(&x955, &x956, 0x0, @intCast(u32, @intCast(u1, x948)), x10); var x957: u32 = undefined; var x958: u1 = undefined; fiatP384AddcarryxU32(&x957, &x958, 0x0, x923, x10); var x959: u32 = undefined; var x960: u1 = undefined; fiatP384AddcarryxU32(&x959, &x960, x958, x925, x953); var x961: u32 = undefined; var x962: u1 = undefined; fiatP384AddcarryxU32(&x961, &x962, x960, x927, x954); var x963: u32 = undefined; var x964: u1 = undefined; fiatP384AddcarryxU32(&x963, &x964, x962, x929, x951); var x965: u32 = undefined; var x966: u1 = undefined; fiatP384AddcarryxU32(&x965, &x966, x964, x931, @intCast(u32, @intCast(u1, x952))); var x967: u32 = undefined; var x968: u1 = undefined; fiatP384AddcarryxU32(&x967, &x968, x966, x933, x949); var x969: u32 = undefined; var x970: u1 = undefined; fiatP384AddcarryxU32(&x969, &x970, x968, x935, x950); var x971: u32 = undefined; var x972: u1 = undefined; fiatP384AddcarryxU32(&x971, &x972, x970, x937, x947); var x973: u32 = undefined; var x974: u1 = undefined; fiatP384AddcarryxU32(&x973, &x974, x972, x939, x955); var x975: u32 = undefined; var x976: u1 = undefined; fiatP384AddcarryxU32(&x975, &x976, x974, x941, @intCast(u32, x956)); var x977: u32 = undefined; var x978: u1 = undefined; fiatP384AddcarryxU32(&x977, &x978, x976, x943, @intCast(u32, 0x0)); var x979: u32 = undefined; var x980: u1 = undefined; fiatP384AddcarryxU32(&x979, &x980, x978, x945, @intCast(u32, 0x0)); var x981: u32 = undefined; var x982: u32 = undefined; fiatP384MulxU32(&x981, &x982, x957, 0xffffffff); var x983: u32 = undefined; var x984: u32 = undefined; fiatP384MulxU32(&x983, &x984, x957, 0xffffffff); var x985: u32 = undefined; var x986: u32 = undefined; fiatP384MulxU32(&x985, &x986, x957, 0xffffffff); var x987: u32 = undefined; var x988: u32 = undefined; fiatP384MulxU32(&x987, &x988, x957, 0xffffffff); var x989: u32 = undefined; var x990: u32 = undefined; fiatP384MulxU32(&x989, &x990, x957, 0xffffffff); var x991: u32 = undefined; var x992: u32 = undefined; fiatP384MulxU32(&x991, &x992, x957, 0xffffffff); var x993: u32 = undefined; var x994: u32 = undefined; fiatP384MulxU32(&x993, &x994, x957, 0xffffffff); var x995: u32 = undefined; var x996: u32 = undefined; fiatP384MulxU32(&x995, &x996, x957, 0xfffffffe); var x997: u32 = undefined; var x998: u32 = undefined; fiatP384MulxU32(&x997, &x998, x957, 0xffffffff); var x999: u32 = undefined; var x1000: u32 = undefined; fiatP384MulxU32(&x999, &x1000, x957, 0xffffffff); var x1001: u32 = undefined; var x1002: u1 = undefined; fiatP384AddcarryxU32(&x1001, &x1002, 0x0, x998, x995); var x1003: u32 = undefined; var x1004: u1 = undefined; fiatP384AddcarryxU32(&x1003, &x1004, x1002, x996, x993); var x1005: u32 = undefined; var x1006: u1 = undefined; fiatP384AddcarryxU32(&x1005, &x1006, x1004, x994, x991); var x1007: u32 = undefined; var x1008: u1 = undefined; fiatP384AddcarryxU32(&x1007, &x1008, x1006, x992, x989); var x1009: u32 = undefined; var x1010: u1 = undefined; fiatP384AddcarryxU32(&x1009, &x1010, x1008, x990, x987); var x1011: u32 = undefined; var x1012: u1 = undefined; fiatP384AddcarryxU32(&x1011, &x1012, x1010, x988, x985); var x1013: u32 = undefined; var x1014: u1 = undefined; fiatP384AddcarryxU32(&x1013, &x1014, x1012, x986, x983); var x1015: u32 = undefined; var x1016: u1 = undefined; fiatP384AddcarryxU32(&x1015, &x1016, x1014, x984, x981); var x1017: u32 = undefined; var x1018: u1 = undefined; fiatP384AddcarryxU32(&x1017, &x1018, 0x0, x957, x999); var x1019: u32 = undefined; var x1020: u1 = undefined; fiatP384AddcarryxU32(&x1019, &x1020, x1018, x959, x1000); var x1021: u32 = undefined; var x1022: u1 = undefined; fiatP384AddcarryxU32(&x1021, &x1022, x1020, x961, @intCast(u32, 0x0)); var x1023: u32 = undefined; var x1024: u1 = undefined; fiatP384AddcarryxU32(&x1023, &x1024, x1022, x963, x997); var x1025: u32 = undefined; var x1026: u1 = undefined; fiatP384AddcarryxU32(&x1025, &x1026, x1024, x965, x1001); var x1027: u32 = undefined; var x1028: u1 = undefined; fiatP384AddcarryxU32(&x1027, &x1028, x1026, x967, x1003); var x1029: u32 = undefined; var x1030: u1 = undefined; fiatP384AddcarryxU32(&x1029, &x1030, x1028, x969, x1005); var x1031: u32 = undefined; var x1032: u1 = undefined; fiatP384AddcarryxU32(&x1031, &x1032, x1030, x971, x1007); var x1033: u32 = undefined; var x1034: u1 = undefined; fiatP384AddcarryxU32(&x1033, &x1034, x1032, x973, x1009); var x1035: u32 = undefined; var x1036: u1 = undefined; fiatP384AddcarryxU32(&x1035, &x1036, x1034, x975, x1011); var x1037: u32 = undefined; var x1038: u1 = undefined; fiatP384AddcarryxU32(&x1037, &x1038, x1036, x977, x1013); var x1039: u32 = undefined; var x1040: u1 = undefined; fiatP384AddcarryxU32(&x1039, &x1040, x1038, x979, x1015); var x1041: u32 = undefined; var x1042: u1 = undefined; fiatP384AddcarryxU32(&x1041, &x1042, x1040, (@intCast(u32, x980) + @intCast(u32, x946)), (@intCast(u32, x1016) + x982)); var x1043: u32 = undefined; var x1044: u32 = undefined; fiatP384MulxU32(&x1043, &x1044, x11, 0x2); var x1045: u32 = undefined; var x1046: u32 = undefined; fiatP384MulxU32(&x1045, &x1046, x11, 0xfffffffe); var x1047: u32 = undefined; var x1048: u32 = undefined; fiatP384MulxU32(&x1047, &x1048, x11, 0x2); var x1049: u32 = undefined; var x1050: u32 = undefined; fiatP384MulxU32(&x1049, &x1050, x11, 0xfffffffe); var x1051: u32 = undefined; var x1052: u1 = undefined; fiatP384AddcarryxU32(&x1051, &x1052, 0x0, @intCast(u32, @intCast(u1, x1044)), x11); var x1053: u32 = undefined; var x1054: u1 = undefined; fiatP384AddcarryxU32(&x1053, &x1054, 0x0, x1019, x11); var x1055: u32 = undefined; var x1056: u1 = undefined; fiatP384AddcarryxU32(&x1055, &x1056, x1054, x1021, x1049); var x1057: u32 = undefined; var x1058: u1 = undefined; fiatP384AddcarryxU32(&x1057, &x1058, x1056, x1023, x1050); var x1059: u32 = undefined; var x1060: u1 = undefined; fiatP384AddcarryxU32(&x1059, &x1060, x1058, x1025, x1047); var x1061: u32 = undefined; var x1062: u1 = undefined; fiatP384AddcarryxU32(&x1061, &x1062, x1060, x1027, @intCast(u32, @intCast(u1, x1048))); var x1063: u32 = undefined; var x1064: u1 = undefined; fiatP384AddcarryxU32(&x1063, &x1064, x1062, x1029, x1045); var x1065: u32 = undefined; var x1066: u1 = undefined; fiatP384AddcarryxU32(&x1065, &x1066, x1064, x1031, x1046); var x1067: u32 = undefined; var x1068: u1 = undefined; fiatP384AddcarryxU32(&x1067, &x1068, x1066, x1033, x1043); var x1069: u32 = undefined; var x1070: u1 = undefined; fiatP384AddcarryxU32(&x1069, &x1070, x1068, x1035, x1051); var x1071: u32 = undefined; var x1072: u1 = undefined; fiatP384AddcarryxU32(&x1071, &x1072, x1070, x1037, @intCast(u32, x1052)); var x1073: u32 = undefined; var x1074: u1 = undefined; fiatP384AddcarryxU32(&x1073, &x1074, x1072, x1039, @intCast(u32, 0x0)); var x1075: u32 = undefined; var x1076: u1 = undefined; fiatP384AddcarryxU32(&x1075, &x1076, x1074, x1041, @intCast(u32, 0x0)); var x1077: u32 = undefined; var x1078: u32 = undefined; fiatP384MulxU32(&x1077, &x1078, x1053, 0xffffffff); var x1079: u32 = undefined; var x1080: u32 = undefined; fiatP384MulxU32(&x1079, &x1080, x1053, 0xffffffff); var x1081: u32 = undefined; var x1082: u32 = undefined; fiatP384MulxU32(&x1081, &x1082, x1053, 0xffffffff); var x1083: u32 = undefined; var x1084: u32 = undefined; fiatP384MulxU32(&x1083, &x1084, x1053, 0xffffffff); var x1085: u32 = undefined; var x1086: u32 = undefined; fiatP384MulxU32(&x1085, &x1086, x1053, 0xffffffff); var x1087: u32 = undefined; var x1088: u32 = undefined; fiatP384MulxU32(&x1087, &x1088, x1053, 0xffffffff); var x1089: u32 = undefined; var x1090: u32 = undefined; fiatP384MulxU32(&x1089, &x1090, x1053, 0xffffffff); var x1091: u32 = undefined; var x1092: u32 = undefined; fiatP384MulxU32(&x1091, &x1092, x1053, 0xfffffffe); var x1093: u32 = undefined; var x1094: u32 = undefined; fiatP384MulxU32(&x1093, &x1094, x1053, 0xffffffff); var x1095: u32 = undefined; var x1096: u32 = undefined; fiatP384MulxU32(&x1095, &x1096, x1053, 0xffffffff); var x1097: u32 = undefined; var x1098: u1 = undefined; fiatP384AddcarryxU32(&x1097, &x1098, 0x0, x1094, x1091); var x1099: u32 = undefined; var x1100: u1 = undefined; fiatP384AddcarryxU32(&x1099, &x1100, x1098, x1092, x1089); var x1101: u32 = undefined; var x1102: u1 = undefined; fiatP384AddcarryxU32(&x1101, &x1102, x1100, x1090, x1087); var x1103: u32 = undefined; var x1104: u1 = undefined; fiatP384AddcarryxU32(&x1103, &x1104, x1102, x1088, x1085); var x1105: u32 = undefined; var x1106: u1 = undefined; fiatP384AddcarryxU32(&x1105, &x1106, x1104, x1086, x1083); var x1107: u32 = undefined; var x1108: u1 = undefined; fiatP384AddcarryxU32(&x1107, &x1108, x1106, x1084, x1081); var x1109: u32 = undefined; var x1110: u1 = undefined; fiatP384AddcarryxU32(&x1109, &x1110, x1108, x1082, x1079); var x1111: u32 = undefined; var x1112: u1 = undefined; fiatP384AddcarryxU32(&x1111, &x1112, x1110, x1080, x1077); var x1113: u32 = undefined; var x1114: u1 = undefined; fiatP384AddcarryxU32(&x1113, &x1114, 0x0, x1053, x1095); var x1115: u32 = undefined; var x1116: u1 = undefined; fiatP384AddcarryxU32(&x1115, &x1116, x1114, x1055, x1096); var x1117: u32 = undefined; var x1118: u1 = undefined; fiatP384AddcarryxU32(&x1117, &x1118, x1116, x1057, @intCast(u32, 0x0)); var x1119: u32 = undefined; var x1120: u1 = undefined; fiatP384AddcarryxU32(&x1119, &x1120, x1118, x1059, x1093); var x1121: u32 = undefined; var x1122: u1 = undefined; fiatP384AddcarryxU32(&x1121, &x1122, x1120, x1061, x1097); var x1123: u32 = undefined; var x1124: u1 = undefined; fiatP384AddcarryxU32(&x1123, &x1124, x1122, x1063, x1099); var x1125: u32 = undefined; var x1126: u1 = undefined; fiatP384AddcarryxU32(&x1125, &x1126, x1124, x1065, x1101); var x1127: u32 = undefined; var x1128: u1 = undefined; fiatP384AddcarryxU32(&x1127, &x1128, x1126, x1067, x1103); var x1129: u32 = undefined; var x1130: u1 = undefined; fiatP384AddcarryxU32(&x1129, &x1130, x1128, x1069, x1105); var x1131: u32 = undefined; var x1132: u1 = undefined; fiatP384AddcarryxU32(&x1131, &x1132, x1130, x1071, x1107); var x1133: u32 = undefined; var x1134: u1 = undefined; fiatP384AddcarryxU32(&x1133, &x1134, x1132, x1073, x1109); var x1135: u32 = undefined; var x1136: u1 = undefined; fiatP384AddcarryxU32(&x1135, &x1136, x1134, x1075, x1111); var x1137: u32 = undefined; var x1138: u1 = undefined; fiatP384AddcarryxU32(&x1137, &x1138, x1136, (@intCast(u32, x1076) + @intCast(u32, x1042)), (@intCast(u32, x1112) + x1078)); var x1139: u32 = undefined; var x1140: u1 = undefined; fiatP384SubborrowxU32(&x1139, &x1140, 0x0, x1115, 0xffffffff); var x1141: u32 = undefined; var x1142: u1 = undefined; fiatP384SubborrowxU32(&x1141, &x1142, x1140, x1117, @intCast(u32, 0x0)); var x1143: u32 = undefined; var x1144: u1 = undefined; fiatP384SubborrowxU32(&x1143, &x1144, x1142, x1119, @intCast(u32, 0x0)); var x1145: u32 = undefined; var x1146: u1 = undefined; fiatP384SubborrowxU32(&x1145, &x1146, x1144, x1121, 0xffffffff); var x1147: u32 = undefined; var x1148: u1 = undefined; fiatP384SubborrowxU32(&x1147, &x1148, x1146, x1123, 0xfffffffe); var x1149: u32 = undefined; var x1150: u1 = undefined; fiatP384SubborrowxU32(&x1149, &x1150, x1148, x1125, 0xffffffff); var x1151: u32 = undefined; var x1152: u1 = undefined; fiatP384SubborrowxU32(&x1151, &x1152, x1150, x1127, 0xffffffff); var x1153: u32 = undefined; var x1154: u1 = undefined; fiatP384SubborrowxU32(&x1153, &x1154, x1152, x1129, 0xffffffff); var x1155: u32 = undefined; var x1156: u1 = undefined; fiatP384SubborrowxU32(&x1155, &x1156, x1154, x1131, 0xffffffff); var x1157: u32 = undefined; var x1158: u1 = undefined; fiatP384SubborrowxU32(&x1157, &x1158, x1156, x1133, 0xffffffff); var x1159: u32 = undefined; var x1160: u1 = undefined; fiatP384SubborrowxU32(&x1159, &x1160, x1158, x1135, 0xffffffff); var x1161: u32 = undefined; var x1162: u1 = undefined; fiatP384SubborrowxU32(&x1161, &x1162, x1160, x1137, 0xffffffff); var x1163: u32 = undefined; var x1164: u1 = undefined; fiatP384SubborrowxU32(&x1163, &x1164, x1162, @intCast(u32, x1138), @intCast(u32, 0x0)); var x1165: u32 = undefined; fiatP384CmovznzU32(&x1165, x1164, x1139, x1115); var x1166: u32 = undefined; fiatP384CmovznzU32(&x1166, x1164, x1141, x1117); var x1167: u32 = undefined; fiatP384CmovznzU32(&x1167, x1164, x1143, x1119); var x1168: u32 = undefined; fiatP384CmovznzU32(&x1168, x1164, x1145, x1121); var x1169: u32 = undefined; fiatP384CmovznzU32(&x1169, x1164, x1147, x1123); var x1170: u32 = undefined; fiatP384CmovznzU32(&x1170, x1164, x1149, x1125); var x1171: u32 = undefined; fiatP384CmovznzU32(&x1171, x1164, x1151, x1127); var x1172: u32 = undefined; fiatP384CmovznzU32(&x1172, x1164, x1153, x1129); var x1173: u32 = undefined; fiatP384CmovznzU32(&x1173, x1164, x1155, x1131); var x1174: u32 = undefined; fiatP384CmovznzU32(&x1174, x1164, x1157, x1133); var x1175: u32 = undefined; fiatP384CmovznzU32(&x1175, x1164, x1159, x1135); var x1176: u32 = undefined; fiatP384CmovznzU32(&x1176, x1164, x1161, x1137); out1[0] = x1165; out1[1] = x1166; out1[2] = x1167; out1[3] = x1168; out1[4] = x1169; out1[5] = x1170; out1[6] = x1171; out1[7] = x1172; out1[8] = x1173; out1[9] = x1174; out1[10] = x1175; out1[11] = x1176; } /// The function fiatP384Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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] pub fn fiatP384Nonzero(out1: *u32, arg1: [12]u32) void { const x1: u32 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | ((arg1[7]) | ((arg1[8]) | ((arg1[9]) | ((arg1[10]) | (arg1[11])))))))))))); out1.* = x1; } /// The function fiatP384Selectznz 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], [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], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Selectznz(out1: *[12]u32, arg1: u1, arg2: [12]u32, arg3: [12]u32) void { var x1: u32 = undefined; fiatP384CmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; fiatP384CmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; fiatP384CmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; fiatP384CmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; fiatP384CmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); var x6: u32 = undefined; fiatP384CmovznzU32(&x6, arg1, (arg2[5]), (arg3[5])); var x7: u32 = undefined; fiatP384CmovznzU32(&x7, arg1, (arg2[6]), (arg3[6])); var x8: u32 = undefined; fiatP384CmovznzU32(&x8, arg1, (arg2[7]), (arg3[7])); var x9: u32 = undefined; fiatP384CmovznzU32(&x9, arg1, (arg2[8]), (arg3[8])); var x10: u32 = undefined; fiatP384CmovznzU32(&x10, arg1, (arg2[9]), (arg3[9])); var x11: u32 = undefined; fiatP384CmovznzU32(&x11, arg1, (arg2[10]), (arg3[10])); var x12: u32 = undefined; fiatP384CmovznzU32(&x12, arg1, (arg2[11]), (arg3[11])); 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; out1[10] = x11; out1[11] = x12; } /// The function fiatP384ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..47] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// 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 ~> 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]] pub fn fiatP384ToBytes(out1: *[48]u8, arg1: [12]u32) void { const x1: u32 = (arg1[11]); const x2: u32 = (arg1[10]); const x3: u32 = (arg1[9]); const x4: u32 = (arg1[8]); const x5: u32 = (arg1[7]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[5]); const x8: u32 = (arg1[4]); const x9: u32 = (arg1[3]); const x10: u32 = (arg1[2]); const x11: u32 = (arg1[1]); const x12: u32 = (arg1[0]); const x13: u8 = @intCast(u8, (x12 & @intCast(u32, 0xff))); const x14: u32 = (x12 >> 8); const x15: u8 = @intCast(u8, (x14 & @intCast(u32, 0xff))); const x16: u32 = (x14 >> 8); const x17: u8 = @intCast(u8, (x16 & @intCast(u32, 0xff))); const x18: u8 = @intCast(u8, (x16 >> 8)); const x19: u8 = @intCast(u8, (x11 & @intCast(u32, 0xff))); const x20: u32 = (x11 >> 8); const x21: u8 = @intCast(u8, (x20 & @intCast(u32, 0xff))); const x22: u32 = (x20 >> 8); const x23: u8 = @intCast(u8, (x22 & @intCast(u32, 0xff))); const x24: u8 = @intCast(u8, (x22 >> 8)); const x25: u8 = @intCast(u8, (x10 & @intCast(u32, 0xff))); const x26: u32 = (x10 >> 8); const x27: u8 = @intCast(u8, (x26 & @intCast(u32, 0xff))); const x28: u32 = (x26 >> 8); const x29: u8 = @intCast(u8, (x28 & @intCast(u32, 0xff))); const x30: u8 = @intCast(u8, (x28 >> 8)); const x31: u8 = @intCast(u8, (x9 & @intCast(u32, 0xff))); const x32: u32 = (x9 >> 8); const x33: u8 = @intCast(u8, (x32 & @intCast(u32, 0xff))); const x34: u32 = (x32 >> 8); const x35: u8 = @intCast(u8, (x34 & @intCast(u32, 0xff))); const x36: u8 = @intCast(u8, (x34 >> 8)); const x37: u8 = @intCast(u8, (x8 & @intCast(u32, 0xff))); const x38: u32 = (x8 >> 8); const x39: u8 = @intCast(u8, (x38 & @intCast(u32, 0xff))); const x40: u32 = (x38 >> 8); const x41: u8 = @intCast(u8, (x40 & @intCast(u32, 0xff))); const x42: u8 = @intCast(u8, (x40 >> 8)); const x43: u8 = @intCast(u8, (x7 & @intCast(u32, 0xff))); const x44: u32 = (x7 >> 8); const x45: u8 = @intCast(u8, (x44 & @intCast(u32, 0xff))); const x46: u32 = (x44 >> 8); const x47: u8 = @intCast(u8, (x46 & @intCast(u32, 0xff))); const x48: u8 = @intCast(u8, (x46 >> 8)); const x49: u8 = @intCast(u8, (x6 & @intCast(u32, 0xff))); const x50: u32 = (x6 >> 8); const x51: u8 = @intCast(u8, (x50 & @intCast(u32, 0xff))); const x52: u32 = (x50 >> 8); const x53: u8 = @intCast(u8, (x52 & @intCast(u32, 0xff))); const x54: u8 = @intCast(u8, (x52 >> 8)); const x55: u8 = @intCast(u8, (x5 & @intCast(u32, 0xff))); const x56: u32 = (x5 >> 8); const x57: u8 = @intCast(u8, (x56 & @intCast(u32, 0xff))); const x58: u32 = (x56 >> 8); const x59: u8 = @intCast(u8, (x58 & @intCast(u32, 0xff))); const x60: u8 = @intCast(u8, (x58 >> 8)); const x61: u8 = @intCast(u8, (x4 & @intCast(u32, 0xff))); const x62: u32 = (x4 >> 8); const x63: u8 = @intCast(u8, (x62 & @intCast(u32, 0xff))); const x64: u32 = (x62 >> 8); const x65: u8 = @intCast(u8, (x64 & @intCast(u32, 0xff))); const x66: u8 = @intCast(u8, (x64 >> 8)); const x67: u8 = @intCast(u8, (x3 & @intCast(u32, 0xff))); const x68: u32 = (x3 >> 8); const x69: u8 = @intCast(u8, (x68 & @intCast(u32, 0xff))); const x70: u32 = (x68 >> 8); const x71: u8 = @intCast(u8, (x70 & @intCast(u32, 0xff))); const x72: u8 = @intCast(u8, (x70 >> 8)); const x73: u8 = @intCast(u8, (x2 & @intCast(u32, 0xff))); const x74: u32 = (x2 >> 8); const x75: u8 = @intCast(u8, (x74 & @intCast(u32, 0xff))); const x76: u32 = (x74 >> 8); const x77: u8 = @intCast(u8, (x76 & @intCast(u32, 0xff))); const x78: u8 = @intCast(u8, (x76 >> 8)); const x79: u8 = @intCast(u8, (x1 & @intCast(u32, 0xff))); const x80: u32 = (x1 >> 8); const x81: u8 = @intCast(u8, (x80 & @intCast(u32, 0xff))); const x82: u32 = (x80 >> 8); const x83: u8 = @intCast(u8, (x82 & @intCast(u32, 0xff))); const x84: u8 = @intCast(u8, (x82 >> 8)); out1[0] = x13; out1[1] = x15; out1[2] = x17; out1[3] = x18; out1[4] = x19; out1[5] = x21; out1[6] = x23; out1[7] = x24; out1[8] = x25; out1[9] = x27; out1[10] = x29; out1[11] = x30; out1[12] = x31; out1[13] = x33; out1[14] = x35; out1[15] = x36; out1[16] = x37; out1[17] = x39; out1[18] = x41; out1[19] = x42; out1[20] = x43; out1[21] = x45; out1[22] = x47; out1[23] = x48; out1[24] = x49; out1[25] = x51; out1[26] = x53; out1[27] = x54; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; out1[32] = x61; out1[33] = x63; out1[34] = x65; out1[35] = x66; out1[36] = x67; out1[37] = x69; out1[38] = x71; out1[39] = x72; out1[40] = x73; out1[41] = x75; out1[42] = x77; out1[43] = x78; out1[44] = x79; out1[45] = x81; out1[46] = x83; out1[47] = x84; } /// The function fiatP384FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < 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 ~> 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]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384FromBytes(out1: *[12]u32, arg1: [48]u8) void { const x1: u32 = (@intCast(u32, (arg1[47])) << 24); const x2: u32 = (@intCast(u32, (arg1[46])) << 16); const x3: u32 = (@intCast(u32, (arg1[45])) << 8); const x4: u8 = (arg1[44]); const x5: u32 = (@intCast(u32, (arg1[43])) << 24); const x6: u32 = (@intCast(u32, (arg1[42])) << 16); const x7: u32 = (@intCast(u32, (arg1[41])) << 8); const x8: u8 = (arg1[40]); const x9: u32 = (@intCast(u32, (arg1[39])) << 24); const x10: u32 = (@intCast(u32, (arg1[38])) << 16); const x11: u32 = (@intCast(u32, (arg1[37])) << 8); const x12: u8 = (arg1[36]); const x13: u32 = (@intCast(u32, (arg1[35])) << 24); const x14: u32 = (@intCast(u32, (arg1[34])) << 16); const x15: u32 = (@intCast(u32, (arg1[33])) << 8); const x16: u8 = (arg1[32]); const x17: u32 = (@intCast(u32, (arg1[31])) << 24); const x18: u32 = (@intCast(u32, (arg1[30])) << 16); const x19: u32 = (@intCast(u32, (arg1[29])) << 8); const x20: u8 = (arg1[28]); const x21: u32 = (@intCast(u32, (arg1[27])) << 24); const x22: u32 = (@intCast(u32, (arg1[26])) << 16); const x23: u32 = (@intCast(u32, (arg1[25])) << 8); const x24: u8 = (arg1[24]); const x25: u32 = (@intCast(u32, (arg1[23])) << 24); const x26: u32 = (@intCast(u32, (arg1[22])) << 16); const x27: u32 = (@intCast(u32, (arg1[21])) << 8); const x28: u8 = (arg1[20]); const x29: u32 = (@intCast(u32, (arg1[19])) << 24); const x30: u32 = (@intCast(u32, (arg1[18])) << 16); const x31: u32 = (@intCast(u32, (arg1[17])) << 8); const x32: u8 = (arg1[16]); const x33: u32 = (@intCast(u32, (arg1[15])) << 24); const x34: u32 = (@intCast(u32, (arg1[14])) << 16); const x35: u32 = (@intCast(u32, (arg1[13])) << 8); const x36: u8 = (arg1[12]); const x37: u32 = (@intCast(u32, (arg1[11])) << 24); const x38: u32 = (@intCast(u32, (arg1[10])) << 16); const x39: u32 = (@intCast(u32, (arg1[9])) << 8); const x40: u8 = (arg1[8]); const x41: u32 = (@intCast(u32, (arg1[7])) << 24); const x42: u32 = (@intCast(u32, (arg1[6])) << 16); const x43: u32 = (@intCast(u32, (arg1[5])) << 8); const x44: u8 = (arg1[4]); const x45: u32 = (@intCast(u32, (arg1[3])) << 24); const x46: u32 = (@intCast(u32, (arg1[2])) << 16); const x47: u32 = (@intCast(u32, (arg1[1])) << 8); const x48: u8 = (arg1[0]); const x49: u32 = (x47 + @intCast(u32, x48)); const x50: u32 = (x46 + x49); const x51: u32 = (x45 + x50); const x52: u32 = (x43 + @intCast(u32, x44)); const x53: u32 = (x42 + x52); const x54: u32 = (x41 + x53); const x55: u32 = (x39 + @intCast(u32, x40)); const x56: u32 = (x38 + x55); const x57: u32 = (x37 + x56); const x58: u32 = (x35 + @intCast(u32, x36)); const x59: u32 = (x34 + x58); const x60: u32 = (x33 + x59); const x61: u32 = (x31 + @intCast(u32, x32)); const x62: u32 = (x30 + x61); const x63: u32 = (x29 + x62); const x64: u32 = (x27 + @intCast(u32, x28)); const x65: u32 = (x26 + x64); const x66: u32 = (x25 + x65); const x67: u32 = (x23 + @intCast(u32, x24)); const x68: u32 = (x22 + x67); const x69: u32 = (x21 + x68); const x70: u32 = (x19 + @intCast(u32, x20)); const x71: u32 = (x18 + x70); const x72: u32 = (x17 + x71); const x73: u32 = (x15 + @intCast(u32, x16)); const x74: u32 = (x14 + x73); const x75: u32 = (x13 + x74); const x76: u32 = (x11 + @intCast(u32, x12)); const x77: u32 = (x10 + x76); const x78: u32 = (x9 + x77); const x79: u32 = (x7 + @intCast(u32, x8)); const x80: u32 = (x6 + x79); const x81: u32 = (x5 + x80); const x82: u32 = (x3 + @intCast(u32, x4)); const x83: u32 = (x2 + x82); const x84: u32 = (x1 + x83); out1[0] = x51; out1[1] = x54; out1[2] = x57; out1[3] = x60; out1[4] = x63; out1[5] = x66; out1[6] = x69; out1[7] = x72; out1[8] = x75; out1[9] = x78; out1[10] = x81; out1[11] = x84; } /// The function fiatP384SetOne returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384SetOne(out1: *[12]u32) void { out1[0] = @intCast(u32, 0x1); out1[1] = 0xffffffff; out1[2] = 0xffffffff; out1[3] = @intCast(u32, 0x0); out1[4] = @intCast(u32, 0x1); out1[5] = @intCast(u32, 0x0); out1[6] = @intCast(u32, 0x0); out1[7] = @intCast(u32, 0x0); out1[8] = @intCast(u32, 0x0); out1[9] = @intCast(u32, 0x0); out1[10] = @intCast(u32, 0x0); out1[11] = @intCast(u32, 0x0); } /// The function fiatP384Msat returns the saturated representation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Msat(out1: *[13]u32) void { out1[0] = 0xffffffff; out1[1] = @intCast(u32, 0x0); out1[2] = @intCast(u32, 0x0); out1[3] = 0xffffffff; out1[4] = 0xfffffffe; out1[5] = 0xffffffff; out1[6] = 0xffffffff; out1[7] = 0xffffffff; out1[8] = 0xffffffff; out1[9] = 0xffffffff; out1[10] = 0xffffffff; out1[11] = 0xffffffff; out1[12] = @intCast(u32, 0x0); } /// The function fiatP384Divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [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] /// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384Divstep(out1: *u32, out2: *[13]u32, out3: *[13]u32, out4: *[12]u32, out5: *[12]u32, arg1: u32, arg2: [13]u32, arg3: [13]u32, arg4: [12]u32, arg5: [12]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatP384AddcarryxU32(&x1, &x2, 0x0, (~arg1), @intCast(u32, 0x1)); const x3: u1 = (@intCast(u1, (x1 >> 31)) & @intCast(u1, ((arg3[0]) & @intCast(u32, 0x1)))); var x4: u32 = undefined; var x5: u1 = undefined; fiatP384AddcarryxU32(&x4, &x5, 0x0, (~arg1), @intCast(u32, 0x1)); var x6: u32 = undefined; fiatP384CmovznzU32(&x6, x3, arg1, x4); var x7: u32 = undefined; fiatP384CmovznzU32(&x7, x3, (arg2[0]), (arg3[0])); var x8: u32 = undefined; fiatP384CmovznzU32(&x8, x3, (arg2[1]), (arg3[1])); var x9: u32 = undefined; fiatP384CmovznzU32(&x9, x3, (arg2[2]), (arg3[2])); var x10: u32 = undefined; fiatP384CmovznzU32(&x10, x3, (arg2[3]), (arg3[3])); var x11: u32 = undefined; fiatP384CmovznzU32(&x11, x3, (arg2[4]), (arg3[4])); var x12: u32 = undefined; fiatP384CmovznzU32(&x12, x3, (arg2[5]), (arg3[5])); var x13: u32 = undefined; fiatP384CmovznzU32(&x13, x3, (arg2[6]), (arg3[6])); var x14: u32 = undefined; fiatP384CmovznzU32(&x14, x3, (arg2[7]), (arg3[7])); var x15: u32 = undefined; fiatP384CmovznzU32(&x15, x3, (arg2[8]), (arg3[8])); var x16: u32 = undefined; fiatP384CmovznzU32(&x16, x3, (arg2[9]), (arg3[9])); var x17: u32 = undefined; fiatP384CmovznzU32(&x17, x3, (arg2[10]), (arg3[10])); var x18: u32 = undefined; fiatP384CmovznzU32(&x18, x3, (arg2[11]), (arg3[11])); var x19: u32 = undefined; fiatP384CmovznzU32(&x19, x3, (arg2[12]), (arg3[12])); var x20: u32 = undefined; var x21: u1 = undefined; fiatP384AddcarryxU32(&x20, &x21, 0x0, @intCast(u32, 0x1), (~(arg2[0]))); var x22: u32 = undefined; var x23: u1 = undefined; fiatP384AddcarryxU32(&x22, &x23, x21, @intCast(u32, 0x0), (~(arg2[1]))); var x24: u32 = undefined; var x25: u1 = undefined; fiatP384AddcarryxU32(&x24, &x25, x23, @intCast(u32, 0x0), (~(arg2[2]))); var x26: u32 = undefined; var x27: u1 = undefined; fiatP384AddcarryxU32(&x26, &x27, x25, @intCast(u32, 0x0), (~(arg2[3]))); var x28: u32 = undefined; var x29: u1 = undefined; fiatP384AddcarryxU32(&x28, &x29, x27, @intCast(u32, 0x0), (~(arg2[4]))); var x30: u32 = undefined; var x31: u1 = undefined; fiatP384AddcarryxU32(&x30, &x31, x29, @intCast(u32, 0x0), (~(arg2[5]))); var x32: u32 = undefined; var x33: u1 = undefined; fiatP384AddcarryxU32(&x32, &x33, x31, @intCast(u32, 0x0), (~(arg2[6]))); var x34: u32 = undefined; var x35: u1 = undefined; fiatP384AddcarryxU32(&x34, &x35, x33, @intCast(u32, 0x0), (~(arg2[7]))); var x36: u32 = undefined; var x37: u1 = undefined; fiatP384AddcarryxU32(&x36, &x37, x35, @intCast(u32, 0x0), (~(arg2[8]))); var x38: u32 = undefined; var x39: u1 = undefined; fiatP384AddcarryxU32(&x38, &x39, x37, @intCast(u32, 0x0), (~(arg2[9]))); var x40: u32 = undefined; var x41: u1 = undefined; fiatP384AddcarryxU32(&x40, &x41, x39, @intCast(u32, 0x0), (~(arg2[10]))); var x42: u32 = undefined; var x43: u1 = undefined; fiatP384AddcarryxU32(&x42, &x43, x41, @intCast(u32, 0x0), (~(arg2[11]))); var x44: u32 = undefined; var x45: u1 = undefined; fiatP384AddcarryxU32(&x44, &x45, x43, @intCast(u32, 0x0), (~(arg2[12]))); var x46: u32 = undefined; fiatP384CmovznzU32(&x46, x3, (arg3[0]), x20); var x47: u32 = undefined; fiatP384CmovznzU32(&x47, x3, (arg3[1]), x22); var x48: u32 = undefined; fiatP384CmovznzU32(&x48, x3, (arg3[2]), x24); var x49: u32 = undefined; fiatP384CmovznzU32(&x49, x3, (arg3[3]), x26); var x50: u32 = undefined; fiatP384CmovznzU32(&x50, x3, (arg3[4]), x28); var x51: u32 = undefined; fiatP384CmovznzU32(&x51, x3, (arg3[5]), x30); var x52: u32 = undefined; fiatP384CmovznzU32(&x52, x3, (arg3[6]), x32); var x53: u32 = undefined; fiatP384CmovznzU32(&x53, x3, (arg3[7]), x34); var x54: u32 = undefined; fiatP384CmovznzU32(&x54, x3, (arg3[8]), x36); var x55: u32 = undefined; fiatP384CmovznzU32(&x55, x3, (arg3[9]), x38); var x56: u32 = undefined; fiatP384CmovznzU32(&x56, x3, (arg3[10]), x40); var x57: u32 = undefined; fiatP384CmovznzU32(&x57, x3, (arg3[11]), x42); var x58: u32 = undefined; fiatP384CmovznzU32(&x58, x3, (arg3[12]), x44); var x59: u32 = undefined; fiatP384CmovznzU32(&x59, x3, (arg4[0]), (arg5[0])); var x60: u32 = undefined; fiatP384CmovznzU32(&x60, x3, (arg4[1]), (arg5[1])); var x61: u32 = undefined; fiatP384CmovznzU32(&x61, x3, (arg4[2]), (arg5[2])); var x62: u32 = undefined; fiatP384CmovznzU32(&x62, x3, (arg4[3]), (arg5[3])); var x63: u32 = undefined; fiatP384CmovznzU32(&x63, x3, (arg4[4]), (arg5[4])); var x64: u32 = undefined; fiatP384CmovznzU32(&x64, x3, (arg4[5]), (arg5[5])); var x65: u32 = undefined; fiatP384CmovznzU32(&x65, x3, (arg4[6]), (arg5[6])); var x66: u32 = undefined; fiatP384CmovznzU32(&x66, x3, (arg4[7]), (arg5[7])); var x67: u32 = undefined; fiatP384CmovznzU32(&x67, x3, (arg4[8]), (arg5[8])); var x68: u32 = undefined; fiatP384CmovznzU32(&x68, x3, (arg4[9]), (arg5[9])); var x69: u32 = undefined; fiatP384CmovznzU32(&x69, x3, (arg4[10]), (arg5[10])); var x70: u32 = undefined; fiatP384CmovznzU32(&x70, x3, (arg4[11]), (arg5[11])); var x71: u32 = undefined; var x72: u1 = undefined; fiatP384AddcarryxU32(&x71, &x72, 0x0, x59, x59); var x73: u32 = undefined; var x74: u1 = undefined; fiatP384AddcarryxU32(&x73, &x74, x72, x60, x60); var x75: u32 = undefined; var x76: u1 = undefined; fiatP384AddcarryxU32(&x75, &x76, x74, x61, x61); var x77: u32 = undefined; var x78: u1 = undefined; fiatP384AddcarryxU32(&x77, &x78, x76, x62, x62); var x79: u32 = undefined; var x80: u1 = undefined; fiatP384AddcarryxU32(&x79, &x80, x78, x63, x63); var x81: u32 = undefined; var x82: u1 = undefined; fiatP384AddcarryxU32(&x81, &x82, x80, x64, x64); var x83: u32 = undefined; var x84: u1 = undefined; fiatP384AddcarryxU32(&x83, &x84, x82, x65, x65); var x85: u32 = undefined; var x86: u1 = undefined; fiatP384AddcarryxU32(&x85, &x86, x84, x66, x66); var x87: u32 = undefined; var x88: u1 = undefined; fiatP384AddcarryxU32(&x87, &x88, x86, x67, x67); var x89: u32 = undefined; var x90: u1 = undefined; fiatP384AddcarryxU32(&x89, &x90, x88, x68, x68); var x91: u32 = undefined; var x92: u1 = undefined; fiatP384AddcarryxU32(&x91, &x92, x90, x69, x69); var x93: u32 = undefined; var x94: u1 = undefined; fiatP384AddcarryxU32(&x93, &x94, x92, x70, x70); var x95: u32 = undefined; var x96: u1 = undefined; fiatP384SubborrowxU32(&x95, &x96, 0x0, x71, 0xffffffff); var x97: u32 = undefined; var x98: u1 = undefined; fiatP384SubborrowxU32(&x97, &x98, x96, x73, @intCast(u32, 0x0)); var x99: u32 = undefined; var x100: u1 = undefined; fiatP384SubborrowxU32(&x99, &x100, x98, x75, @intCast(u32, 0x0)); var x101: u32 = undefined; var x102: u1 = undefined; fiatP384SubborrowxU32(&x101, &x102, x100, x77, 0xffffffff); var x103: u32 = undefined; var x104: u1 = undefined; fiatP384SubborrowxU32(&x103, &x104, x102, x79, 0xfffffffe); var x105: u32 = undefined; var x106: u1 = undefined; fiatP384SubborrowxU32(&x105, &x106, x104, x81, 0xffffffff); var x107: u32 = undefined; var x108: u1 = undefined; fiatP384SubborrowxU32(&x107, &x108, x106, x83, 0xffffffff); var x109: u32 = undefined; var x110: u1 = undefined; fiatP384SubborrowxU32(&x109, &x110, x108, x85, 0xffffffff); var x111: u32 = undefined; var x112: u1 = undefined; fiatP384SubborrowxU32(&x111, &x112, x110, x87, 0xffffffff); var x113: u32 = undefined; var x114: u1 = undefined; fiatP384SubborrowxU32(&x113, &x114, x112, x89, 0xffffffff); var x115: u32 = undefined; var x116: u1 = undefined; fiatP384SubborrowxU32(&x115, &x116, x114, x91, 0xffffffff); var x117: u32 = undefined; var x118: u1 = undefined; fiatP384SubborrowxU32(&x117, &x118, x116, x93, 0xffffffff); var x119: u32 = undefined; var x120: u1 = undefined; fiatP384SubborrowxU32(&x119, &x120, x118, @intCast(u32, x94), @intCast(u32, 0x0)); const x121: u32 = (arg4[11]); const x122: u32 = (arg4[10]); const x123: u32 = (arg4[9]); const x124: u32 = (arg4[8]); const x125: u32 = (arg4[7]); const x126: u32 = (arg4[6]); const x127: u32 = (arg4[5]); const x128: u32 = (arg4[4]); const x129: u32 = (arg4[3]); const x130: u32 = (arg4[2]); const x131: u32 = (arg4[1]); const x132: u32 = (arg4[0]); var x133: u32 = undefined; var x134: u1 = undefined; fiatP384SubborrowxU32(&x133, &x134, 0x0, @intCast(u32, 0x0), x132); var x135: u32 = undefined; var x136: u1 = undefined; fiatP384SubborrowxU32(&x135, &x136, x134, @intCast(u32, 0x0), x131); var x137: u32 = undefined; var x138: u1 = undefined; fiatP384SubborrowxU32(&x137, &x138, x136, @intCast(u32, 0x0), x130); var x139: u32 = undefined; var x140: u1 = undefined; fiatP384SubborrowxU32(&x139, &x140, x138, @intCast(u32, 0x0), x129); var x141: u32 = undefined; var x142: u1 = undefined; fiatP384SubborrowxU32(&x141, &x142, x140, @intCast(u32, 0x0), x128); var x143: u32 = undefined; var x144: u1 = undefined; fiatP384SubborrowxU32(&x143, &x144, x142, @intCast(u32, 0x0), x127); var x145: u32 = undefined; var x146: u1 = undefined; fiatP384SubborrowxU32(&x145, &x146, x144, @intCast(u32, 0x0), x126); var x147: u32 = undefined; var x148: u1 = undefined; fiatP384SubborrowxU32(&x147, &x148, x146, @intCast(u32, 0x0), x125); var x149: u32 = undefined; var x150: u1 = undefined; fiatP384SubborrowxU32(&x149, &x150, x148, @intCast(u32, 0x0), x124); var x151: u32 = undefined; var x152: u1 = undefined; fiatP384SubborrowxU32(&x151, &x152, x150, @intCast(u32, 0x0), x123); var x153: u32 = undefined; var x154: u1 = undefined; fiatP384SubborrowxU32(&x153, &x154, x152, @intCast(u32, 0x0), x122); var x155: u32 = undefined; var x156: u1 = undefined; fiatP384SubborrowxU32(&x155, &x156, x154, @intCast(u32, 0x0), x121); var x157: u32 = undefined; fiatP384CmovznzU32(&x157, x156, @intCast(u32, 0x0), 0xffffffff); var x158: u32 = undefined; var x159: u1 = undefined; fiatP384AddcarryxU32(&x158, &x159, 0x0, x133, x157); var x160: u32 = undefined; var x161: u1 = undefined; fiatP384AddcarryxU32(&x160, &x161, x159, x135, @intCast(u32, 0x0)); var x162: u32 = undefined; var x163: u1 = undefined; fiatP384AddcarryxU32(&x162, &x163, x161, x137, @intCast(u32, 0x0)); var x164: u32 = undefined; var x165: u1 = undefined; fiatP384AddcarryxU32(&x164, &x165, x163, x139, x157); var x166: u32 = undefined; var x167: u1 = undefined; fiatP384AddcarryxU32(&x166, &x167, x165, x141, (x157 & 0xfffffffe)); var x168: u32 = undefined; var x169: u1 = undefined; fiatP384AddcarryxU32(&x168, &x169, x167, x143, x157); var x170: u32 = undefined; var x171: u1 = undefined; fiatP384AddcarryxU32(&x170, &x171, x169, x145, x157); var x172: u32 = undefined; var x173: u1 = undefined; fiatP384AddcarryxU32(&x172, &x173, x171, x147, x157); var x174: u32 = undefined; var x175: u1 = undefined; fiatP384AddcarryxU32(&x174, &x175, x173, x149, x157); var x176: u32 = undefined; var x177: u1 = undefined; fiatP384AddcarryxU32(&x176, &x177, x175, x151, x157); var x178: u32 = undefined; var x179: u1 = undefined; fiatP384AddcarryxU32(&x178, &x179, x177, x153, x157); var x180: u32 = undefined; var x181: u1 = undefined; fiatP384AddcarryxU32(&x180, &x181, x179, x155, x157); var x182: u32 = undefined; fiatP384CmovznzU32(&x182, x3, (arg5[0]), x158); var x183: u32 = undefined; fiatP384CmovznzU32(&x183, x3, (arg5[1]), x160); var x184: u32 = undefined; fiatP384CmovznzU32(&x184, x3, (arg5[2]), x162); var x185: u32 = undefined; fiatP384CmovznzU32(&x185, x3, (arg5[3]), x164); var x186: u32 = undefined; fiatP384CmovznzU32(&x186, x3, (arg5[4]), x166); var x187: u32 = undefined; fiatP384CmovznzU32(&x187, x3, (arg5[5]), x168); var x188: u32 = undefined; fiatP384CmovznzU32(&x188, x3, (arg5[6]), x170); var x189: u32 = undefined; fiatP384CmovznzU32(&x189, x3, (arg5[7]), x172); var x190: u32 = undefined; fiatP384CmovznzU32(&x190, x3, (arg5[8]), x174); var x191: u32 = undefined; fiatP384CmovznzU32(&x191, x3, (arg5[9]), x176); var x192: u32 = undefined; fiatP384CmovznzU32(&x192, x3, (arg5[10]), x178); var x193: u32 = undefined; fiatP384CmovznzU32(&x193, x3, (arg5[11]), x180); const x194: u1 = @intCast(u1, (x46 & @intCast(u32, 0x1))); var x195: u32 = undefined; fiatP384CmovznzU32(&x195, x194, @intCast(u32, 0x0), x7); var x196: u32 = undefined; fiatP384CmovznzU32(&x196, x194, @intCast(u32, 0x0), x8); var x197: u32 = undefined; fiatP384CmovznzU32(&x197, x194, @intCast(u32, 0x0), x9); var x198: u32 = undefined; fiatP384CmovznzU32(&x198, x194, @intCast(u32, 0x0), x10); var x199: u32 = undefined; fiatP384CmovznzU32(&x199, x194, @intCast(u32, 0x0), x11); var x200: u32 = undefined; fiatP384CmovznzU32(&x200, x194, @intCast(u32, 0x0), x12); var x201: u32 = undefined; fiatP384CmovznzU32(&x201, x194, @intCast(u32, 0x0), x13); var x202: u32 = undefined; fiatP384CmovznzU32(&x202, x194, @intCast(u32, 0x0), x14); var x203: u32 = undefined; fiatP384CmovznzU32(&x203, x194, @intCast(u32, 0x0), x15); var x204: u32 = undefined; fiatP384CmovznzU32(&x204, x194, @intCast(u32, 0x0), x16); var x205: u32 = undefined; fiatP384CmovznzU32(&x205, x194, @intCast(u32, 0x0), x17); var x206: u32 = undefined; fiatP384CmovznzU32(&x206, x194, @intCast(u32, 0x0), x18); var x207: u32 = undefined; fiatP384CmovznzU32(&x207, x194, @intCast(u32, 0x0), x19); var x208: u32 = undefined; var x209: u1 = undefined; fiatP384AddcarryxU32(&x208, &x209, 0x0, x46, x195); var x210: u32 = undefined; var x211: u1 = undefined; fiatP384AddcarryxU32(&x210, &x211, x209, x47, x196); var x212: u32 = undefined; var x213: u1 = undefined; fiatP384AddcarryxU32(&x212, &x213, x211, x48, x197); var x214: u32 = undefined; var x215: u1 = undefined; fiatP384AddcarryxU32(&x214, &x215, x213, x49, x198); var x216: u32 = undefined; var x217: u1 = undefined; fiatP384AddcarryxU32(&x216, &x217, x215, x50, x199); var x218: u32 = undefined; var x219: u1 = undefined; fiatP384AddcarryxU32(&x218, &x219, x217, x51, x200); var x220: u32 = undefined; var x221: u1 = undefined; fiatP384AddcarryxU32(&x220, &x221, x219, x52, x201); var x222: u32 = undefined; var x223: u1 = undefined; fiatP384AddcarryxU32(&x222, &x223, x221, x53, x202); var x224: u32 = undefined; var x225: u1 = undefined; fiatP384AddcarryxU32(&x224, &x225, x223, x54, x203); var x226: u32 = undefined; var x227: u1 = undefined; fiatP384AddcarryxU32(&x226, &x227, x225, x55, x204); var x228: u32 = undefined; var x229: u1 = undefined; fiatP384AddcarryxU32(&x228, &x229, x227, x56, x205); var x230: u32 = undefined; var x231: u1 = undefined; fiatP384AddcarryxU32(&x230, &x231, x229, x57, x206); var x232: u32 = undefined; var x233: u1 = undefined; fiatP384AddcarryxU32(&x232, &x233, x231, x58, x207); var x234: u32 = undefined; fiatP384CmovznzU32(&x234, x194, @intCast(u32, 0x0), x59); var x235: u32 = undefined; fiatP384CmovznzU32(&x235, x194, @intCast(u32, 0x0), x60); var x236: u32 = undefined; fiatP384CmovznzU32(&x236, x194, @intCast(u32, 0x0), x61); var x237: u32 = undefined; fiatP384CmovznzU32(&x237, x194, @intCast(u32, 0x0), x62); var x238: u32 = undefined; fiatP384CmovznzU32(&x238, x194, @intCast(u32, 0x0), x63); var x239: u32 = undefined; fiatP384CmovznzU32(&x239, x194, @intCast(u32, 0x0), x64); var x240: u32 = undefined; fiatP384CmovznzU32(&x240, x194, @intCast(u32, 0x0), x65); var x241: u32 = undefined; fiatP384CmovznzU32(&x241, x194, @intCast(u32, 0x0), x66); var x242: u32 = undefined; fiatP384CmovznzU32(&x242, x194, @intCast(u32, 0x0), x67); var x243: u32 = undefined; fiatP384CmovznzU32(&x243, x194, @intCast(u32, 0x0), x68); var x244: u32 = undefined; fiatP384CmovznzU32(&x244, x194, @intCast(u32, 0x0), x69); var x245: u32 = undefined; fiatP384CmovznzU32(&x245, x194, @intCast(u32, 0x0), x70); var x246: u32 = undefined; var x247: u1 = undefined; fiatP384AddcarryxU32(&x246, &x247, 0x0, x182, x234); var x248: u32 = undefined; var x249: u1 = undefined; fiatP384AddcarryxU32(&x248, &x249, x247, x183, x235); var x250: u32 = undefined; var x251: u1 = undefined; fiatP384AddcarryxU32(&x250, &x251, x249, x184, x236); var x252: u32 = undefined; var x253: u1 = undefined; fiatP384AddcarryxU32(&x252, &x253, x251, x185, x237); var x254: u32 = undefined; var x255: u1 = undefined; fiatP384AddcarryxU32(&x254, &x255, x253, x186, x238); var x256: u32 = undefined; var x257: u1 = undefined; fiatP384AddcarryxU32(&x256, &x257, x255, x187, x239); var x258: u32 = undefined; var x259: u1 = undefined; fiatP384AddcarryxU32(&x258, &x259, x257, x188, x240); var x260: u32 = undefined; var x261: u1 = undefined; fiatP384AddcarryxU32(&x260, &x261, x259, x189, x241); var x262: u32 = undefined; var x263: u1 = undefined; fiatP384AddcarryxU32(&x262, &x263, x261, x190, x242); var x264: u32 = undefined; var x265: u1 = undefined; fiatP384AddcarryxU32(&x264, &x265, x263, x191, x243); var x266: u32 = undefined; var x267: u1 = undefined; fiatP384AddcarryxU32(&x266, &x267, x265, x192, x244); var x268: u32 = undefined; var x269: u1 = undefined; fiatP384AddcarryxU32(&x268, &x269, x267, x193, x245); var x270: u32 = undefined; var x271: u1 = undefined; fiatP384SubborrowxU32(&x270, &x271, 0x0, x246, 0xffffffff); var x272: u32 = undefined; var x273: u1 = undefined; fiatP384SubborrowxU32(&x272, &x273, x271, x248, @intCast(u32, 0x0)); var x274: u32 = undefined; var x275: u1 = undefined; fiatP384SubborrowxU32(&x274, &x275, x273, x250, @intCast(u32, 0x0)); var x276: u32 = undefined; var x277: u1 = undefined; fiatP384SubborrowxU32(&x276, &x277, x275, x252, 0xffffffff); var x278: u32 = undefined; var x279: u1 = undefined; fiatP384SubborrowxU32(&x278, &x279, x277, x254, 0xfffffffe); var x280: u32 = undefined; var x281: u1 = undefined; fiatP384SubborrowxU32(&x280, &x281, x279, x256, 0xffffffff); var x282: u32 = undefined; var x283: u1 = undefined; fiatP384SubborrowxU32(&x282, &x283, x281, x258, 0xffffffff); var x284: u32 = undefined; var x285: u1 = undefined; fiatP384SubborrowxU32(&x284, &x285, x283, x260, 0xffffffff); var x286: u32 = undefined; var x287: u1 = undefined; fiatP384SubborrowxU32(&x286, &x287, x285, x262, 0xffffffff); var x288: u32 = undefined; var x289: u1 = undefined; fiatP384SubborrowxU32(&x288, &x289, x287, x264, 0xffffffff); var x290: u32 = undefined; var x291: u1 = undefined; fiatP384SubborrowxU32(&x290, &x291, x289, x266, 0xffffffff); var x292: u32 = undefined; var x293: u1 = undefined; fiatP384SubborrowxU32(&x292, &x293, x291, x268, 0xffffffff); var x294: u32 = undefined; var x295: u1 = undefined; fiatP384SubborrowxU32(&x294, &x295, x293, @intCast(u32, x269), @intCast(u32, 0x0)); var x296: u32 = undefined; var x297: u1 = undefined; fiatP384AddcarryxU32(&x296, &x297, 0x0, x6, @intCast(u32, 0x1)); const x298: u32 = ((x208 >> 1) | ((x210 << 31) & 0xffffffff)); const x299: u32 = ((x210 >> 1) | ((x212 << 31) & 0xffffffff)); const x300: u32 = ((x212 >> 1) | ((x214 << 31) & 0xffffffff)); const x301: u32 = ((x214 >> 1) | ((x216 << 31) & 0xffffffff)); const x302: u32 = ((x216 >> 1) | ((x218 << 31) & 0xffffffff)); const x303: u32 = ((x218 >> 1) | ((x220 << 31) & 0xffffffff)); const x304: u32 = ((x220 >> 1) | ((x222 << 31) & 0xffffffff)); const x305: u32 = ((x222 >> 1) | ((x224 << 31) & 0xffffffff)); const x306: u32 = ((x224 >> 1) | ((x226 << 31) & 0xffffffff)); const x307: u32 = ((x226 >> 1) | ((x228 << 31) & 0xffffffff)); const x308: u32 = ((x228 >> 1) | ((x230 << 31) & 0xffffffff)); const x309: u32 = ((x230 >> 1) | ((x232 << 31) & 0xffffffff)); const x310: u32 = ((x232 & 0x80000000) | (x232 >> 1)); var x311: u32 = undefined; fiatP384CmovznzU32(&x311, x120, x95, x71); var x312: u32 = undefined; fiatP384CmovznzU32(&x312, x120, x97, x73); var x313: u32 = undefined; fiatP384CmovznzU32(&x313, x120, x99, x75); var x314: u32 = undefined; fiatP384CmovznzU32(&x314, x120, x101, x77); var x315: u32 = undefined; fiatP384CmovznzU32(&x315, x120, x103, x79); var x316: u32 = undefined; fiatP384CmovznzU32(&x316, x120, x105, x81); var x317: u32 = undefined; fiatP384CmovznzU32(&x317, x120, x107, x83); var x318: u32 = undefined; fiatP384CmovznzU32(&x318, x120, x109, x85); var x319: u32 = undefined; fiatP384CmovznzU32(&x319, x120, x111, x87); var x320: u32 = undefined; fiatP384CmovznzU32(&x320, x120, x113, x89); var x321: u32 = undefined; fiatP384CmovznzU32(&x321, x120, x115, x91); var x322: u32 = undefined; fiatP384CmovznzU32(&x322, x120, x117, x93); var x323: u32 = undefined; fiatP384CmovznzU32(&x323, x295, x270, x246); var x324: u32 = undefined; fiatP384CmovznzU32(&x324, x295, x272, x248); var x325: u32 = undefined; fiatP384CmovznzU32(&x325, x295, x274, x250); var x326: u32 = undefined; fiatP384CmovznzU32(&x326, x295, x276, x252); var x327: u32 = undefined; fiatP384CmovznzU32(&x327, x295, x278, x254); var x328: u32 = undefined; fiatP384CmovznzU32(&x328, x295, x280, x256); var x329: u32 = undefined; fiatP384CmovznzU32(&x329, x295, x282, x258); var x330: u32 = undefined; fiatP384CmovznzU32(&x330, x295, x284, x260); var x331: u32 = undefined; fiatP384CmovznzU32(&x331, x295, x286, x262); var x332: u32 = undefined; fiatP384CmovznzU32(&x332, x295, x288, x264); var x333: u32 = undefined; fiatP384CmovznzU32(&x333, x295, x290, x266); var x334: u32 = undefined; fiatP384CmovznzU32(&x334, x295, x292, x268); out1.* = x296; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out2[8] = x15; out2[9] = x16; out2[10] = x17; out2[11] = x18; out2[12] = x19; out3[0] = x298; out3[1] = x299; out3[2] = x300; out3[3] = x301; out3[4] = x302; out3[5] = x303; out3[6] = x304; out3[7] = x305; out3[8] = x306; out3[9] = x307; out3[10] = x308; out3[11] = x309; out3[12] = x310; out4[0] = x311; out4[1] = x312; out4[2] = x313; out4[3] = x314; out4[4] = x315; out4[5] = x316; out4[6] = x317; out4[7] = x318; out4[8] = x319; out4[9] = x320; out4[10] = x321; out4[11] = x322; out5[0] = x323; out5[1] = x324; out5[2] = x325; out5[3] = x326; out5[4] = x327; out5[5] = x328; out5[6] = x329; out5[7] = x330; out5[8] = x331; out5[9] = x332; out5[10] = x333; out5[11] = x334; } /// The function fiatP384DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP384DivstepPrecomp(out1: *[12]u32) void { out1[0] = 0xfff18fff; out1[1] = 0xfff69400; out1[2] = 0xffffd3ff; out1[3] = 0x2b7fe; out1[4] = 0xfffe97ff; out1[5] = 0xfffedbff; out1[6] = 0x2fff; out1[7] = 0x28400; out1[8] = 0x50400; out1[9] = 0x60400; out1[10] = 0x38000; out1[11] = 0xfffc4800; }
fiat-zig/src/p384_32.zig
const utils = @import("utils"); const kernel = @import("root").kernel; const print = kernel.print; const memory = kernel.memory; const platform = @import("platform.zig"); const util = @import("util.zig"); const timing = @import("timing.zig"); const c = @cImport({ @cInclude("georgios_bios_int.h"); }); pub const Error = error { BiosIntCallFailed, }; pub const Params = struct { interrupt: u8, eax: u32, ebx: u32 = 0, ecx: u32 = 0, edx: u32 = 0, edi: u32 = 0, slow: bool = false, }; const debug_io_access = false; const debug_mem_access = false; const exec_trace = false; export fn georgios_bios_int_to_string( buffer: [*]u8, buffer_size: usize, got: *usize, kind: u8, value: *anyopaque) bool { var ts = utils.ToString{.buffer = buffer[0..buffer_size]}; switch (kind) { 's' => { ts.cstring(@ptrCast([*:0]const u8, value)) catch return true; }, 'x' => { var v: usize = undefined; utils.memory_copy_anyptr(utils.to_bytes(&v), value); ts.hex(v) catch return true; }, else => { print.format("georgios_bios_to_string: Unexpected kind {:c}\n", .{kind}); }, } got.* = ts.got; return false; } export fn georgios_bios_int_print_string(str: [*:0]const u8) void { var i: usize = 0; while (str[i] != 0) { print.char(str[i]); i += 1; } } export fn georgios_bios_int_print_value(value: u32) void { print.hex(value); } export fn georgios_bios_int_wait() void { timing.wait_microseconds(500); } export fn georgios_bios_int_malloc(size: usize) ?*anyopaque { const a = kernel.alloc.alloc_array(u8, size) catch return null; return @ptrCast(*anyopaque, a.ptr); } export fn georgios_bios_int_calloc(num: usize, size: usize) ?*anyopaque { const a = kernel.alloc.alloc_array(u8, size * num) catch return null; utils.memory_set(a, 0); return @ptrCast(*anyopaque, a.ptr); } export fn georgios_bios_int_free(ptr: ?*anyopaque) void { if (ptr != null) { kernel.alloc.free_array(utils.make_const_slice(u8, @ptrCast([*]u8, ptr), 0)) catch {}; } } export fn georgios_bios_int_strcat(dest: [*c]u8, src: [*c]const u8) [*c]u8 { var dest_i: usize = 0; while (dest[dest_i] != 0) { dest_i += 1; } var src_i: usize = 0; while (src[src_i] != 0) { dest[dest_i] = src[src_i]; dest_i += 1; src_i += 1; } dest[dest_i] = 0; return dest; } // For Access to I/O Ports export fn georgios_bios_int_inb(port: u16) callconv(.C) u8 { if (debug_io_access) print.format("georgios_bios_int_inb {:x}\n", .{port}); return util.in8(port); } export fn georgios_bios_int_inw(port: u16) callconv(.C) u16 { if (debug_io_access) print.format("georgios_bios_int_inw {:x}\n", .{port}); return util.in16(port); } export fn georgios_bios_int_inl(port: u16) callconv(.C) u32 { if (debug_io_access) print.format("georgios_bios_int_inl {:x}\n", .{port}); return util.in32(port); } export fn georgios_bios_int_outb(port: u16, value: u8) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outb {:x}, {:x}\n", .{port, value}); return util.out8(port, value); } export fn georgios_bios_int_outw(port: u16, value: u16) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outw {:x}, {:x}\n", .{port, value}); return util.out16(port, value); } export fn georgios_bios_int_outl(port: u16, value: u32) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outl {:x}, {:x}\n", .{port, value}); return util.out32(port, value); } export fn georgios_bios_int_fush_log_impl(buf: [*c]u8, size: c_uint) void { print.string(buf[0..size]); } // For Access to Memory export fn georgios_bios_int_rdb(addr: u32) callconv(.C) u8 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u8, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdb {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_rdw(addr: u32) callconv(.C) u16 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u16, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdw {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_rdl(addr: u32) callconv(.C) u32 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u32, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdl {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_wrb(addr: u32, value: u8) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrb {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u8, addr).* = value; } export fn georgios_bios_int_wrw(addr: u32, value: u16) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrw {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u16, addr).* = value; } export fn georgios_bios_int_wrl(addr: u32, value: u32) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrl {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u32, addr).* = value; } pub fn init() void { c.georgios_bios_int_init(exec_trace); } pub fn run(params: *Params) Error!void { const pmem = &kernel.memory_mgr.impl; pmem.map(.{.start = 0, .size = utils.Mi(1)}, 0, false) catch @panic("bios_int map"); var c_params = c.GeorgiosBiosInt{ .interrupt = params.interrupt, .eax = params.eax, .ebx = params.ebx, .ecx = params.ecx, .edx = params.edx, .edi = params.edi, .slow = params.slow, }; const failed = c.georgios_bios_int_run(&c_params); params.eax = c_params.eax; params.ebx = c_params.ebx; params.ecx = c_params.ecx; params.edx = c_params.edx; params.edi = c_params.edi; params.slow = false; if (failed) { return Error.BiosIntCallFailed; } } pub fn done() void { c.georgios_bios_int_done(); }
kernel/platform/bios_int.zig
const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; const math = std.math; pub fn max(A: []i32) i32 { var max_val: comptime i32 = 0; for (A) |value, index| { if (value > max_val) { max_val = A[index]; } } return max_val; } //Stable sort that expects C to only contain values `x` such that `0 <= x < radix` pub fn counting_sort(A: []i32, B: []i32, C: []usize, exp: i32, radix: usize) void { //Reset all elements of array C to 0 mem.set(usize, C, 0); for (A) |_, index| { const digit_of_Ai = @rem(@intCast(usize, @divFloor(A[index], exp)), radix); C[digit_of_Ai] = C[digit_of_Ai] + 1; } var j: usize = 1; while (j < radix) : (j = j + 1) { C[j] = C[j] + C[j - 1]; } var m = A.len - 1; while (m != math.maxInt(usize) and m >= 0) : (m = m -% 1) { const digit_of_Ai = @rem(@intCast(usize, @divFloor(A[m], exp)), radix); C[digit_of_Ai] = C[digit_of_Ai] - 1; //Output stored in B B[C[digit_of_Ai]] = A[m]; } } ///References: https://brilliant.org/wiki/radix-sort/ /// https://en.wikipedia.org/wiki/Radix_sort ///LSD radix sort pub fn sort(A: []i32, B: []i32, radix: usize) !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { _ = gpa.deinit(); } const C = try gpa.allocator.alloc(usize, radix); defer gpa.allocator.free(C); var k = max(A); var exp: i32 = 1; //Utilize counting sort to order A digit wise starting from the least significant digit while (@divFloor(k, exp) > 0) : (exp *= 10) { counting_sort(A, B, C, exp, radix); //Copy output of B to A for (B) |value, index| { A[index] = value; } } } pub fn main() !void {} test "empty array" { var array: []i32 = &.{}; var work_array: []i32 = &.{}; try sort(array, work_array, 10); const a = array.len; try expect(a == 0); } test "array with one element" { var array: [1]i32 = .{5}; var work_array: [1]i32 = .{0}; try sort(&array, &work_array, 10); const a = array.len; try expect(a == 1); try expect(array[0] == 5); } test "sorted array" { var array: [10]i32 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var work_array: [10]i32 = .{0} ** 10; try sort(&array, &work_array, 10); for (array) |value, i| { try expect(value == (i + 1)); } } test "reverse order" { var array: [10]i32 = .{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; var work_array: [10]i32 = .{0} ** 10; try sort(&array, &work_array, 10); for (array) |value, i| { try expect(value == (i + 1)); } } test "unsorted array" { var array: [5]i32 = .{ 5, 3, 4, 1, 2 }; var work_array: [5]i32 = .{0} ** 5; try sort(&array, &work_array, 10); for (array) |value, i| { try expect(value == (i + 1)); } } test "two last unordered" { var array: [10]i32 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 10, 9 }; var work_array: [10]i32 = .{0} ** 10; try sort(&array, &work_array, 10); for (array) |value, i| { try expect(value == (i + 1)); } } test "two first unordered" { var array: [10]i32 = .{ 2, 1, 3, 4, 5, 6, 7, 8, 9, 10 }; var work_array: [10]i32 = .{0} ** 10; try sort(&array, &work_array, 10); for (array) |value, i| { try expect(value == (i + 1)); } }
sorting/radix_sort.zig
const std = @import("std"); const common = @import("common.zig"); const general = @import("general.zig"); const window = @import("window.zig"); const text_sync = @import("text_sync.zig"); pub const NotificationMessage = struct { jsonrpc: []const u8 = "2.0", /// The method to be invoked. method: []const u8, /// The notification's params. params: NotificationParams, }; pub const NotificationParams = union(enum) { // General progress: ProgressParams, initialized: general.InitializedParams, // Window show_message: window.ShowMessageParams, log_message: window.LogMessageParams, // Text Sync did_open: text_sync.DidOpenTextDocumentParams, did_change: text_sync.DidChangeTextDocumentParams, }; /// Params of a request (params) pub const NotificationParseTarget = union(enum) { // General progress: common.Paramsify(ProgressParams), initialized: common.Paramsify(general.InitializedParams), // Window show_message: common.Paramsify(window.ShowMessageParams), log_message: common.Paramsify(window.LogMessageParams), // Text Sync did_open: common.Paramsify(text_sync.DidOpenTextDocumentParams), did_change: common.Paramsify(text_sync.DidChangeTextDocumentParams), pub fn toMessage(self: NotificationParseTarget) NotificationMessage { inline for (std.meta.fields(NotificationParseTarget)) |field, i| { if (@enumToInt(self) == i) { return .{ .method = @field(self, field.name).method, .params = @unionInit(NotificationParams, field.name, @field(self, field.name).params), }; } } unreachable; } }; pub const ProgressToken = union(enum) { integer: common.integer, string: []const u8, }; // TODO: Generic T used; what the hell does that mean?? pub const ProgressValue = union(enum) { integer: common.integer, string: []const u8, }; /// The base protocol offers also support to report progress in a generic fashion. /// This mechanism can be used to report any kind of progress including work done progress /// (usually used to report progress in the user interface using a progress bar) /// and partial result progress to support streaming of results. /// /// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#progress) pub const ProgressParams = struct { pub const method = "$/progress"; pub const kind = common.PacketKind.notification; /// The progress token provided by the client or server. token: ProgressToken, /// The progress data. value: ProgressValue, };
src/types/notifications.zig
const std = @import("std"); const meta = std.meta; const assert = std.debug.assert; const testing = std.testing; const builtin = std.builtin; const Allocator = std.mem.Allocator; pub fn Num(comptime T: type, endian: std.builtin.Endian) type { const info = @typeInfo(T); if (info != .Int and info != .Float) { @compileError("expected an int or a float"); } return struct { const IntType = if (info == .Float) meta.Int(.unsigned, info.Float.bits) else T; pub const UserType = T; pub fn write(self: UserType, writer: anytype) !void { try writer.writeInt(IntType, @bitCast(IntType, self), endian); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { _ = alloc; const val = try reader.readInt(IntType, endian); return @bitCast(T, val); } pub fn deinit(self: UserType, alloc: Allocator) void { _ = self; _ = alloc; } pub fn size(self: UserType) usize { _ = self; return @sizeOf(T); } }; } pub const Bool = struct { pub const UserType = bool; pub fn write(self: UserType, writer: anytype) !void { try writer.writeByte(if (self) 0x01 else 0x00); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { _ = alloc; return (try reader.readByte()) == 0x01; } pub fn deinit(self: UserType, alloc: Allocator) void { _ = self; _ = alloc; } pub fn size(self: UserType) usize { _ = self; return 1; } }; pub const Void = struct { pub const UserType = void; pub fn write(self: UserType, writer: anytype) !void { _ = self; _ = writer; } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { _ = alloc; _ = reader; } pub fn deinit(self: UserType, alloc: Allocator) void { _ = self; _ = alloc; } pub fn size(self: UserType) usize { _ = self; return 0; } }; pub fn StructFieldSpecs(comptime UsedSpec: type, comptime Partial: type) [meta.fields(Partial).len]type { const info = @typeInfo(Partial).Struct; var specs: [info.fields.len]type = undefined; inline for (info.fields) |field, i| { const SpecType = UsedSpec.Spec(field.field_type); specs[i] = SpecType; } return specs; } pub fn StructUserType(comptime Partial: type, comptime Specs: []const type) type { const info = @typeInfo(Partial).Struct; var fields: [info.fields.len]builtin.TypeInfo.StructField = undefined; inline for (info.fields) |*field, i| { var f = field.*; f.field_type = Specs[i].UserType; f.default_value = null; fields[i] = f; } return @Type(builtin.TypeInfo{ .Struct = .{ .layout = info.layout, .fields = &fields, .decls = &[_]builtin.TypeInfo.Declaration{}, .is_tuple = info.is_tuple, } }); } // pub fn Struct(comptime UsedSpec: type, comptime Partial: type) type { // const info = @typeInfo(Partial).Struct; // return struct { // pub const Specs = StructFieldSpecs(UsedSpec, Partial); // pub const UserType = StructUserType(Partial, std.mem.span(&Specs)); // pub fn write(self: UserType, writer: anytype) !void { // inline for (info.fields) |field, i| { // try Specs[i].write(@field(self, field.name), writer); // } // } // pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { // var data: UserType = undefined; // inline for (info.fields) |field, i| { // @field(data, field.name) = try Specs[i].deserialize(alloc, reader); // } // return data; // } // pub fn deinit(self: UserType, alloc: Allocator) void { // inline for (info.fields) |field, i| { // Specs[i].deinit(@field(self, field.name), alloc); // } // } // pub fn size(self: UserType) usize { // var total_size: usize = 0; // inline for (info.fields) |field, i| { // total_size += Specs[i].size(@field(self, field.name)); // } // return total_size; // } // }; // } pub fn Struct(comptime UsedSpec: type, comptime Partial: type) type { const info = @typeInfo(Partial).Struct; return struct { pub const Specs = StructFieldSpecs(UsedSpec, Partial); pub const UserType = StructUserType(Partial, std.mem.span(&Specs)); pub fn write(self: anytype, writer: anytype) !void { const CustomType = @TypeOf(self); inline for (info.fields) |field, i| { if (@hasField(CustomType, field.name)) { try Specs[i].write(@field(self, field.name), writer); } else if (@typeInfo(field.field_type) == .Optional) { try Specs[i].write(null, writer); } else { @compileError("Custom struct \"" ++ @typeName(CustomType) ++ "\" missing required field: \"" ++ field.name ++ "\""); } } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { var data: UserType = undefined; inline for (info.fields) |field, i| { @field(data, field.name) = try Specs[i].deserialize(alloc, reader); } return data; } pub fn deinit(self: UserType, alloc: Allocator) void { inline for (info.fields) |field, i| { Specs[i].deinit(@field(self, field.name), alloc); } } pub fn size(self: anytype) usize { const CustomType = @TypeOf(self); var total_size: usize = 0; inline for (info.fields) |field, i| { if (@hasField(CustomType, field.name)) { total_size += Specs[i].size(@field(self, field.name)); } else if (@typeInfo(field.field_type) == .Optional) { total_size += Specs[i].size(null); } else { @compileError("Custom struct \"" ++ @typeName(CustomType) ++ "\" missing required field: \"" ++ field.name ++ "\""); } } return total_size; } }; } pub fn isIntType(comptime T: type) bool { if (isSerializable(T)) { return @typeInfo(T.UserType) == .Int; } else { return @typeInfo(T) == .Int; } } pub fn Enum(comptime UsedSpec: type, comptime PartialTag: type, comptime UserType: type) type { assert(@typeInfo(UserType) == .Enum); return struct { pub const TagType = UsedSpec.Spec(PartialTag); comptime { assert(@typeInfo(TagType.UserType) == .Int); } pub const UserType = UserType; pub fn getInt(self: UserType) TagType.UserType { return @intCast(TagType.UserType, @enumToInt(self)); } pub fn write(self: UserType, writer: anytype) !void { try TagType.write(getInt(self), writer); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { return @intToEnum(UserType, try TagType.deserialize(alloc, reader)); } pub fn deinit(self: UserType, alloc: Allocator) void { _ = self; _ = alloc; } pub fn size(self: UserType) usize { return TagType.size(getInt(self)); } }; } pub fn UnionSpecs(comptime UsedSpec: type, comptime PartialUnion: type) [meta.fields(PartialUnion).len]type { const info = @typeInfo(PartialUnion).Union; var specs: [info.fields.len]type = undefined; inline for (info.fields) |field, i| { specs[i] = UsedSpec.Spec(field.field_type); } return specs; } pub fn UnionUserType(comptime Partial: type, comptime Specs: []const type) type { const info = @typeInfo(Partial).Union; var fields: [info.fields.len]builtin.TypeInfo.UnionField = undefined; inline for (info.fields) |*field, i| { var f = field.*; f.field_type = Specs[i].UserType; fields[i] = f; } return @Type(builtin.TypeInfo{ .Union = .{ .layout = info.layout, .tag_type = info.tag_type, .fields = &fields, .decls = &[_]std.builtin.TypeInfo.Declaration{}, } }); } // special (incompatible with normal ser/de) pub fn Union(comptime UsedSpec: type, comptime PartialUnion: type) type { assert(@typeInfo(PartialUnion) == .Union); return struct { pub const Specs = UnionSpecs(UsedSpec, PartialUnion); pub const UserType = UnionUserType(PartialUnion, std.mem.span(&Specs)); pub const IntType = meta.Tag(meta.Tag(UserType)); const field_enum = meta.FieldEnum(meta.Tag(UserType)); pub fn getInt(self: anytype) IntType { const info = @typeInfo(@TypeOf(self)); if (info == .Union) { return @intCast(IntType, @enumToInt(self)); } else { assert(info == .Struct and info.Struct.fields.len == 1); return @intCast(IntType, @enumToInt(@field(meta.Tag(UserType), info.Struct.fields[0].name))); } } fn tagEnumField(comptime i: comptime_int) builtin.TypeInfo.EnumField { return meta.fieldInfo(meta.Tag(UserType), @intToEnum(meta.FieldEnum(meta.Tag(UserType)), i)); } pub fn write(self: anytype, writer: anytype) !void { const info = @typeInfo(@TypeOf(self)); if (info == .Union) { const tag_int = getInt(self); inline for (meta.fields(UserType)) |field, i| { const enum_field = tagEnumField(i); if (enum_field.value == tag_int) { const res = Specs[i].write(@field(self, field.name), writer); if (meta.isError(res)) res catch |err| return err; return; } } return error.InvalidTag; } else { assert(info == .Struct and info.Struct.fields.len == 1); const name = info.Struct.fields[0].name; const i = @enumToInt(@field(field_enum, name)); try Specs[i].write(@field(self, name), writer); } } pub fn deserialize(alloc: Allocator, reader: anytype, tag_int: IntType) !UserType { inline for (meta.fields(UserType)) |field, i| { const enum_field = tagEnumField(i); if (enum_field.value == tag_int) { // untested if this workaround is necessary for write, but it // is necessary for deserialize https://github.com/ziglang/zig/issues/10087 const res = Specs[i].deserialize(alloc, reader); if (meta.isError(res)) _ = res catch |err| return err; const val = res catch unreachable; return @unionInit(UserType, field.name, val); } } return error.InvalidTag; } pub fn deinit(self: UserType, alloc: Allocator) void { const tag_int = getInt(self); inline for (meta.fields(UserType)) |field, i| { _ = field; //const enum_field = meta.fieldInfo(meta.Tag(UserType), @intToEnum(meta.FieldEnum(meta.Tag(UserType)), i)); const enum_field = tagEnumField(i); if (enum_field.value == tag_int) { Specs[i].deinit(@field(self, field.name), alloc); return; } } } pub fn size(self: anytype) usize { const info = @typeInfo(@TypeOf(self)); if (info == .Union) { const tag_int = getInt(self); inline for (meta.fields(UserType)) |field, i| { _ = field; //const enum_field = meta.fieldInfo(meta.Tag(UserType), @intToEnum(meta.FieldEnum(meta.Tag(UserType)), i)); const enum_field = tagEnumField(i); if (enum_field.value == tag_int) { return Specs[i].size(@field(self, field.name)); } } return 0; } else { assert(info == .Struct and info.Struct.fields.len == 1); const name = info.Struct.fields[0].name; const i = @enumToInt(@field(field_enum, name)); return Specs[i].size(@field(self, name)); } } }; } pub fn TaggedUnion(comptime UsedSpec: type, comptime PartialTag: type, comptime PartialUnion: type) type { return struct { pub const TagType = UsedSpec.Spec(PartialTag); comptime { assert(@typeInfo(TagType.UserType) == .Int); } pub const UnionType = Union(UsedSpec, PartialUnion); pub const UserType = UnionType.UserType; pub fn write(self: anytype, writer: anytype) !void { const tag_int = UnionType.getInt(self); try TagType.write(tag_int, writer); try UnionType.write(self, writer); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { const tag_int = try TagType.deserialize(alloc, reader); errdefer std.log.err("tag value: 0x{X}", .{tag_int}); return try UnionType.deserialize(alloc, reader, tag_int); } pub fn deinit(self: UserType, alloc: Allocator) void { UnionType.deinit(self, alloc); } pub fn size(self: anytype) usize { const tag_int = UnionType.getInt(self); return TagType.size(tag_int) + UnionType.size(self); } }; } test "serde tagged union" { const TestEnum = enum(u8) { A = 0, B = 1, C = 2, D = 4, }; const TestUnion = union(TestEnum) { A: u8, B: u16, C: void, D: struct { a: i32, b: bool, }, }; const SerdeUnion = TaggedUnion(DefaultSpec, u8, TestUnion); inline for (.{ .{ .buf = [_]u8{ 0x00, 0x05 }, .desired = SerdeUnion.UserType{ .A = 5 } }, .{ .buf = [_]u8{ 0x01, 0x01, 0x00 }, .desired = SerdeUnion.UserType{ .B = 256 } }, .{ .buf = [_]u8{0x02}, .desired = SerdeUnion.UserType.C }, .{ .buf = [_]u8{ 0x04, 0x00, 0x00, 0x00, 0x08, 0x01 }, .desired = SerdeUnion.UserType{ .D = .{ .a = 8, .b = true } } }, }) |pair| { var stream = std.io.fixedBufferStream(&pair.buf); const result = try SerdeUnion.deserialize(testing.allocator, &stream.reader()); try testing.expect(meta.eql(result, pair.desired)); } } pub fn Packed(comptime T: type) type { return struct { pub const UserType = T; pub fn write(self: UserType, writer: anytype) !void { try writer.writeStruct(self); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { _ = alloc; return reader.readStruct(UserType); } pub fn deinit(self: UserType, alloc: Allocator) void { _ = self; _ = alloc; } pub fn size(self: UserType) usize { _ = self; return @sizeOf(UserType); } }; } test "packed spec" { // TODO: how could i forget about endianness ! probably has to be fixed const TestStruct = Packed(packed struct { a: bool, b: bool, c: bool, d: bool, e: bool, f: bool, }); // 0b11010000 -> 0xD0 // 4321 const buf = [_]u8{0xD0}; var stream = std.io.fixedBufferStream(&buf); const result = try TestStruct.deserialize(testing.allocator, &stream.reader()); try testing.expect(meta.eql(result, .{ .a = false, .b = false, .c = false, .d = false, .e = true, .f = false, })); } pub fn Array(comptime UsedSpec: type, comptime Partial: type) type { const info = @typeInfo(Partial).Array; return struct { pub const ElemType = UsedSpec.Spec(info.child); pub const UserType = [info.len]ElemType.UserType; pub fn write(self: anytype, writer: anytype) !void { var iter = toIterator(self); while (iter.next()) |elem| { try ElemType.write(elem, writer); } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { var data: UserType = undefined; for (data) |*item, i| { errdefer { var ind: usize = 0; while (ind < i) : (i += 1) { ElemType.deinit(data[i], alloc); } } item.* = try ElemType.deserialize(alloc, reader); } return data; } pub fn deinit(self: UserType, alloc: Allocator) void { for (self) |item| { ElemType.deinit(item, alloc); } } pub fn size(self: UserType) usize { var total_size: usize = 0; for (self) |item| { total_size += ElemType.size(item); } return total_size; } }; } pub const DefaultSpec = struct { pub fn Spec(comptime Partial: type) type { if (isSerializable(Partial)) { // partial spec is already a full spec return Partial; } switch (@typeInfo(Partial)) { .Void => return Void, .Bool => return Bool, .Int => return Num(Partial, .Big), .Float => return Num(Partial, .Big), .Struct => |info| { if (info.layout == .Packed) { return Packed(Partial); } else { return Struct(@This(), Partial); } }, .Optional => return Optional(@This(), Partial), .Enum => return Enum(@This(), meta.Tag(Partial), Partial), else => @compileError("dont know how to do full spec for " ++ @typeName(Partial)), } } }; pub fn isSerializable(comptime T: type) bool { const info = @typeInfo(T); if (info != .Struct and info != .Union and info != .Enum) return false; inline for (.{ "write", "deserialize", "deinit", "size", "UserType" }) |name| { if (!@hasDecl(T, name)) { return false; } } return true; } test "serde full spec" { const SpecType = DefaultSpec.Spec(struct { a: i32, b: struct { c: bool, d: u8, e: Num(u16, .Little), }, c: enum(u8) { A = 0x00, B = 0x01, C = 0x02 }, }); const buf = [_]u8{ 0x00, 0x00, 0x01, 0x02, 0x01, 0x08, 0x10, 0x00, 0x02 }; var reader = std.io.fixedBufferStream(&buf); const result = try SpecType.deserialize(testing.allocator, &reader.reader()); try testing.expect(meta.eql(SpecType.UserType{ .a = 258, .b = .{ .c = true, .d = 0x08, .e = 0x10, }, .c = .C, }, result)); try testing.expectEqual(buf.len, SpecType.size(result)); } pub const Remaining = struct { pub const UserType = []const u8; // TODO: it'd be nice to be able to pass in any type to write pub fn write(self: UserType, writer: anytype) !void { try writer.writeAll(self); } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { var data = std.ArrayList(u8).init(alloc); defer data.deinit(); // should be same function as an errdefer here; if successful, there shouldnt be any memory to deinit var buf: [1024]u8 = undefined; while (true) { const len = reader.read(&buf) catch |err| if (err == error.ReadTooFar) 0 else return err; if (len == 0) { break; } try data.appendSlice(buf[0..len]); } return data.toOwnedSlice(); } pub fn deinit(self: UserType, alloc: Allocator) void { alloc.free(self); } pub fn size(self: UserType) usize { return self.len; } }; test "serde remaining" { const SpecType = DefaultSpec.Spec(struct { a: i32, data: Remaining, }); const buf = [_]u8{ 0x00, 0x00, 0x01, 0x02, 0x01, 0x08, 0x10, 0x00, 0x02 }; var reader = std.io.fixedBufferStream(&buf); const result = try SpecType.deserialize(testing.allocator, &reader.reader()); defer SpecType.deinit(result, testing.allocator); try testing.expectEqual(@as(i32, 258), result.a); try testing.expectEqualSlices(u8, &[_]u8{ 0x01, 0x08, 0x10, 0x00, 0x02 }, result.data); try testing.expectEqual(buf.len, SpecType.size(result)); } pub fn SizePrefixedArray(comptime UsedSpec: type, comptime PartialLength: type, comptime T: type) type { return struct { pub const ElemType = UsedSpec.Spec(T); pub const LengthType = UsedSpec.Spec(PartialLength); pub const UserType = []const ElemType.UserType; pub fn write(self: UserType, writer: anytype) !void { var elements_size: usize = 0; for (self) |item| { elements_size += ElemType.size(item); } try LengthType.write(@intCast(LengthType.UserType, elements_size), writer); for (self) |item| { try ElemType.write(item, writer); } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { const bytes_len = @intCast(usize, try LengthType.deserialize(alloc, reader)); var limited_reader = std.io.limitedReader(reader, @intCast(usize, bytes_len)); var lim_reader = limited_reader.reader(); var data = std.ArrayList(ElemType.UserType).init(alloc); defer data.deinit(); errdefer { for (data) |item| { ElemType.deinit(item, alloc); } } while (true) { const result = try ElemType.deserialize(alloc, lim_reader); if (result == error.EndOfStream) { break; } try data.append(try result); } return data.toOwnedSlice(); } pub fn deinit(self: UserType, alloc: Allocator) void { for (self) |item| { ElemType.deinit(item, alloc); } alloc.free(self); } pub fn size(self: UserType) usize { var elements_size: usize = 0; for (self) |item| { elements_size += ElemType.size(item); } return LengthType.size(@intCast(LengthType.UserType, elements_size)) + elements_size; } }; } // pub fn PrefixedArray(comptime UsedSpec: type, comptime PartialLength: type, comptime T: type) type { // return struct { // pub const LengthType = UsedSpec.Spec(PartialLength); // pub const SpecType = UsedSpec.Spec(T); // pub const UserType = []const SpecType.UserType; // pub fn write(self: UserType, writer: anytype) !void { // try LengthType.write(@intCast(LengthType.UserType, self.len), writer); // for (self) |elem| { // try SpecType.write(elem, writer); // } // } // pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { // const len = @intCast(usize, try LengthType.deserialize(alloc, reader)); // var data = try alloc.alloc(SpecType.UserType, len); // errdefer alloc.free(data); // for (data) |*elem, i| { // errdefer { // var ind: usize = 0; // while (ind < i) : (ind += 1) { // SpecType.deinit(data[ind], alloc); // } // } // elem.* = try SpecType.deserialize(alloc, reader); // } // return data; // } // pub fn deinit(self: UserType, alloc: Allocator) void { // for (self) |elem| { // SpecType.deinit(elem, alloc); // } // alloc.free(self); // } // pub fn size(self: UserType) usize { // var total_size = LengthType.size(@intCast(LengthType.UserType, self.len)); // for (self) |elem| { // total_size += SpecType.size(elem); // } // return total_size; // } // }; // } // guessing it doesnt handle sentinels at the moment pub fn ToIterator(comptime T: type) type { const info = @typeInfo(T); //if (info == .Pointer and info.Pointer.size == .One) return ToIterator(meta.Child(T)); if (info == .Array or (info == .Pointer and (info.Pointer.size == .Slice or (info.Pointer.size == .One and @typeInfo(info.Pointer.child) != .Struct)))) { return struct { index: usize = 0, backing: T, pub fn next(self: *@This()) ?meta.Elem(T) { if (self.index < self.backing.len) { const elem = self.backing[self.index]; self.index += 1; return elem; } else return null; } pub fn size(self: *const @This()) usize { return self.backing.len; } }; } else if (info == .Struct and @hasDecl(T, "next") and @hasDecl(T, "size")) { return T; } @compileError("type passed to ToIterator is not iterable: " ++ @typeName(T)); } pub fn TupleArrayType(comptime T: type) type { const fields = @typeInfo(T).Struct.fields; return [fields.len]fields[0].field_type; } // TODO: doesnt work on tuples of tuples pub fn tupleToArray(val: anytype) TupleArrayType(@TypeOf(val)) { const fields = @typeInfo(@TypeOf(val)).Struct.fields; comptime { inline for (fields) |field| { assert(field.field_type == fields[0].field_type); } } var arr: [fields.len]fields[0].field_type = undefined; comptime var ind = 0; inline while (ind < fields.len) : (ind += 1) { arr[ind] = val[ind]; } return arr; } pub fn toIterator(val: anytype) ToIterator(if (@typeInfo(@TypeOf(val)) == .Struct and @typeInfo(@TypeOf(val)).Struct.is_tuple) TupleArrayType(@TypeOf(val)) else @TypeOf(val)) { const info = @typeInfo(@TypeOf(val)); const actual_val = switch (info) { .Struct => if (info.Struct.is_tuple) tupleToArray(val) else val, .Pointer => if (info.Pointer.size == .One and @typeInfo(info.Pointer.child) != .Struct) .{ .backing = val } else (if (info.Pointer.size == .Slice) val else { @compileError("failed to turn type " ++ @typeName(@TypeOf(val)) ++ " into an iterator"); }), else => unreachable, }; if (@typeInfo(@TypeOf(actual_val)) == .Struct) { return actual_val; } else { return .{ .backing = actual_val }; } } pub fn PrefixedArray(comptime UsedSpec: type, comptime PartialLength: type, comptime T: type) type { return struct { pub const LengthType = UsedSpec.Spec(PartialLength); pub const SpecType = UsedSpec.Spec(T); pub const UserType = []const SpecType.UserType; pub fn write(self: anytype, writer: anytype) !void { var iter = toIterator(self); try LengthType.write(@intCast(LengthType.UserType, iter.size()), writer); while (iter.next()) |elem| { try SpecType.write(elem, writer); } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { const len = @intCast(usize, try LengthType.deserialize(alloc, reader)); var data = try alloc.alloc(SpecType.UserType, len); errdefer alloc.free(data); for (data) |*elem, i| { errdefer { var ind: usize = 0; while (ind < i) : (ind += 1) { SpecType.deinit(data[ind], alloc); } } elem.* = try SpecType.deserialize(alloc, reader); } return data; } pub fn deinit(self: UserType, alloc: Allocator) void { for (self) |elem| { SpecType.deinit(elem, alloc); } alloc.free(self); } pub fn size(self: anytype) usize { var iter = toIterator(self); var total_size = LengthType.size(@intCast(LengthType.UserType, iter.size())); while (iter.next()) |elem| { total_size += SpecType.size(elem); } return total_size; } }; } test "serde prefixed array" { const SpecType = PrefixedArray(DefaultSpec, u8, u16); const buf = [_]u8{ 0x04, // <-- length 0x00, // beginning of data 0x01, 0x02, 0x01, 0x08, 0x10, 0x00, 0x02, }; var reader = std.io.fixedBufferStream(&buf); const result = try SpecType.deserialize(testing.allocator, &reader.reader()); defer SpecType.deinit(result, testing.allocator); try testing.expectEqualSlices(u16, &[_]u16{ 0x0001, 0x0201, 0x0810, 0x0002 }, result); try testing.expectEqual(buf.len, SpecType.size(result)); var wrote_data = std.ArrayList(u8).init(testing.allocator); defer wrote_data.deinit(); try SpecType.write(result, wrote_data.writer()); try testing.expectEqualSlices(u8, &buf, wrote_data.items); wrote_data.clearAndFree(); const arr: [4]u16 = .{ 0x0001, 0x0201, 0x0810, 0x0002 }; try SpecType.write(arr, wrote_data.writer()); // should be being passed an array, not a slice try testing.expectEqualSlices(u8, &buf, wrote_data.items); wrote_data.clearAndFree(); try SpecType.write(.{ @as(u16, 0x0001), @as(u16, 0x0201), @as(u16, 0x0810), @as(u16, 0x0002) }, wrote_data.writer()); // tuple try testing.expectEqualSlices(u8, &buf, wrote_data.items); } pub fn Optional(comptime UsedSpec: type, comptime T: type) type { return struct { pub const InnerType = UsedSpec.Spec(@typeInfo(T).Optional.child); pub const UserType = ?InnerType.UserType; pub fn write(self: UserType, writer: anytype) !void { try Bool.write(self != null, writer); if (self) |inner| { try InnerType.write(inner, writer); } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { if (try Bool.deserialize(alloc, reader)) { return try InnerType.deserialize(alloc, reader); } return null; } pub fn deinit(self: UserType, alloc: Allocator) void { if (self) |inner| { InnerType.deinit(inner, alloc); } } pub fn size(self: UserType) usize { if (self) |inner| { return 1 + InnerType.size(inner); } return 1; } }; }
src/serde.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "NewTaskEntry", .filter = .info, }).write; const libalign = lib.util.libalign; /// Class that handles calling a function with any arguments on a new stack /// Used as a helper for task creation in platform-specific code pub const NewTaskEntry = struct { /// Callback that should be executed in a new task function: fn (*NewTaskEntry) noreturn, pub fn alloc(task: *os.thread.Task, func: anytype, args: anytype) *NewTaskEntry { comptime const Args = @TypeOf(args); comptime const Func = @TypeOf(func); // Method: specify subtype with specific types of func and args const Wrapper = struct { entry: NewTaskEntry = .{ .function = invoke }, function: Func, args: Args, /// Error guard fn callWithErrorGuard(self: *@This()) !void { return @call(.{}, self.function, self.args); } /// Implementation of invoke fn invoke(entry: *NewTaskEntry) noreturn { const self = @fieldParentPtr(@This(), "entry", entry); self.callWithErrorGuard() catch |err| { log(null, "Task has finished with error {e}\n", .{err}); }; os.thread.scheduler.exitTask(); } /// Creates Wrapper on the stack fn create( function: anytype, arguments: anytype, boot_stack_top: usize, boot_stack_bottom: usize, ) *@This() { const addr = libalign.alignDown( usize, @alignOf(@This()), boot_stack_top - @sizeOf(@This()), ); std.debug.assert(addr > boot_stack_bottom); const wrapper_ptr = @intToPtr(*@This(), addr); wrapper_ptr.* = .{ .function = function, .args = arguments, }; return wrapper_ptr; } }; const stack_top = task.stack; const stack_bottom = stack_top - os.platform.thread.task_stack_size; return &Wrapper.create(func, args, stack_top, stack_bottom).entry; } };
subprojects/flork/src/thread/task_entry.zig
const std = @import("std"); const Builder = @import("std").build.Builder; const ReloadStep = @import("./reload_step.zig"); const Self = @This(); pub const PackageAddOptions = union(enum) { Automatic: []const u8, Manual: struct { name: []const u8, src: []const u8, }, None: void, }; pub const Options = struct { name: []const u8, identifier: []const u8, version: ?std.builtin.Version = null, target: std.zig.CrossTarget = std.zig.CrossTarget{}, mode: ?std.builtin.Mode = null, package_add: PackageAddOptions = .{ .Automatic = "zig-vst", }, }; builder: *Builder, lib_step: *std.build.LibExeObjStep, step: std.build.Step, options: Options, pub fn create(builder: *Builder, root_src: []const u8, options: Options) *Self { const self = builder.allocator.create(Self) catch unreachable; const name = options.name; if (options.version) |version| { self.lib_step = builder.addSharedLibrary(name, root_src, .{ .versioned = version }); } else { self.lib_step = builder.addSharedLibrary(name, root_src, .{ .unversioned = {} }); } self.builder = builder; self.step = std.build.Step.init(.custom, "macOS .vst bundle", builder.allocator, make); self.options = options; if (options.mode) |mode| self.lib_step.setBuildMode(mode); self.lib_step.setTarget(options.target); self.addPackage() catch unreachable; self.step.dependOn(&self.lib_step.step); return self; } pub fn autoReload(self: *Self) *ReloadStep { return ReloadStep.create(self); } pub fn getInternalLibOutputPath(self: *Self) []const u8 { const output_source = self.lib_step.getOutputSource(); return output_source.getPath(self.builder); } fn addPackage(self: *Self) !void { switch (self.options.package_add) { .Automatic => |package_name| { const this_filename = @src().file; if (std.fs.path.dirname(this_filename)) |dirname| { const main_path = try std.fs.path.resolve(self.builder.allocator, &[_][]const u8{ dirname, "main.zig", }); self.lib_step.addPackagePath(package_name, main_path); } else { std.log.err("Failed to automatically determine the location of the zig-vst source code. Consider changing your Options.package_add value to .Manual or .None\n", .{}); } }, .Manual => |manual_config| { self.lib_step.addPackagePath(manual_config.name, manual_config.src); }, .None => {}, } } fn make(step: *std.build.Step) !void { const self = @fieldParentPtr(Self, "step", step); return switch (self.options.target.getOsTag()) { .macos => self.makeMacOS(), else => self.makeDefault(), }; } fn makeDefault(self: *Self) !void { const cwd = std.fs.cwd(); const lib_output_path = self.getInternalLibOutputPath(); const extension = std.fs.path.extension(lib_output_path); const version_string = if (self.options.version) |version| self.builder.fmt(".{}.{}.{}", .{ version.major, version.minor, version.patch, }) else ""; const name = self.builder.fmt("{s}{s}{s}", .{ self.options.name, version_string, extension, }); const vst_path = self.builder.getInstallPath(.prefix, "vst"); var vst_dir = try cwd.makeOpenPath(vst_path, .{}); defer vst_dir.close(); try cwd.copyFile(lib_output_path, vst_dir, name, .{}); } fn makeMacOS(self: *Self) !void { const bundle_path = try self.getOutputDir(); const cwd = std.fs.cwd(); var bundle_dir = try cwd.makeOpenPath(bundle_path, .{}); defer bundle_dir.close(); try bundle_dir.makePath("Contents/MacOS"); const binary_path = try std.fs.path.join(self.builder.allocator, &[_][]const u8{ "Contents/MacOS", self.options.name, }); const lib_output_path = self.getInternalLibOutputPath(); try cwd.copyFile(lib_output_path, bundle_dir, binary_path, .{}); const plist_file = try bundle_dir.createFile("Contents/Info.plist", .{}); defer plist_file.close(); try self.writePlist(plist_file); const pkginfo_file = try bundle_dir.createFile("Contents/PkgInfo", .{}); defer pkginfo_file.close(); try pkginfo_file.writeAll("BNDL????"); } fn getOutputDir(self: *Self) ![]const u8 { const vst_path = self.builder.getInstallPath(.prefix, "vst"); const bundle_basename = self.builder.fmt("{s}.vst", .{self.options.name}); return try std.fs.path.join(self.builder.allocator, &[_][]const u8{ vst_path, bundle_basename, }); } fn writePlist(self: *Self, file: std.fs.File) !void { var writer = file.writer(); const template = @embedFile("./Info.template.plist"); const version_string = if (self.options.version) |version| self.builder.fmt("{}.{}.{}", .{ version.major, version.minor, version.patch, }) else "unversioned"; var replace_idx: usize = 0; const replace = [_][]const u8{ "English", self.options.name, self.options.identifier, self.options.name, "????", version_string, version_string, }; for (template) |char| { if (char == '$' and replace_idx < replace.len) { try writer.writeAll(replace[replace_idx]); replace_idx += 1; } else { try writer.writeByte(char); } } }
src/build_step.zig
const gllparser = @import("../gllparser/gllparser.zig"); const Error = gllparser.Error; const Parser = gllparser.Parser; const ParserContext = gllparser.Context; const Result = gllparser.Result; const NodeName = gllparser.NodeName; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const Value = struct { pub fn deinit(self: *const @This(), allocator: mem.Allocator) void { _ = self; _ = allocator; } }; /// Matches the end of the `input` string. pub fn End(comptime Payload: type) type { return struct { parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, null, null), const Self = @This(); pub fn init(allocator: mem.Allocator) !*Parser(Payload, Value) { const self = Self{}; return try self.parser.heapAlloc(allocator, self); } pub fn initStack() Self { return Self{}; } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 { _ = parser; _ = node_name_cache; return std.hash_map.hashString("End"); } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const ParserContext(Payload, Value)) callconv(.Async) !void { _ = parser; var ctx = in_ctx.with({}); defer ctx.results.close(); if (ctx.offset != ctx.src.len) { try ctx.results.add(Result(Value).initError(ctx.offset + 1, "expected end of input")); return; } try ctx.results.add(Result(Value).init(ctx.offset, .{})); return; } }; } test "end" { nosuspend { const allocator = testing.allocator; const Payload = void; var ctx = try ParserContext(Payload, Value).init(allocator, "", {}); defer ctx.deinit(); var e = try End(Payload).init(allocator); defer e.deinit(allocator, null); try e.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; defer first.deinit(ctx.allocator); try testing.expectEqual(Result(Value).init(0, .{}), first); try testing.expect(sub.next() == null); } }
src/combn/parser/end.zig
const std = @import("std"); pub const KeySym = enum { arrow_up, arrow_down, arrow_left, arrow_right, pub fn jsonStringify( value: KeySym, options: std.json.StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { _ = options; try out_stream.writeAll(std.meta.tagName(value)); } }; pub const MouseButton = enum { left, middle, right, scroll_up, scroll_down, pub fn jsonStringify( value: MouseButton, options: std.json.StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { _ = options; try out_stream.writeAll(std.meta.tagName(value)); } }; pub const KeyCode = union(enum) { // How to represent a null value? See discussions below // https://github.com/ziglang/zig/issues/9415 // https://github.com/greenfork/kisa/commit/23cfb17ae335dfe044eb4f1cd798deb37b48d569#r53652535 // unrecognized: u0, unicode_codepoint: u32, function: u8, keysym: KeySym, mouse_button: MouseButton, mouse_position: struct { x: u32, y: u32 }, }; pub const Key = struct { code: KeyCode, modifiers: u8 = 0, // Any Unicode character can be UTF-8 encoded in no more than 6 bytes, plus terminating null utf8: [7]u8 = undefined, // zig fmt: off const shift_bit = @as(u8, 1 << 0); const alt_bit = @as(u8, 1 << 1); const ctrl_bit = @as(u8, 1 << 2); const super_bit = @as(u8, 1 << 3); const hyper_bit = @as(u8, 1 << 4); const meta_bit = @as(u8, 1 << 5); const caps_lock_bit = @as(u8, 1 << 6); const num_lock_bit = @as(u8, 1 << 7); // zig fmt: on pub fn hasShift(self: Key) bool { return (self.modifiers & shift_bit) != 0; } pub fn hasAlt(self: Key) bool { return (self.modifiers & alt_bit) != 0; } pub fn hasCtrl(self: Key) bool { return (self.modifiers & ctrl_bit) != 0; } pub fn hasSuper(self: Key) bool { return (self.modifiers & super_bit) != 0; } pub fn hasHyper(self: Key) bool { return (self.modifiers & hyper_bit) != 0; } pub fn hasMeta(self: Key) bool { return (self.modifiers & meta_bit) != 0; } pub fn hasCapsLock(self: Key) bool { return (self.modifiers & caps_lock_bit) != 0; } pub fn hasNumLock(self: Key) bool { return (self.modifiers & num_lock_bit) != 0; } pub fn addShift(self: *Key) void { self.modifiers = self.modifiers | shift_bit; } pub fn addAlt(self: *Key) void { self.modifiers = self.modifiers | alt_bit; } pub fn addCtrl(self: *Key) void { self.modifiers = self.modifiers | ctrl_bit; } pub fn addSuper(self: *Key) void { self.modifiers = self.modifiers | super_bit; } pub fn addHyper(self: *Key) void { self.modifiers = self.modifiers | hyper_bit; } pub fn addMeta(self: *Key) void { self.modifiers = self.modifiers | meta_bit; } pub fn addCapsLock(self: *Key) void { self.modifiers = self.modifiers | caps_lock_bit; } pub fn addNumLock(self: *Key) void { self.modifiers = self.modifiers | num_lock_bit; } fn utf8len(self: Key) usize { var length: usize = 0; for (self.utf8) |byte| { if (byte == 0) break; length += 1; } else { unreachable; // we are responsible for making sure this never happens } return length; } pub fn isAscii(self: Key) bool { return self.code == .unicode_codepoint and self.utf8len() == 1; } pub fn isCtrl(self: Key, character: u8) bool { return self.isAscii() and self.utf8[0] == character and self.modifiers == ctrl_bit; } pub fn ascii(character: u8) Key { var key = Key{ .code = .{ .unicode_codepoint = character } }; key.utf8[0] = character; key.utf8[1] = 0; return key; } pub fn ctrl(character: u8) Key { var key = ascii(character); key.addCtrl(); return key; } pub fn alt(character: u8) Key { var key = ascii(character); key.addAlt(); return key; } pub fn shift(character: u8) Key { var key = ascii(character); key.addShift(); return key; } // We don't use `utf8` field for equality because it only contains necessary information // to represent other values and must not be considered to be always present. pub fn eql(a: Key, b: Key) bool { return std.meta.eql(a.code, b.code) and std.meta.eql(a.modifiers, b.modifiers); } pub fn hash(key: Key) u64 { var hasher = std.hash.Wyhash.init(0); std.hash.autoHash(&hasher, key.code); std.hash.autoHash(&hasher, key.modifiers); return hasher.final(); } pub const HashMapContext = struct { pub fn hash(self: @This(), s: Key) u64 { _ = self; return Key.hash(s); } pub fn eql(self: @This(), a: Key, b: Key) bool { _ = self; return Key.eql(a, b); } }; pub fn format( value: Key, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = options; if (fmt.len == 1 and fmt[0] == 's') { try writer.writeAll("Key("); if (value.hasNumLock()) try writer.writeAll("num_lock-"); if (value.hasCapsLock()) try writer.writeAll("caps_lock-"); if (value.hasMeta()) try writer.writeAll("meta-"); if (value.hasHyper()) try writer.writeAll("hyper-"); if (value.hasSuper()) try writer.writeAll("super-"); if (value.hasCtrl()) try writer.writeAll("ctrl-"); if (value.hasAlt()) try writer.writeAll("alt-"); if (value.hasShift()) try writer.writeAll("shift-"); switch (value.code) { .unicode_codepoint => |val| { try std.fmt.format(writer, "{c}", .{@intCast(u8, val)}); }, .function => |val| try std.fmt.format(writer, "f{d}", .{val}), .keysym => |val| try std.fmt.format(writer, "{s}", .{std.meta.tagName(val)}), .mouse_button => |val| try std.fmt.format(writer, "{s}", .{std.meta.tagName(val)}), .mouse_position => |val| { try std.fmt.format(writer, "MousePosition({d},{d})", .{ val.x, val.y }); }, } try writer.writeAll(")"); } else if (fmt.len == 0) { try std.fmt.format( writer, "{s}{{ .code = {}, .modifiers = {b}, .utf8 = {any} }}", .{ @typeName(@TypeOf(value)), value.code, value.modifiers, value.utf8 }, ); } else { @compileError("Unknown format character for Key: '" ++ fmt ++ "'"); } } }; test "keys: construction" { try std.testing.expect(!Key.ascii('c').hasCtrl()); try std.testing.expect(Key.ctrl('c').hasCtrl()); try std.testing.expect(Key.ascii('c').isAscii()); try std.testing.expect(Key.ctrl('c').isAscii()); try std.testing.expect(Key.ctrl('c').isCtrl('c')); }
src/keys.zig
const std = @import("std"); const builtin = @import("builtin"); pub const enable_tracy = @import("build_options").enable_tracy; const tracy = if (!enable_tracy) @import("tracy.zig") else @import("tracy_fake.zig"); const Allocator = std.mem.Allocator; const Writer = std.fs.File.Writer; const assert = std.debug.assert; const failTest = std.debug.panic; const testing = std.testing; const clib = @cImport({ @cInclude("sys/mman.h"); }); const log = std.log.scoped(.fastBPE); const str = []const u8; const DebugMode = u32; const LEARN_BPE: u8 = 1; const READ_WORDS: u8 = 2; const PUT_WORD: u8 = 4; const MERGE_PAIRS: u8 = 8; const COUNT_PAIRS_OF_CHARS: u8 = 16; const DEBUG: DebugMode = LEARN_BPE; fn debug(comptime mode: DebugMode, comptime fmt: str, any: anytype) void { if (DEBUG & mode == 0) { return; } std.debug.print("[DEBUG] " ++ fmt ++ "\n", any); } const kMaxWordLen: usize = 4096; const kMaxPairs: i32 = 1000 * 1000 * 1000; const kThreads: i32 = max(1, min(10, int(clib.thread.hardware_concurrency()))); pub const kEndWord = comptime "</w>"; pub const kTokenDelim = comptime "@@"; fn strCmp(word1: str, word2: str) bool { if (word1.len > word2.len) return !(strCmp(word2, word1)); for (word1) |c1, i| { const c2 = word2[i]; if (c1 == c2) continue; return c1 < c2; } // if lengths match then they are equal and "word1 < word2" is false. return word1.len < word2.len; } test "compare string to prefix" { testing.expect(strCmp("foo", "foobar")); testing.expect(!strCmp("foobar", "foo")); } test "compare string" { testing.expect(!strCmp("foo", "bar")); testing.expect(strCmp("bar", "foo")); } fn readWordsFromBuff(word_count: *Vocab, buffer: []u8) !u64 { var n_words: u64 = 0; var w_start: u32 = 0; var w_end: u32 = 0; var next_char: u8 = ' '; while (w_end < buffer.len) { next_char = buffer[w_end]; if (next_char != ' ' and next_char != '\n' and w_end + 1 < buffer.len) { w_end += 1; continue; } if (w_end + 1 == buffer.len and buffer[w_end] != '\n') { // only include last file char if it's not a newline w_end += 1; } // end of word const w = buffer[w_start..w_end]; w_start = w_end + 1; w_end = w_start; if (w.len == 0) continue; n_words += 1; if (word_count.getEntry(w)) |wc| { wc.value += 1; } else { const w_copy = try word_count.allocator.alloc(u8, w.len); std.mem.copy(u8, w_copy, w); _ = try word_count.put(w_copy, 1); } } return n_words; } pub fn readWords(fp: str, word_count: *Vocab) !void { var n_words: u64 = 0; // Read from stdin var line_no: u32 = 0; if (fp.len == 1 and fp[0] == '-') { var line_buf: [4096]u8 = undefined; const stdin = std.io.bufferedInStream(std.io.getStdIn().inStream()).inStream(); while (stdin.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { error.StreamTooLong => blk: { // Line is longer than buf size, skip it. try stdin.skipUntilDelimiterOrEof(' '); log.warn("Skipped line {}", .{line_no}); break :blk &line_buf; }, else => |e| return e, }) |line| { line_no += 1; n_words += try readWordsFromBuff(word_count, line); } } else { var realpath_buff: [std.fs.MAX_PATH_BYTES]u8 = undefined; const realpath = try std.fs.realpath(fp, &realpath_buff); const file = try std.fs.openFileAbsolute(fp, .{ .read = true }); log.info("Loading vocabulary from {} ...\n", .{fp}); const stat = try file.stat(); const buffer: []u8 = try std.os.mmap(null, stat.size, clib.PROT_READ, clib.MAP_PRIVATE, file.handle, 0); n_words = try readWordsFromBuff(word_count, buffer); } log.info("Read {} words ({} unique) from text file.\n", .{ n_words, word_count.count() }); } pub const Vocab = std.StringHashMap(i32); const VocabEntry = Vocab.Entry; const VocabHeader = packed struct { entries: [*]VocabEntry, capacity: Vocab.Size, }; /// Orders word by number of occurences, and alphabetical order in case of ties. fn hasMoreOccurences(context: void, kv1: Vocab.Entry, kv2: Vocab.Entry) bool { if (kv1.value == kv2.value) return strCmp(kv1.key, kv2.key); return kv1.value > kv2.value; } /// Counts words in given **tokenized** files. /// Output is sorted by decreasing order. pub fn getVocab(inputFile1: str, inputFile2: str, base_allocator: *Allocator) !void { var arena = std.heap.ArenaAllocator.init(base_allocator); defer arena.deinit(); var allocator = &arena.allocator; var word_count = Vocab.init(allocator); defer word_count.deinit(); try readWords(inputFile1, &word_count); if (inputFile2.len > 0) { try readWords(inputFile2, &word_count); } // Ideally we could salvage the word_count buffer as we iterate through it. // We used to be able to do that, but not anymore. // var unmanaged = word_count.unmanaged; // @ptrCast(*VocabHeader, @ptrCast([*]VocabHeader, unmanaged.metadata.?) - 1) // var entries_ptr: [*]VocabEntry = .entries; // var entries = entries_ptr[] var entries: []VocabEntry = try allocator.alloc(VocabEntry, word_count.count()); var i: usize = 0; var it = word_count.iterator(); while (it.next()) |entry| { entries[i] = entry.*; i += 1; } // var entries: []VocabEntry = word_count.unmanaged.recycle(); log.info("Word count: {}\n", .{entries.len}); std.sort.sort(VocabEntry, entries, {}, hasMoreOccurences); const stdout_file = std.io.getStdOut(); // print sorted vocab for (entries) |entry| { try stdout_file.outStream().print("{} {}\n", .{ entry.key, entry.value }); } } pub const WordIndex = struct { ids: std.StringHashMap(u32), tokens: std.ArrayList(str), _buffer: [kMaxWordLen + kEndWord.len]u8 = [_]u8{0} ** (kMaxWordLen + kEndWord.len), pub fn init(allocator: *Allocator) !WordIndex { var idx = WordIndex{ .ids = std.StringHashMap(u32).init(allocator), .tokens = std.ArrayList(str).init(allocator), }; std.mem.copy(u8, idx._buffer[kMaxWordLen..], kEndWord); return idx; } pub fn deinit(self: *WordIndex) void { self.ids.deinit(); self.tokens.deinit(); } pub fn ensureCapacity(self: *WordIndex, capacity: u32) !void { try self.ids.ensureCapacity(capacity); try self.tokens.ensureCapacity(capacity); } pub fn getOrPut(self: *WordIndex, word: str, end_of_word: bool) !u32 { var _word = word; if (end_of_word) { // TODO: We can do this without copying by storing (string, bool) instead std.mem.copy(u8, self._buffer[kMaxWordLen - word.len ..], word); _word = self._buffer[kMaxWordLen - word.len ..]; } var new_id = @intCast(u32, self.tokens.items.len); try self.ensureCapacity(new_id + 1); var res = try self.ids.getOrPut(_word); if (res.found_existing) { var id = res.entry.value; // debug("get token: {} -> {}", .{ _word, id }); return id; } else { debug(PUT_WORD, "add new token: {} -> {}", .{ new_id, _word }); // TODO: sometimes we don't need to copy if the string just got allocated. var new_word = try self.tokens.allocator.alloc(u8, _word.len); std.mem.copy(u8, new_word, _word); // We update the key so that we point to the newly allocated string // instead of the buffer. res.entry.key = new_word; res.entry.value = new_id; self.tokens.appendAssumeCapacity(new_word); return new_id; } } pub fn count(self: *WordIndex) !u32 { return @intCast(u32, self.tokens.items.len); } }; const WordPair = struct { w1: u32 = 0, w2: u32 = 0 }; const PairCount = struct { w1: u32 = 0, w2: u32 = 0, count: i32 = 0, pub fn init(pair: WordPair, count: i32) PairCount { return PairCount{ .w1 = pair.w1, .w2 = pair.w2, .count = count }; } }; const PairCounts = std.AutoHashMap(WordPair, *PairCount); const PairLoc = std.AutoHashMap(WordPair, std.AutoHashMap(u32, void)); const LearnBpeState = struct { // word_parts represents the bpe-parts making up a word. // It starts with unicode chars and those get merged when we learn new byte-pairs. word_parts: std.ArrayList(std.ArrayList(u32)), word_counts: std.ArrayList(i32), pairs: PairCounts, pair_loc: PairLoc, contiguous_counts: std.ArrayList(PairCount), index: WordIndex, allocator: *Allocator, pub fn init(allocator: *Allocator) LearnBpeState { var state = LearnBpeState{ .word_parts = std.ArrayList(std.ArrayList(u32)).init(allocator), .word_counts = std.ArrayList(i32).init(allocator), .pairs = PairCounts.init(allocator), .pair_loc = PairLoc.init(allocator), .contiguous_counts = std.ArrayList(PairCount).init(allocator), .index = try WordIndex.init(allocator), .allocator = allocator, }; return state; } pub fn deinit(self: *LearnBpeState) void { self.word_parts.deinit(); self.word_counts.deinit(); self.pairs.deinit(); self.pair_loc.deinit(); self.contiguous_counts.deinit(); self.index.deinit(); } pub fn ensureExtraCapacity(self: *LearnBpeState, capacity: usize) !void { var len = self.contiguous_counts.items.len; try self.contiguous_counts.ensureCapacity(len + capacity); var full_len = @intCast(u32, len + capacity); try self.contiguous_counts.ensureCapacity(full_len); try self.pair_loc.ensureCapacity(full_len); try self.pairs.ensureCapacity(full_len); // TODO: do we need to increase the index size here ? try self.index.ensureCapacity(full_len); } /// Pop the pair with the highest count and merge the two tokens. pub fn popMaxPair(self: *LearnBpeState) ?PairCount { const trace = tracy.trace(@src()); defer trace.end(); // findMaxPair is taking ~40x longer than mergeCounts // TODO: can we sort pairs, and keep them sorted during merge ? const max_p = self.findMaxPair() orelse return null; const max_p_copy = max_p.*; self.mergeCounts(max_p) catch |err| switch (err) { error.OutOfMemory => { @panic("OutOfMemory, can't generate more pairs"); }, }; return max_p_copy; } fn findMaxPair(self: *LearnBpeState) ?*PairCount { const trace = tracy.trace(@src()); defer trace.end(); var counts = self.contiguous_counts.items; if (counts.len == 0) return null; var zero = PairCount{ .w1 = 0, .w2 = 0, .count = -1, }; var max_p: *PairCount = &zero; for (counts) |*x| { if (x.count > max_p.count) { max_p = x; } else if (x.count == max_p.count) { if (x.w1 < max_p.w1) { max_p = x; } else if (x.w1 == max_p.w1 and x.w2 < max_p.w2) { max_p = x; } } } if (max_p.count <= 0) return null; return max_p; } /// Replaces a pair by a fixed entry, and update all counters. fn mergeCounts(self: *LearnBpeState, merge: *PairCount) !void { const trace = tracy.trace(@src()); defer trace.end(); merge.count = -1; var tokens = self.index.tokens.items; // TODO: find this string somewhere else ? var new_token = try strConcat(self.allocator, tokens[merge.w1], tokens[merge.w2]); var new_token_id = try self.index.getOrPut(new_token, false); var word_parts = self.word_parts.items; var where_it = self.pair_loc.get(.{ .w1 = merge.w1, .w2 = merge.w2 }).?.iterator(); while (where_it.next()) |wi| { var parts = &word_parts[wi.key]; var cwi = self.word_counts.items[wi.key]; try self.ensureExtraCapacity(parts.items.len); var cur_pair = WordPair{ .w2 = parts.items[0] }; var j: usize = 0; while (j < parts.items.len) : (j += 1) { const w = parts.items[j]; if (j == 0) continue; cur_pair.w1 = cur_pair.w2; cur_pair.w2 = w; if (cur_pair.w1 != merge.w1 or cur_pair.w2 != merge.w2) continue; // we've found the pair, get the string // change count for word before us. if (j > 1) { const w0 = parts.items[j - 2]; try self.incCount(w0, cur_pair.w1, -cwi, wi.key); try self.incCount(w0, new_token_id, cwi, wi.key); } // Remove [w1, w2] from parts insert w1@@w2 instead. // TODO only mark the token and remove later. parts.items[j - 1] = new_token_id; // update count for next token if (j + 1 < parts.items.len) { const w3 = parts.items[j + 1]; try self.incCount(cur_pair.w2, w3, -cwi, wi.key); try self.incCount(new_token_id, w3, cwi, wi.key); } _ = parts.orderedRemove(j); cur_pair.w2 = new_token_id; } } } fn getCount(self: *const LearnBpeState, w1: str, w2: str) i32 { var w1_id: u32 = self.index.ids.get(w1).?; if (w2.len == 0) { return self.word_counts.items[w1_id]; } else { var w2_id = self.index.ids.get(w2).?; return self.pairs.get(.{ .w1 = w1_id, .w2 = w2_id }).?.count; } } /// Increments the count for the pair (w1, w2), found in word 'wid'. fn incCount(self: *LearnBpeState, w1: u32, w2: u32, count: i32, wid: u32) !void { const trace = tracy.trace(@src()); defer trace.end(); if (count == 0) return; const pair = WordPair{ .w1 = w1, .w2 = w2 }; var tokens = self.index.tokens.items; debug(MERGE_PAIRS, "incCount({}, {}, {}, {})", .{ tokens[w1], tokens[w2], count, wid }); if (self.pairs.get(pair)) |kv| { // assert(kv.value.count + count >= 0); debug(MERGE_PAIRS, "Incrementing count of ({}, {}, {}) by {}", .{ tokens[w1], tokens[w2], kv.count, count }); const old_count = kv.count; kv.count += count; if (count > 0) { var loc = self.pair_loc.getEntry(pair) orelse unreachable; _ = try loc.value.put(wid, {}); } // TODO: should we remove from `pair_loc` if kv.value.count falls to 0 ? } else { // can't decrement from inexisting pair. assert(count > 0); debug(MERGE_PAIRS, "Creating PairCount ({}, {}, {})", .{ tokens[w1], tokens[w2], count }); const pc = PairCount.init(pair, count); const pc_ptr: *PairCount = try self.contiguous_counts.addOne(); pc_ptr.* = pc; // TODO: handle case where index is full _ = try self.pairs.put(pair, pc_ptr); var loc = std.AutoHashMap(u32, void).init(self.allocator); _ = try loc.put(wid, {}); _ = try self.pair_loc.put(pair, loc); } } }; /// Learns BPE from the given files. /// TODO: allow to write to a file pub fn learnbpe(n_pairs: i32, inputFile1: str, inputFile2: str, base_allocator: *Allocator) !void { // get vocab debug(LEARN_BPE, "Extracting vocabulary...", .{}); var arena = std.heap.ArenaAllocator.init(base_allocator); defer arena.deinit(); var allocator = &arena.allocator; var word_count = Vocab.init(allocator); defer word_count.deinit(); try readWords(inputFile1, &word_count); if (inputFile2.len > 0) { try readWords(inputFile2, &word_count); } debug(LEARN_BPE, "Vocabulary extrated, found {} words.", .{word_count.count()}); // a token is an int, it represents a string const reservation = @intCast(u32, 20 * n_pairs); var state = LearnBpeState.init(allocator); defer state.deinit(); try state.ensureExtraCapacity(reservation); debug(LEARN_BPE, "Initializing counters for 1-char tokens...", .{}); try initSingleChars(&word_count, &state); debug(LEARN_BPE, "Counter initialized, found {} tokens", .{state.index.count()}); debug(LEARN_BPE, "Counting pairs of chars ...", .{}); try countPairsOfChars(&state); debug(LEARN_BPE, "Found {} pairs.", .{state.pairs.count()}); debug(LEARN_BPE, "Recursively merging top pairs ...", .{}); try printSortedBytePairs(&state, n_pairs, std.io.getStdOut()); } fn printSortedBytePairs(state: *LearnBpeState, n_pairs: i32, file: std.fs.File) !void { const trace = tracy.trace(@src()); defer trace.end(); const print = file.writer().print; var tokens = &state.index.tokens; var i: usize = 0; while (i < n_pairs) : (i += 1) { var max_p = (state.popMaxPair()) orelse break; _ = try print("{} {} {}\n", .{ tokens.items[max_p.w1], tokens.items[max_p.w2], max_p.count }); } } fn initSingleChars(word_count: *Vocab, state: *LearnBpeState) !void { try state.word_parts.ensureCapacity(word_count.count()); var idx = &state.index; var word_counts = &state.word_counts; try word_counts.ensureCapacity(word_count.count()); var wc_it = word_count.iterator(); while (wc_it.next()) |wc| { var realLength: i32 = 0; var word: str = wc.key; var current_word = std.ArrayList(u32).init(state.allocator); try current_word.ensureCapacity(word.len); word_counts.appendAssumeCapacity(wc.value); var lastStart: usize = 0; // TODO: try std.unicode.Utf8Iterator for (word) |char, pos| { if (pos == 0) continue; if ((char & 0xc0) == 0x80) // continuation byte continue; realLength += 1; var id = try idx.getOrPut(word[lastStart..pos], false); current_word.appendAssumeCapacity(id); lastStart = pos; } var id = try idx.getOrPut(word[lastStart..], true); current_word.appendAssumeCapacity(id); state.word_parts.appendAssumeCapacity(current_word); } } test "init single chars" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var vocab = Vocab.init(allocator); defer vocab.deinit(); try vocab.put("hello", 1); try vocab.put("world", 2); var state = LearnBpeState.init(allocator); defer state.deinit(); try state.ensureExtraCapacity(16); try initSingleChars(&vocab, &state); // 8 because there are 7 unique chars, but "o" appears both at the end // and in the middle of a word. testing.expectEqual(state.index.ids.count(), 8); testing.expect(state.index.ids.contains("h")); testing.expect(state.index.ids.contains("e")); testing.expect(state.index.ids.contains("l")); testing.expect(state.index.ids.contains("o</w>")); testing.expect(state.index.ids.contains("w")); testing.expect(state.index.ids.contains("o")); testing.expect(state.index.ids.contains("r")); testing.expect(state.index.ids.contains("d</w>")); } fn expectContainsPair(state: *LearnBpeState, w1: str, w2: str) void { const w1_id = state.index.ids.get(w1) orelse failTest("Index doesn't contain ({0}, {1}), {0} is unknow.", .{ w1, w2 }); const w2_id = state.index.ids.get(w2) orelse failTest("Index doesn't contain ({0}, {1}), {1} is unknow.", .{ w1, w2 }); const pair: WordPair = .{ .w1 = w1_id, .w2 = w2_id }; if (!state.pairs.contains(pair)) { failTest("Index doesn't contain ({} ({}), {} ({}))", .{ w1, w1_id, w2, w2_id }); } } fn expectPairIs(state: *LearnBpeState, pair: PairCount, w1: str, w2: str) void { expectContainsPair(state, w1, w2); var w1_id = state.index.ids.get(w1).?; var w2_id = state.index.ids.get(w2).?; if (w1_id != pair.w1 or w2_id != pair.w2) { log.err("Pair({}, {}) != ({}, {})", .{ state.index.tokens.items[pair.w1], state.index.tokens.items[pair.w2], w1, w2 }); log.err("Pair({}, {}) != ({}, {})", .{ pair.w1, pair.w2, w1_id, w2_id }); assert((w1_id == pair.w1 and w2_id == pair.w2)); return; } debug(MERGE_PAIRS, "Pair({}, {}) is ({}, {})", .{ pair.w1, pair.w2, w1, w2 }); } test "init count pair of chars" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var vocab = Vocab.init(allocator); defer vocab.deinit(); try vocab.put("hello", 1); try vocab.put("world", 2); var state = LearnBpeState.init(allocator); defer state.deinit(); try state.ensureExtraCapacity(16); try initSingleChars(&vocab, &state); assert(state.index.ids.count() == 8); try countPairsOfChars(&state); // 5 chars in a word -> 4 bigrams. All bigrams are distinct. assert(state.pairs.count() == 8); expectContainsPair(&state, "h", "e"); expectContainsPair(&state, "e", "l"); expectContainsPair(&state, "l", "o</w>"); } fn countPairsOfChars(state: *LearnBpeState) !void { const trace = tracy.trace(@src()); defer trace.end(); var word_counts = state.word_counts.items; debug(COUNT_PAIRS_OF_CHARS, "Will counts pairs of chars from {} full words", .{state.word_parts.items.len}); for (state.word_parts.items) |word, wi| { const count = word_counts[wi]; try countPairsOfCharFromWord(word, @intCast(u32, wi), word_counts[wi], state); } debug(COUNT_PAIRS_OF_CHARS, "Done Counting", .{}); } fn countPairsOfCharFromWord(word: std.ArrayList(u32), wi: u32, count: i32, state: *LearnBpeState) !void { const trace = tracy.trace(@src()); defer trace.end(); var first_round = true; var cur_pair = WordPair{}; // Use pointers to actually modify the state. var pairs = &state.pairs; var pair_loc = &state.pair_loc; var contiguous_counts = &state.contiguous_counts; debug(COUNT_PAIRS_OF_CHARS, "Counting from @{} (len: {}, count: {})", .{ wi, word.items.len, count }); try contiguous_counts.ensureCapacity(contiguous_counts.items.len + word.items.len); for (word.items) |token, i| { cur_pair.w1 = cur_pair.w2; cur_pair.w2 = token; if (i == 0) // cur_pair.w1 isn't correctly initialized continue; if (pairs.get(cur_pair)) |pair| { pair.count += count; var w = pair_loc.getEntry(cur_pair) orelse unreachable; assert(count > 0); _ = try w.value.put(@intCast(u32, wi), {}); } else { const pair = PairCount.init(cur_pair, count); var pc_ptr: *PairCount = contiguous_counts.addOneAssumeCapacity(); pc_ptr.* = pair; // TODO: handle too many pairs _ = try pairs.put(cur_pair, pc_ptr); var set = std.AutoHashMap(u32, void).init(state.allocator); if (count > 0) _ = try set.put(wi, {}); _ = try pair_loc.put(cur_pair, set); } } } test "find pair with the highest count" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var vocab = Vocab.init(allocator); defer vocab.deinit(); try vocab.put("hello", 1); try vocab.put("wor_", 2); try vocab.put("wo_", 2); var state = LearnBpeState.init(allocator); defer state.deinit(); try state.ensureExtraCapacity(16); try initSingleChars(&vocab, &state); try countPairsOfChars(&state); var max_pair = state.popMaxPair().?; expectPairIs(&state, max_pair, "w", "o"); expectContainsPair(&state, "w", "o"); // TODO: also check that the word "wor_" is not currently split as "wo r _" in word_parts expectContainsPair(&state, "wo", "r"); expectContainsPair(&state, "wo", "_</w>"); max_pair = state.popMaxPair().?; expectPairIs(&state, max_pair, "r", "_</w>"); } pub fn strConcat(allocator: *Allocator, a: str, b: str) ![]u8 { return try std.mem.concat(allocator, u8, &[_]str{ a, b }); } pub fn resolve(file_path: str) std.fs.File { // var realpath_buff: [1024]u8 = undefined; // const realpath = try std.fs.realpath(fp, &realpath_buff); if (std.mem.eql(u8, file_path, "-")) { return std.io.getStdIn(); } return std.fs.openFileAbsolute(file_path, .{ .read = true }) catch |e| { log.err("Error '{}' when opening {}\n", .{ e, file_path }); std.process.exit(1); }; }
fastBPE/learnBPE.zig
const std = @import("std"); const EPS = 3e-9; pub const Point = struct { x: f32, y: f32, }; pub fn isCounterClockWise(poly: []const Point) bool { var seq: f32 = 0; for (poly) |a, idx| { const b = poly[(idx + 1) % poly.len]; seq += (b.x - a.x) * (b.y + a.y); } return if (seq < 0) true else false; } /// Checks if the point `p` lies on the left, or right side of the line AB /// return: -1: right side /// 0: on the line /// 1: left side pub fn pointLineDirection(a: Point, b: Point, p: Point) i2 { const nom = (p.y - a.y) * (b.x - a.x); const dom = (p.x - a.x) * (b.y - a.y); if (std.math.absFloat(nom - dom) < EPS) { return 0; } else if (nom > dom) return 1 else return -1; } /// Checks if point `p` resides inside, on, or outside the closed polygon `poly` /// return: -1: outside /// 0: on /// 1: inside pub fn pointInPolygon(p: Point, poly: []const Point) i2 { var wm: i32 = 0; for (poly) |a, idx| { const b = poly[(idx + 1) % poly.len]; const in_line = pointLineDirection(a, b, p); // P lies on AB (and therefore POLY) if (in_line == 0) return 0; if (a.y <= p.y) { if ((b.y > p.y) and (in_line == 1)) wm += 1; } else if ((b.y < p.y) and (in_line == -1)) wm -= 1; } return if (wm != 0) 1 else -1; } const expect = @import("std").testing.expect; // https://i.imgur.com/7VeyP0C.png test "direction int" { const a = Point{ .x = 0, .y = 0 }; const b = Point{ .x = 0, .y = 4 }; const p_left = Point{ .x = -1, .y = 3 }; const p_right = Point{ .x = 3, .y = 1 }; const p_on = Point{ .x = 0, .y = 2 }; try expect(pointLineDirection(a, b, p_left) == 1); try expect(pointLineDirection(a, b, p_right) == -1); try expect(pointLineDirection(a, b, p_on) == 0); } // https://i.imgur.com/LCjoSFw.png test "direction float" { const a = Point{ .x = 51.41115357611, .y = 35.7190335556 }; const b = Point{ .x = 51.41141214984, .y = 35.71968303418 }; const p_left = Point{ .x = 51.41104409394, .y = 35.71947343327 }; const p_right = Point{ .x = 51.41155781799, .y = 35.71922272608 }; const p_on = Point{ .x = 51.41124340764, .y = 35.71925919263 }; try expect(pointLineDirection(a, b, p_left) == 1); try expect(pointLineDirection(a, b, p_right) == -1); try expect(pointLineDirection(a, b, p_on) == 0); } // https://i.imgur.com/9dDG7DG.png test "in polygon int" { const poly = [_]Point{ .{ .x = -2, .y = -1 }, .{ .x = 1, .y = -1 }, .{ .x = 2, .y = 1 }, .{ .x = -1, .y = 1 }, }; const p_in = Point{ .x = 0, .y = 0 }; const p_out = Point{ .x = 2, .y = 0 }; const p_on = Point{ .x = 0, .y = 1 }; try expect(pointInPolygon(p_in, poly[0..]) == 1); try expect(pointInPolygon(p_out, poly[0..]) == -1); try expect(pointInPolygon(p_on, poly[0..]) == 0); } // https://i.imgur.com/OrFLrs0.png test "in polygon float" { const poly = [_]Point{ .{ .x = 51.41469955416, .y = 35.72200728582 }, .{ .x = 51.41348706955, .y = 35.7213489078 }, .{ .x = 51.4137390144, .y = 35.72041566362 }, .{ .x = 51.41422715756, .y = 35.71981480199 }, .{ .x = 51.41542389562, .y = 35.72070970064 }, .{ .x = 51.41506172489, .y = 35.72106765728 }, .{ .x = 51.41429014377, .y = 35.72081197413 }, .{ .x = 51.41463656795, .y = 35.71954633044 }, .{ .x = 51.41606950431, .y = 35.71895824674 }, .{ .x = 51.4166836199, .y = 35.72002574329 }, .{ .x = 51.4171560165, .y = 35.72024307617 }, .{ .x = 51.41743945447, .y = 35.71973809593 }, .{ .x = 51.41747094757, .y = 35.71904773801 }, .{ .x = 51.41683321216, .y = 35.71889432433 }, .{ .x = 51.41632932245, .y = 35.7201791548 }, .{ .x = 51.41718750961, .y = 35.72198171784 }, .{ .x = 51.41663638024, .y = 35.72199450183 }, .{ .x = 51.41550262839, .y = 35.7213489078 }, }; const p_out = [_]Point{ .{ .x = 51.41658156842, .y = 35.72015209299 }, .{ .x = 51.41373037219, .y = 35.7217090877 }, }; const p_in = [_]Point{ .{ .x = 51.41448139071, .y = 35.7213258319 }, .{ .x = 51.41477106929, .y = 35.72068997161 }, .{ .x = 51.41571520686, .y = 35.71994086942 }, }; const p_on = [_]Point{ .{ .x = 51.4171560165, .y = 35.72024307617 }, .{ .x = 51.41743945447, .y = 35.71973809593 }, .{ .x = 51.41747094757, .y = 35.71904773801 }, }; for (p_out) |p| try expect(pointInPolygon(p, poly[0..]) == -1); for (p_in) |p| try expect(pointInPolygon(p, poly[0..]) == 1); for (p_on) |p| try expect(pointInPolygon(p, poly[0..]) == 0); }
src/winding_number.zig
const std = @import("std"); const testing = std.testing; const Tree = @import("tree.zig").Tree; const Merk = @import("merk.zig").Merk; // TODO: change these as config pub const BatcSizeLimit = 10_000; pub const BatchKeyLimit = 1024; pub const BatchValueLimit = 1024; pub const OpTag = enum(u1) { Put, Del }; pub const OpError = error{DeleteNonexistantKey}; pub const Op = struct { const Self = @This(); op: OpTag, key: []const u8, val: []const u8, }; pub fn applyTo(tree: ?*Tree, batch: []Op) OpError!?*Tree { if (tree) |t| return try apply(t, batch); return try build(batch); } pub fn build(batch: []Op) OpError!*Tree { var mid_index: usize = batch.len / 2; if (batch[mid_index].op == OpTag.Del) return error.DeleteNonexistantKey; var mid_tree = Tree.init(batch[mid_index].key, batch[mid_index].val) catch unreachable; return try recurse(mid_tree, batch, mid_index, true); } pub fn apply(tree: *Tree, batch: []Op) !?*Tree { var found: bool = false; var mid: usize = 0; binaryBatchSearch(tree.key(), batch, &found, &mid); if (found) { if (batch[mid].op == OpTag.Put) { tree.updateVal(batch[mid].val); } else if (batch[mid].op == OpTag.Del) { var maybe_tree = remove(tree); var left_batch = batch[0..mid]; var right_batch = batch[mid+1..]; if (left_batch.len != 0) { maybe_tree = try applyTo(maybe_tree, left_batch); } if (right_batch.len != 0) { maybe_tree = try applyTo(maybe_tree, right_batch); } return maybe_tree; } } return try recurse(tree, batch, mid, found); } pub fn recurse(tree: *Tree, batch: []Op, mid: usize, exclusive: bool) OpError!*Tree { var left_batch = batch[0..mid]; var right_batch = if (exclusive) batch[mid + 1 ..] else batch[mid..]; if (left_batch.len != 0) { var detached = tree.detach(true); var applied = try applyTo(detached, left_batch); tree.attach(true, applied); } if (right_batch.len != 0) { var detached = tree.detach(false); var applied = try applyTo(detached, right_batch); tree.attach(false, applied); } return balance(tree); } pub fn balance(tree: *Tree) *Tree { var factor = balanceFactor(tree); if (-1 <= factor and factor <= 1) return tree; var is_left = factor < 0; var child_left = balanceFactor(tree.child(is_left)) > 0; if ((is_left and child_left) or (!is_left and !child_left)) { // Note: expected to have child var child = tree.detach(is_left).?; var rotated = rotate(child, !is_left); tree.attach(is_left, rotated); } return rotate(tree, is_left); } pub fn balanceFactor(tree: ?*Tree) i16 { if (tree) |t| return t.balanceFactor(); return 0; } pub fn rotate(tree: *Tree, is_left: bool) *Tree { // Note: expected to have child var child = tree.detach(is_left).?; if (child.detach(!is_left)) |grand_child| tree.attach(is_left, grand_child); var balanced = balance(tree); child.attach(!is_left, balanced); var balanced_child = balance(child); return balanced_child; } pub fn remove(tree: *Tree) ?*Tree { var has_left = if (tree.link(true)) |_| true else false; var has_right = if (tree.link(false)) |_| true else false; // no child if (!has_left and !has_right) return null; var is_left = tree.childHeight(true) > tree.childHeight(false); // single child if (!(has_left and has_right)) return tree.detach(is_left); // two child, promote edge of taller child var tall_child = tree.detach(is_left).?; var short_child = tree.detach(!is_left).?; return promoteEdge(tall_child, short_child, !is_left); } pub fn promoteEdge(tree: *Tree, attach: *Tree, is_left: bool) *Tree { var edge = removeEdge(tree, is_left); var _edge = edge.edge; _edge.attach(!is_left, edge.child); _edge.attach(is_left, attach); return balance(_edge); } const Edge = struct { edge: *Tree, child: ?*Tree, }; pub fn removeEdge(tree: *Tree, is_left: bool) Edge { if (tree.link(is_left)) |_| {} else { return .{ .edge = tree, .child = tree.detach(!is_left) }; } var child = tree.detach(is_left).?; var edge = removeEdge(child, is_left); tree.attach(is_left, edge.child); return .{ .edge = edge.edge, .child = balance(tree) }; } pub fn binaryBatchSearch(needle: []const u8, batch: []Op, found: *bool, index: *usize) void { var low: usize = 0; var high: usize = batch.len - 1; while (low <= high) { const median = (low + high) / 2; if (std.mem.eql(u8, batch[median].key, needle)) { found.* = true; index.* = median; return; } else if (std.mem.lessThan(u8, batch[median].key, needle)) { low = median + 1; } else { if (median == 0) break; high = median - 1; } } found.* = false; index.* = low; return; } pub fn sortBatch(batch: []Op) void { std.sort.sort(Op, batch, {}, batchCmpLessThan); } fn batchCmpLessThan(context: void, a: Op, b: Op) bool { return std.mem.lessThan(u8, a.key, b.key); } test "apply" { // insert & update case var buf: [65536]u8 = undefined; var buffer = std.heap.FixedBufferAllocator.init(&buf); var arena = std.heap.ArenaAllocator.init(&buffer.allocator); Merk.stack_allocator = &arena.allocator; defer arena.deinit(); var op0 = Op{ .op = OpTag.Put, .key = "key0", .val = "value" }; var op1 = Op{ .op = OpTag.Put, .key = "key1", .val = "value" }; var op2 = Op{ .op = OpTag.Put, .key = "key2", .val = "value" }; var op3 = Op{ .op = OpTag.Put, .key = "key3", .val = "value" }; var op4 = Op{ .op = OpTag.Put, .key = "key4", .val = "value" }; var op5 = Op{ .op = OpTag.Put, .key = "key5", .val = "value" }; var op6 = Op{ .op = OpTag.Put, .key = "key6", .val = "value" }; var op7 = Op{ .op = OpTag.Put, .key = "key7", .val = "value" }; var op8 = Op{ .op = OpTag.Put, .key = "key8", .val = "value" }; var op9 = Op{ .op = OpTag.Put, .key = "key9", .val = "value" }; var batch1 = [_]Op{ op3, op6, op8 }; var tree = try applyTo(null, &batch1); testing.expect(tree.?.verify()); testing.expectEqualSlices(u8, tree.?.key(), "key6"); testing.expectEqualSlices(u8, tree.?.child(true).?.key(), "key3"); testing.expectEqualSlices(u8, tree.?.child(false).?.key(), "key8"); var batch2 = [_]Op{ op0, op1, op2, op3, op6, op8 }; tree = try applyTo(tree, &batch2); testing.expect(tree.?.verify()); testing.expectEqualSlices(u8, tree.?.key(), "key3"); testing.expectEqualSlices(u8, tree.?.child(true).?.key(), "key1"); testing.expectEqualSlices(u8, tree.?.child(true).?.child(true).?.key(), "key0"); testing.expectEqualSlices(u8, tree.?.child(true).?.child(false).?.key(), "key2"); testing.expectEqualSlices(u8, tree.?.child(false).?.key(), "key6"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(false).?.key(), "key8"); var batch3 = [_]Op{ op0, op4, op5, op7, op9 }; tree = try applyTo(tree, &batch3); testing.expect(tree.?.verify()); testing.expectEqualSlices(u8, tree.?.key(), "key3"); testing.expectEqualSlices(u8, tree.?.child(true).?.key(), "key1"); testing.expectEqualSlices(u8, tree.?.child(true).?.child(true).?.key(), "key0"); testing.expectEqualSlices(u8, tree.?.child(true).?.child(false).?.key(), "key2"); testing.expectEqualSlices(u8, tree.?.child(false).?.key(), "key6"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(true).?.key(), "key5"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(true).?.child(true).?.key(), "key4"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(false).?.key(), "key8"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(false).?.child(true).?.key(), "key7"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(false).?.child(false).?.key(), "key9"); // TODO: delete case var op10 = Op{ .op = OpTag.Del, .key = "key0", .val = undefined }; var op11 = Op{ .op = OpTag.Del, .key = "key1", .val = undefined }; var op12 = Op{ .op = OpTag.Del, .key = "key2", .val = undefined }; var op13 = Op{ .op = OpTag.Del, .key = "key3", .val = undefined }; var op14 = Op{ .op = OpTag.Del, .key = "key4", .val = undefined }; var op15 = Op{ .op = OpTag.Del, .key = "key5", .val = undefined }; var op16 = Op{ .op = OpTag.Del, .key = "key6", .val = undefined }; var op17 = Op{ .op = OpTag.Del, .key = "key7", .val = undefined }; var op18 = Op{ .op = OpTag.Del, .key = "key8", .val = undefined }; var op19 = Op{ .op = OpTag.Del, .key = "key9", .val = undefined }; var batch4 = [_]Op{ op11, op15, op16, op19 }; tree = try applyTo(tree, &batch4); testing.expectEqualSlices(u8, tree.?.key(), "key3"); testing.expectEqualSlices(u8, tree.?.child(true).?.key(), "key2"); testing.expectEqualSlices(u8, tree.?.child(true).?.child(true).?.key(), "key0"); testing.expectEqualSlices(u8, tree.?.child(false).?.key(), "key7"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(true).?.key(), "key4"); testing.expectEqualSlices(u8, tree.?.child(false).?.child(false).?.key(), "key8"); var batch5 = [_]Op{ op12, op13, op17 }; tree = try applyTo(tree, &batch5); testing.expect(tree.?.verify()); var batch6 = [_]Op{ op10, op14, op18 }; tree = try applyTo(tree, &batch6); testing.expect(tree == null); } test "build" { var batch = [_]Op{ Op{ .op = OpTag.Put, .key = "key2", .val = "value2" }, Op{ .op = OpTag.Put, .key = "key3", .val = "value3" }, Op{ .op = OpTag.Put, .key = "key5", .val = "value5" }, }; Merk.stack_allocator = testing.allocator; var tree = try build(&batch); testing.expectEqualSlices(u8, tree.key(), "key3"); testing.expectEqualSlices(u8, tree.child(true).?.key(), "key2"); testing.expectEqualSlices(u8, tree.child(false).?.key(), "key5"); Merk.stack_allocator.destroy(tree); Merk.stack_allocator.destroy(tree.child(true).?); Merk.stack_allocator.destroy(tree.child(false).?); } test "binaryBatchSearch" { var batch = [_]Op{ Op{ .op = OpTag.Put, .key = "key2", .val = "value" }, Op{ .op = OpTag.Put, .key = "key3", .val = "value" }, Op{ .op = OpTag.Del, .key = "key5", .val = undefined }, }; var found: bool = false; var index: usize = 0; binaryBatchSearch("key3", &batch, &found, &index); testing.expect(found); testing.expectEqual(index, 1); binaryBatchSearch("key5", &batch, &found, &index); testing.expect(found); testing.expectEqual(index, 2); binaryBatchSearch("key4", &batch, &found, &index); testing.expect(!found); testing.expectEqual(index, 2); binaryBatchSearch("key1", &batch, &found, &index); testing.expect(!found); testing.expectEqual(index, 0); binaryBatchSearch("key6", &batch, &found, &index); testing.expect(!found); testing.expectEqual(index, 3); } test "sortBatch" { var batch = [_]Op{ Op{ .op = OpTag.Put, .key = "key0", .val = "value" }, Op{ .op = OpTag.Put, .key = "key9", .val = "value" }, Op{ .op = OpTag.Put, .key = "key6", .val = "value" }, Op{ .op = OpTag.Put, .key = "key8", .val = "value" }, Op{ .op = OpTag.Put, .key = "key2", .val = "value" }, }; sortBatch(&batch); var i: usize = 0; while (i < batch.len - 1) : (i += 1) { testing.expect(batchCmpLessThan({}, batch[i], batch[i + 1])); } }
src/ops.zig
const std = @import("std"); const builtin = @import("builtin"); const lola = @import("lola"); // This is required for the runtime library to be able to provide // object implementations. pub const ObjectPool = lola.runtime.ObjectPool([_]type{ lola.libs.runtime.LoLaDictionary, lola.libs.runtime.LoLaList, }); pub fn main() !u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const argv = try std.process.argsAlloc(gpa.allocator()); defer std.process.argsFree(gpa.allocator(), argv); if (argv.len != 3) { return 1; } const date_time = std.time.epoch.EpochSeconds{ .secs = @intCast(u64, std.time.timestamp()), }; const time = date_time.getDaySeconds(); const date = date_time.getEpochDay(); const year_day = date.calculateYearDay(); const month_day = year_day.calculateMonthDay(); var files = std.ArrayList(Benchmark).init(gpa.allocator()); defer files.deinit(); var string_arena = std.heap.ArenaAllocator.init(gpa.allocator()); defer string_arena.deinit(); const date_string = try std.fmt.allocPrint(string_arena.allocator(), "{d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}:{d:0>2}", .{ year_day.year, month_day.month.numeric(), month_day.day_index, time.getHoursIntoDay(), time.getMinutesIntoHour(), time.getSecondsIntoMinute(), }); { var dir = try std.fs.cwd().openDir(argv[1], .{ .iterate = true }); defer dir.close(); var iterator = dir.iterate(); while (try iterator.next()) |entry| { const name = try string_arena.allocator().dupe(u8, entry.name); const source = try dir.readFileAlloc(string_arena.allocator(), entry.name, size(1.5, .MeBi)); // 1 MB source const target_file = try std.fmt.allocPrint(string_arena.allocator(), "{s}-{s}.csv", .{ name[0 .. name.len - std.fs.path.extension(name).len], @tagName(builtin.mode), }); try files.append(Benchmark{ .file_name = name, .source_code = source, .target_file = target_file, }); } } var output_dir = try std.fs.cwd().openDir(argv[2], .{ .iterate = true }); defer output_dir.close(); for (files.items) |benchmark| { const result = benchmark.run(gpa.allocator()) catch |err| { std.log.warn("failed to run benchmark {s}: {s}", .{ benchmark.file_name, @errorName(err), }); continue; }; var file: std.fs.File = if (output_dir.openFile(benchmark.target_file, .{ .mode = .write_only })) |file| file else |_| blk: { var file = try output_dir.createFile(benchmark.target_file, .{}); try file.writeAll("time;compile;setup;run\n"); break :blk file; }; defer file.close(); try file.seekFromEnd(0); try file.writer().print("{s};{d};{d};{d}\n", .{ date_string, result.compile_time, result.setup_time, result.run_time }); } return 0; } pub const Unit = enum(u64) { base = 1, kilo = 1000, KiBi = 1024, mega = 1000 * 1000, MeBi = 1024 * 1024, giga = 1000 * 1000 * 1000, GiBi = 1024 * 1024 * 1024, tera = 1000 * 1000 * 1000 * 1000, TeBi = 1024 * 1024 * 1024 * 1024, }; pub fn size(comptime val: comptime_float, comptime unit: Unit) usize { return @floatToInt(usize, std.math.floor(@as(f64, @as(comptime_int, @enumToInt(unit)) * val))); } pub const BenchmarkResult = struct { build_mode: std.builtin.Mode = builtin.mode, compile_time: u128, setup_time: u128, run_time: u128, }; const Benchmark = struct { file_name: []const u8, source_code: []const u8, target_file: []const u8, pub fn run(self: Benchmark, allocator: std.mem.Allocator) !BenchmarkResult { std.log.info("Running benchmark {s}...", .{self.file_name}); var result = BenchmarkResult{ .compile_time = undefined, .setup_time = undefined, .run_time = undefined, }; const compile_start = std.time.nanoTimestamp(); var diagnostics = lola.compiler.Diagnostics.init(allocator); defer { for (diagnostics.messages.items) |msg| { std.debug.print("{}\n", .{msg}); } diagnostics.deinit(); } // This compiles a piece of source code into a compile unit. // A compile unit is a piece of LoLa IR code with metadata for // all existing functions, debug symbols and so on. It can be loaded into // a environment and be executed. var compile_unit = (try lola.compiler.compile(allocator, &diagnostics, self.file_name, self.source_code)) orelse return error.SyntaxError; defer compile_unit.deinit(); const setup_start = std.time.nanoTimestamp(); result.compile_time = @intCast(u128, setup_start - compile_start); var pool = ObjectPool.init(allocator); defer pool.deinit(); var env = try lola.runtime.Environment.init(allocator, &compile_unit, pool.interface()); defer env.deinit(); try env.installModule(lola.libs.std, lola.runtime.Context.null_pointer); try env.installModule(lola.libs.runtime, lola.runtime.Context.null_pointer); var vm = try lola.runtime.VM.init(allocator, &env); defer vm.deinit(); const runtime_start = std.time.nanoTimestamp(); result.setup_time = @intCast(u128, runtime_start - setup_start); while (true) { var res = try vm.execute(1_000_000); pool.clearUsageCounters(); try pool.walkEnvironment(env); try pool.walkVM(vm); pool.collectGarbage(); if (res == .completed) break; } result.run_time = @intCast(u128, std.time.nanoTimestamp() - runtime_start); return result; } };
src/benchmark/perf.zig
const std = @import("std"); const assert = std.debug.assert; pub fn EncodedType(comptime T: type) type { comptime assert(@typeInfo(T) == .Int); comptime assert(@typeInfo(T).Int.signedness == .unsigned); const num_bits = @typeInfo(T).Int.bits; const num_bytes_ceil = try std.math.divCeil(comptime_int, num_bits, 8); const num_zero_bits_available = (num_bytes_ceil * 8) - num_bits; const num_zero_bits_needed = num_bytes_ceil; var num_bytes_needed = num_bytes_ceil; if (num_zero_bits_needed > num_zero_bits_available) { num_bytes_needed += 1; } return std.meta.Int(.unsigned, num_bytes_needed * 8); } pub fn DecodedType(comptime T: type) type { comptime assert(@typeInfo(T) == .Int); comptime assert(@typeInfo(T).Int.signedness == .unsigned); const num_bits = @typeInfo(T).Int.bits; comptime assert(num_bits % 8 == 0); const num_bytes = num_bits / 8; // every byte has 1 unavailable bit const num_available_bits = num_bits - num_bytes; return std.meta.Int(.unsigned, num_available_bits); } pub fn decode(comptime T: type, x: T) DecodedType(T) { const OutType = DecodedType(T); var out: T = 0; var mask: T = 0x7F << (@typeInfo(T).Int.bits - 8); while (mask != 0) { out >>= 1; out |= x & mask; mask >>= 8; } return @truncate(OutType, out); } pub fn encode(comptime T: type, x: T) EncodedType(T) { const OutType = EncodedType(T); var in: OutType = x; var out: OutType = undefined; // compute masks at compile time so that we can handle any // sized integer without any runtime cost const byte_count = @typeInfo(OutType).Int.bits / 8; const byte_masks = comptime blk: { var masks_array: [byte_count]OutType = undefined; masks_array[0] = 0x7F; const ByteCountType = std.math.Log2Int(OutType); var byte_index: ByteCountType = 1; while (byte_index < byte_count) : (byte_index += 1) { const prev_mask = masks_array[byte_index - 1]; masks_array[byte_index] = ((prev_mask + 1) << 8) - 1; } break :blk &masks_array; }; inline for (byte_masks) |mask| { out = in & ~mask; out <<= 1; out |= in & mask; in = out; } return out; } /// Returns true if the given slice has no non-synchsafe /// bytes within it. pub fn isSliceSynchsafe(bytes: []const u8) bool { for (bytes) |byte| { // if any byte has its most significant bit set, // then it's not synchsafe if (byte & (1 << 7) != 0) { return false; } } return true; } /// Returns true if the given integer has no non-synchsafe /// bytes within it. pub fn areIntBytesSynchsafe(comptime T: type, x: T) bool { comptime assert(@typeInfo(T) == .Int); comptime assert(@typeInfo(T).Int.signedness == .unsigned); const num_bits = @typeInfo(T).Int.bits; if (num_bits < 8) return true; const mask: T = comptime mask: { const num_bytes = num_bits / 8; var mask: T = 1 << 7; var i: usize = 1; inline while (i < num_bytes) : (i += 1) { mask <<= 8; mask |= 1 << 7; } break :mask mask; }; return x & mask == 0; } /// Returns true if the integer is small enough that synchsafety /// is irrelevant. That is, the encoded and decoded forms of the /// integer are guaranteed to be equal. /// /// Note: Any number for which this function returns false /// has the opposite guarantee--the encoded and decoded values /// will always differ. pub fn isBelowSynchsafeThreshold(comptime T: type, x: T) bool { comptime assert(@typeInfo(T) == .Int); comptime assert(@typeInfo(T).Int.signedness == .unsigned); return std.math.maxInt(T) < 128 or x < 128; } fn testEncodeAndDecode(comptime T: type, encoded: T, decoded: DecodedType(T)) !void { try std.testing.expectEqual(encoded, encode(DecodedType(T), decoded)); try std.testing.expectEqual(decoded, decode(T, encoded)); } test "decode and encode" { try testEncodeAndDecode(u24, 0x037F7F, 0xFFFF); try testEncodeAndDecode(u16, 0x17F, 0xFF); } test "encoded and decoded types" { try std.testing.expectEqual(u28, DecodedType(u32)); try std.testing.expectEqual(u14, DecodedType(u16)); try std.testing.expectEqual(u16, EncodedType(u8)); try std.testing.expectEqual(u8, EncodedType(u7)); try std.testing.expectEqual(u32, EncodedType(u28)); try std.testing.expectEqual(u16, EncodedType(u14)); try std.testing.expectEqual(u24, EncodedType(u15)); } test "is synchsafe" { try std.testing.expect(isSliceSynchsafe(&[_]u8{ 0, 0, 0, 127 })); try std.testing.expect(!isSliceSynchsafe(&[_]u8{ 0, 0, 0, 255 })); try std.testing.expect(areIntBytesSynchsafe(u2, 0)); try std.testing.expect(areIntBytesSynchsafe(u8, 127)); try std.testing.expect(!areIntBytesSynchsafe(u8, 128)); try std.testing.expect(!areIntBytesSynchsafe(u8, 255)); try std.testing.expect(areIntBytesSynchsafe(u9, 256)); try std.testing.expect(isBelowSynchsafeThreshold(u2, 0)); try std.testing.expect(isBelowSynchsafeThreshold(u8, 127)); try std.testing.expect(!isBelowSynchsafeThreshold(u8, 128)); }
src/synchsafe.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../inputs/day10.txt"); pub fn main() anyerror!void { var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_impl.deinit(); const gpa = gpa_impl.allocator(); return main_with_allocator(gpa); } pub fn main_with_allocator(allocator: Allocator) anyerror!void { print("Part 1: {d}\n", .{try part1(allocator, data[0..])}); print("Part 2: {d}\n", .{try part2(allocator, data[0..])}); } fn part1(allocator: Allocator, input: []const u8) !usize { var lines = std.mem.tokenize(u8, input, "\n"); var stack = std.ArrayList(u8).init(allocator); defer stack.deinit(); var score: usize = 0; while (lines.next()) |line| { const result = try matching(line, &stack); switch (result) { .corrupted => |c| { switch (c) { ')' => score += 3, ']' => score += 57, '}' => score += 1197, '>' => score += 25137, else => unreachable, } }, else => {}, } } return score; } fn part2(allocator: Allocator, input: []const u8) !usize { var lines = std.mem.tokenize(u8, input, "\n"); var stack = std.ArrayList(u8).init(allocator); defer stack.deinit(); var scores = std.ArrayList(usize).init(allocator); defer scores.deinit(); while (lines.next()) |line| { const result = try matching(line, &stack); switch (result) { .incomplete => { var score: usize = 0; while (stack.popOrNull()) |c| { score *= 5; switch (c) { ')' => score += 1, ']' => score += 2, '}' => score += 3, '>' => score += 4, else => unreachable, } } try scores.append(score); }, else => {}, } } std.sort.sort(usize, scores.items, {}, comptime std.sort.asc(usize)); return scores.items[scores.items.len / 2]; } const Result = union(enum) { corrupted: u8, incomplete, success, }; fn matching(line: []const u8, stack: *std.ArrayList(u8)) !Result { stack.clearRetainingCapacity(); for (line) |c| { switch (c) { '(' => try stack.append(')'), '[' => try stack.append(']'), '{' => try stack.append('}'), '<' => try stack.append('>'), else => { const expected = stack.popOrNull(); if (expected) |e| { if (c != e) { return Result{ .corrupted = c }; } } else { return Result{ .corrupted = c }; } }, } } if (stack.items.len == 0) { return Result.success; } else { return Result.incomplete; } } test "matching" { const input = \\[({(<(())[]>[[{[]{<()<>> \\[(()[<>])]({[<{<<[]>>( \\{([(<{}[<>[]}>{[]{[(<()> \\(((({<>}<{<{<>}{[]{[]{} \\[[<[([]))<([[{}[[()]]] \\[{[{({}]{}}([{[{{{}}([] \\{<[[]]>}<{[{[{[]{()[[[] \\[<(<(<(<{}))><([]([]() \\<{([([[(<>()){}]>(<<{{ \\<{([{{}}[<[[[<>{}]]]>[]] ; const allocator = std.testing.allocator; try std.testing.expectEqual(@as(usize, 26397), try part1(allocator, input[0..])); try std.testing.expectEqual(@as(usize, 288957), try part2(allocator, input[0..])); }
src/day10.zig
const std = @import("std"); const upaya = @import("upaya"); pub const Map = struct { w: usize = 64, h: usize = 64, tile_size: usize = 16, tile_spacing: usize = 0, image: []const u8 = "", data: []u8, ruleset: RuleSet, ruleset_groups: std.AutoHashMap(u8, []const u8), pre_rulesets: std.ArrayList(RuleSet), tags: std.ArrayList(Tag), tile_definitions: TileDefinitions, objects: std.ArrayList(Object), animations: std.ArrayList(Animation), pub fn init(tile_size: usize, tile_spacing: usize) Map { var map = .{ .w = 64, .h = 64, .tile_size = tile_size, .tile_spacing = tile_spacing, .data = upaya.mem.allocator.alloc(u8, 64 * 64) catch unreachable, .ruleset = RuleSet.init(), .ruleset_groups = std.AutoHashMap(u8, []const u8).init(upaya.mem.allocator), .pre_rulesets = std.ArrayList(RuleSet).init(upaya.mem.allocator), .tags = std.ArrayList(Tag).init(upaya.mem.allocator), .tile_definitions = .{}, .objects = std.ArrayList(Object).init(upaya.mem.allocator), .animations = std.ArrayList(Animation).init(upaya.mem.allocator), }; std.mem.set(u8, map.data, 0); return map; } pub fn deinit(self: *Map) void { upaya.mem.allocator.free(self.data); for (self.pre_rulesets.items) |pr| { pr.deinit(); } self.ruleset.deinit(); self.ruleset_groups.deinit(); self.tags.deinit(); self.objects.deinit(); self.animations.deinit(); if (self.image.len > 0) { upaya.mem.allocator.free(self.image); } } pub fn addTag(self: *Map) void { self.tags.append(Tag.init()) catch unreachable; } pub fn addObject(self: *Map) void { var obj = Object.init(self.objects.items.len); _ = std.fmt.bufPrint(&obj.name, "Object ${}", .{self.objects.items.len}) catch unreachable; obj.name[8 + 1 + @divTrunc(self.objects.items.len, 10)] = 0; self.objects.append(obj) catch unreachable; } pub fn getObjectWithId(self: Map, id: usize) Object { for (self.objects.items) |obj| { if (obj.id == id) return obj; } unreachable; } pub fn getGroupName(self: Map, group: u8) []const u8 { return self.ruleset_groups.get(group) orelse "Unnamed Group"; } pub fn renameGroup(self: *Map, group: u8, name: []const u8) void { if (self.ruleset_groups.remove(group)) |entry| { upaya.mem.allocator.free(entry.value); } self.ruleset_groups.put(group, upaya.mem.allocator.dupe(u8, name) catch unreachable) catch unreachable; } pub fn removeGroupIfEmpty(self: *Map, group: u8) void { for (self.ruleset.rules.items) |rule| { if (rule.group == group) return; } if (self.ruleset_groups.remove(group)) |entry| { upaya.mem.allocator.free(entry.value); } } pub fn addAnimation(self: *Map, tile: u8) void { self.animations.append(Animation.init(tile)) catch unreachable; } pub fn tryGetAnimation(self: *Map, tile: u8) ?Animation { for (self.animations.items) |anim| { if (anim.tile == tile) return anim; } return null; } pub fn addPreRuleSet(self: *Map) void { self.pre_rulesets.append(RuleSet.init()) catch unreachable; } pub fn getTile(self: Map, x: usize, y: usize) u8 { if (x > self.w or y > self.h) { return 0; } return self.data[x + y * self.w]; } pub fn setTile(self: Map, x: usize, y: usize, value: u8) void { self.data[x + y * self.w] = value; } }; pub const RuleSet = struct { seed: u64 = 0, repeat: u8 = 20, rules: std.ArrayList(Rule), pub fn init() RuleSet { return .{ .rules = std.ArrayList(Rule).init(upaya.mem.allocator) }; } pub fn deinit(self: RuleSet) void { self.rules.deinit(); } pub fn addRule(self: *RuleSet) void { self.rules.append(Rule.init()) catch unreachable; } pub fn getNextAvailableGroup(self: RuleSet, map: *Map, name: []const u8) u8 { var group: u8 = 0; for (self.rules.items) |rule| { group = std.math.max(group, rule.group); } map.ruleset_groups.put(group + 1, upaya.mem.allocator.dupe(u8, name) catch unreachable) catch unreachable; return group + 1; } /// adds the Rules required for a nine-slice with index being the top-left element of the nine-slice pub fn addNinceSliceRules(self: *RuleSet, map: *Map, tiles_per_row: usize, selected_brush_index: usize, name_prefix: []const u8, index: usize) void { const x = @mod(index, tiles_per_row); const y = @divTrunc(index, tiles_per_row); const group = self.getNextAvailableGroup(map, name_prefix); var rule = Rule.init(); rule.group = group; const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-tl" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(1, 2).negate(selected_brush_index + 1); rule.get(2, 1).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + y * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const tr_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-tr" }) catch unreachable; std.mem.copy(u8, &rule.name, tr_name); rule.get(3, 2).negate(selected_brush_index + 1); rule.get(2, 1).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 2 + y * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const bl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-bl" }) catch unreachable; std.mem.copy(u8, &rule.name, bl_name); rule.get(1, 2).negate(selected_brush_index + 1); rule.get(2, 3).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + (y + 2) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const br_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-br" }) catch unreachable; std.mem.copy(u8, &rule.name, br_name); rule.get(2, 3).negate(selected_brush_index + 1); rule.get(3, 2).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 2 + (y + 2) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const t_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-t" }) catch unreachable; std.mem.copy(u8, &rule.name, t_name); rule.get(2, 1).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 1 + y * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const b_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-b" }) catch unreachable; std.mem.copy(u8, &rule.name, b_name); rule.get(2, 3).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 1 + (y + 2) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const l_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-l" }) catch unreachable; std.mem.copy(u8, &rule.name, l_name); rule.get(1, 2).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + (y + 1) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const r_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-r" }) catch unreachable; std.mem.copy(u8, &rule.name, r_name); rule.get(3, 2).negate(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, (x + 2) + (y + 1) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const c_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-c" }) catch unreachable; std.mem.copy(u8, &rule.name, c_name); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 1 + (y + 1) * tiles_per_row)); self.rules.append(rule) catch unreachable; } pub fn addInnerFourRules(self: *RuleSet, map: *Map, tiles_per_row: usize, selected_brush_index: usize, name_prefix: []const u8, index: usize) void { const x = @mod(index, tiles_per_row); const y = @divTrunc(index, tiles_per_row); const group = self.getNextAvailableGroup(map, name_prefix); var rule = Rule.init(); rule.group = group; const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-tl" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(1, 1).negate(selected_brush_index + 1); rule.get(1, 2).require(selected_brush_index + 1); rule.get(2, 1).require(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + y * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const tr_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-tr" }) catch unreachable; std.mem.copy(u8, &rule.name, tr_name); rule.get(3, 1).negate(selected_brush_index + 1); rule.get(3, 2).require(selected_brush_index + 1); rule.get(2, 1).require(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 1 + y * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const bl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-bl" }) catch unreachable; std.mem.copy(u8, &rule.name, bl_name); rule.get(1, 2).require(selected_brush_index + 1); rule.get(2, 3).require(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.get(1, 3).negate(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + (y + 1) * tiles_per_row)); self.rules.append(rule) catch unreachable; rule = Rule.init(); rule.group = group; const br_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-br" }) catch unreachable; std.mem.copy(u8, &rule.name, br_name); rule.get(2, 3).require(selected_brush_index + 1); rule.get(3, 2).require(selected_brush_index + 1); rule.get(2, 2).require(selected_brush_index + 1); rule.get(3, 3).negate(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, x + 1 + (y + 1) * tiles_per_row)); self.rules.append(rule) catch unreachable; } pub fn addFloodFill(self: *RuleSet, selected_brush_index: usize, name_prefix: []const u8, left: bool, right: bool, up: bool, down: bool) void { if (left) { var rule = Rule.init(); const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-l" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(2, 2).require(0); rule.get(3, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, selected_brush_index)); self.rules.append(rule) catch unreachable; } if (right) { var rule = Rule.init(); const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-r" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(2, 2).require(0); rule.get(1, 2).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, selected_brush_index)); self.rules.append(rule) catch unreachable; } if (up) { var rule = Rule.init(); const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-u" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(2, 2).require(0); rule.get(2, 3).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, selected_brush_index)); self.rules.append(rule) catch unreachable; } if (down) { var rule = Rule.init(); const tl_name = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ name_prefix, "-d" }) catch unreachable; std.mem.copy(u8, &rule.name, tl_name); rule.get(2, 2).require(0); rule.get(2, 1).require(selected_brush_index + 1); rule.toggleSelected(@intCast(u8, selected_brush_index)); self.rules.append(rule) catch unreachable; } } }; pub const Rule = struct { name: [25:0]u8 = [_:0]u8{0} ** 25, rule_tiles: [25]RuleTile = undefined, chance: u8 = 100, result_tiles: upaya.FixedList(u8, 25), // indices into the tileset image group: u8 = 0, // UI-relevant: used to group Rules into a tree leaf node visually pub fn init() Rule { return .{ .rule_tiles = [_]RuleTile{RuleTile{ .tile = 0, .state = .none }} ** 25, .result_tiles = upaya.FixedList(u8, 25).init(), }; } pub fn clone(self: Rule) Rule { var new_rule = Rule.init(); std.mem.copy(u8, &new_rule.name, &self.name); std.mem.copy(RuleTile, &new_rule.rule_tiles, &self.rule_tiles); std.mem.copy(u8, &new_rule.result_tiles.items, &self.result_tiles.items); new_rule.result_tiles.len = self.result_tiles.len; new_rule.chance = self.chance; new_rule.group = self.group; return new_rule; } pub fn clearPatternData(self: *Rule) void { self.rule_tiles = [_]RuleTile{RuleTile{ .tile = 0, .state = .none }} ** 25; } pub fn get(self: *Rule, x: usize, y: usize) *RuleTile { return &self.rule_tiles[x + y * 5]; } pub fn resultTile(self: *Rule, random: usize) usize { const index = std.rand.limitRangeBiased(usize, random, self.result_tiles.len); return self.result_tiles.items[index]; } pub fn toggleSelected(self: *Rule, index: u8) void { if (self.result_tiles.indexOf(index)) |slice_index| { _ = self.result_tiles.swapRemove(slice_index); } else { self.result_tiles.append(index); } } pub fn flip(self: *Rule, dir: enum { horizontal, vertical }) void { if (dir == .vertical) { for ([_]usize{ 0, 1 }) |y| { for ([_]usize{ 0, 1, 2, 3, 4 }) |x| { std.mem.swap(RuleTile, &self.rule_tiles[x + y * 5], &self.rule_tiles[x + (4 - y) * 5]); } } } else { for ([_]usize{ 0, 1 }) |x| { for ([_]usize{ 0, 1, 2, 3, 4 }) |y| { std.mem.swap(RuleTile, &self.rule_tiles[x + y * 5], &self.rule_tiles[(4 - x) + y * 5]); } } } } pub fn shift(self: *Rule, dir: enum { left, right, up, down }) void { var x_incr: i32 = if (dir == .left) -1 else 1; var x_vals = [_]usize{ 0, 1, 2, 3, 4 }; if (dir == .right) std.mem.reverse(usize, &x_vals); var y_incr: i32 = if (dir == .up) -1 else 1; var y_vals = [_]usize{ 0, 1, 2, 3, 4 }; if (dir == .down) std.mem.reverse(usize, &y_vals); if (dir == .left or dir == .right) { for (y_vals) |y| { for (x_vals) |x| { self.swap(x, y, @intCast(i32, x) + x_incr, @intCast(i32, y)); } } } else { for (x_vals) |x| { for (y_vals) |y| { self.swap(x, y, @intCast(i32, x), @intCast(i32, y) + y_incr); } } } } fn swap(self: *Rule, x: usize, y: usize, new_x: i32, new_y: i32) void { // destinations can be invalid and when they are we just reset the source values if (new_x >= 0 and new_x < 5 and new_y >= 0 and new_y < 5) { self.rule_tiles[@intCast(usize, new_x + new_y * 5)] = self.rule_tiles[x + y * 5].clone(); } self.rule_tiles[x + y * 5].reset(); } }; pub const RuleTile = struct { tile: usize = 0, state: RuleState = .none, pub const RuleState = enum(u4) { none, negated, required, }; pub fn clone(self: RuleTile) RuleTile { return .{ .tile = self.tile, .state = self.state }; } pub fn reset(self: *RuleTile) void { self.tile = 0; self.state = .none; } pub fn passes(self: RuleTile, tile: usize) bool { if (self.state == .none) return false; if (tile == self.tile) { return self.state == .required; } return self.state == .negated; } pub fn toggleState(self: *RuleTile, new_state: RuleState) void { if (self.tile == 0) { self.state = new_state; } else { self.tile = 0; self.state = .none; } } pub fn negate(self: *RuleTile, index: usize) void { if (self.tile == 0) { self.tile = index; self.state = .negated; } else { self.tile = 0; self.state = .none; } } pub fn require(self: *RuleTile, index: usize) void { if (self.tile == 0) { self.tile = index; self.state = .required; } else { self.tile = 0; self.state = .none; } } }; pub const Tag = struct { name: [25]u8, tiles: upaya.FixedList(u8, 10), pub fn init() Tag { return .{ .name = [_]u8{0} ** 25, .tiles = upaya.FixedList(u8, 10).init() }; } pub fn toggleSelected(self: *Tag, index: u8) void { if (self.tiles.indexOf(index)) |slice_index| { _ = self.tiles.swapRemove(slice_index); } else { self.tiles.append(index); } } }; pub const TileDefinitions = struct { solid: upaya.FixedList(u8, 50) = upaya.FixedList(u8, 50).init(), slope_down: upaya.FixedList(u8, 10) = upaya.FixedList(u8, 10).init(), slope_down_steep: upaya.FixedList(u8, 10) = upaya.FixedList(u8, 10).init(), slope_up: upaya.FixedList(u8, 10) = upaya.FixedList(u8, 10).init(), slope_up_steep: upaya.FixedList(u8, 10) = upaya.FixedList(u8, 10).init(), pub fn toggleSelected(tiles: anytype, index: u8) void { if (tiles.indexOf(index)) |slice_index| { _ = tiles.swapRemove(slice_index); } else { tiles.append(index); } } }; pub const Object = struct { id: u8 = 0, name: [25]u8 = undefined, x: usize = 0, y: usize = 0, props: std.ArrayList(Prop), pub const Prop = struct { name: [25]u8, value: PropValue, pub fn init() Prop { return .{ .name = [_]u8{0} ** 25, .value = undefined }; } }; pub const PropValue = union(enum) { string: [25]u8, int: i32, float: f32, link: u8, }; pub fn init(id: usize) Object { var obj = Object{ .name = [_]u8{0} ** 25, .id = @intCast(u8, id), .props = std.ArrayList(Prop).init(upaya.mem.allocator) }; _ = std.fmt.bufPrint(&obj.name, "Object ${}", .{id}) catch unreachable; obj.name[8 + 1 + @divTrunc(id, 10)] = 0; return obj; } pub fn deinit(self: Object) void { self.props.deinit(); } pub fn addProp(self: *Object, value: PropValue) void { self.props.append(.{ .name = undefined, .value = value }) catch unreachable; } pub fn removeLinkPropsWithId(self: *Object, id: u8) void { var delete_index: usize = std.math.maxInt(usize); for (self.props.items) |prop, i| { switch (prop.value) { .link => |linked_id| { if (linked_id == id) { delete_index = i; break; } }, else => {}, } } if (delete_index < std.math.maxInt(usize)) { _ = self.props.orderedRemove(delete_index); } } }; pub const Animation = struct { tile: u8, rate: u16 = 500, tiles: upaya.FixedList(u8, 10), pub fn init(tile: u8) Animation { var anim = Animation{ .tile = tile, .tiles = upaya.FixedList(u8, 10).init() }; anim.toggleSelected(tile); return anim; } pub fn toggleSelected(self: *Animation, index: u8) void { if (self.tiles.indexOf(index)) |slice_index| { _ = self.tiles.swapRemove(slice_index); } else { self.tiles.append(index); } } };
tilescript/map.zig
const std = @import("std"); const stdx = @import("stdx"); const build_options = @import("build_options"); const Vec2 = stdx.math.Vec2; const vec2 = Vec2.init; const builtin = @import("builtin"); const IsWasm = builtin.target.isWasm(); const graphics = @import("graphics"); const Graphics = graphics.Graphics; const FontId = graphics.FontId; const Image = graphics.Image; const Color = graphics.Color; const platform = @import("platform"); const log = stdx.log.scoped(.demo); var dispatcher: platform.EventDispatcher = undefined; var win: platform.Window = undefined; var renderer: graphics.Renderer = undefined; var cam: graphics.Camera = undefined; var gctx: *graphics.Graphics = undefined; var quit = false; var zig_logo_svg: []const u8 = undefined; var tiger_head_image: graphics.ImageId = undefined; var game_char_image: Image = undefined; var last_frame_time_ns: u64 = undefined; var font_id: FontId = undefined; pub fn main() !void { const alloc = stdx.heap.getDefaultAllocator(); defer stdx.heap.deinitDefaultAllocator(); dispatcher = platform.EventDispatcher.init(alloc); defer dispatcher.deinit(); win = try platform.Window.init(alloc, .{ .title = "Demo", .width = 1200, .height = 720, .resizable = true, .high_dpi = true, .anti_alias = true, }); defer win.deinit(); win.addDefaultHandlers(&dispatcher); const S = struct { fn onQuit(_: ?*anyopaque) void { quit = true; } }; dispatcher.addOnQuit(null, S.onQuit); renderer.init(alloc, &win); defer renderer.deinit(alloc); gctx = renderer.getGraphics(); cam.init2D(win.getWidth(), win.getHeight()); try initAssets(alloc); defer deinitAssets(alloc); var timer = std.time.Timer.start() catch unreachable; last_frame_time_ns = timer.read(); while (!quit) { const diff_ms = @intToFloat(f32, timer.read() - last_frame_time_ns) / 1e6; last_frame_time_ns = timer.read(); dispatcher.processEvents(); update(diff_ms); std.time.sleep(15); } } // Main loop shared by desktop and web. fn update(delta_ms: f32) void { renderer.beginFrame(cam); const g = gctx; g.setFillColor(Color.Black); g.fillRect(0, 0, @intToFloat(f32, win.getWidth()), @intToFloat(f32, win.getHeight())); // Shapes. g.setFillColor(Color.Red); g.fillRect(60, 100, 300, 200); g.setLineWidth(8); g.setStrokeColor(Color.Red.darker()); g.drawRect(60, 100, 300, 200); g.translate(0, -120); g.rotateDeg(20); g.setFillColor(Color.Blue.withAlpha(150)); g.fillRect(250, 200, 300, 200); g.resetTransform(); // Gradients. g.setFillGradient(400, 500, Color.Red, 700, 700, Color.Blue); g.fillRect(400, 500, 300, 200); // Text. g.setFont(font_id, 26); g.setFillColor(Color.Orange); g.fillText(140, 10, "The quick brown fox 🦊 jumps over the lazy dog. 🐶"); g.rotateDeg(45); g.setFont(font_id, 48); g.setFillColor(Color.SkyBlue); g.fillText(140, 10, "The quick brown fox 🦊 jumps over the lazy dog. 🐶"); g.resetTransform(); // More shapes. g.setFillColor(Color.Green); g.fillCircle(550, 150, 100); g.setFillColor(Color.Green.darker()); g.fillCircleSectorDeg(550, 150, 100, 0, 120); g.setStrokeColor(Color.Yellow); g.drawCircle(700, 200, 70); g.setStrokeColor(Color.Yellow.darker()); g.drawCircleArcDeg(700, 200, 70, 0, 120); g.setFillColor(Color.Purple); g.fillEllipse(850, 70, 80, 40); g.setFillColor(Color.Purple.lighter()); g.fillEllipseSectorDeg(850, 70, 80, 40, 0, 240); g.setStrokeColor(Color.Brown); g.drawEllipse(850, 70, 80, 40); g.setStrokeColor(Color.Brown.lighter()); g.drawEllipseArcDeg(850, 70, 80, 40, 0, 120); g.setFillColor(Color.Red); g.fillTriangle(850, 70, 800, 170, 900, 170); g.setFillColor(Color.Brown); g.fillConvexPolygon(&.{ vec2(1000, 70), vec2(960, 120), vec2(950, 170), vec2(1000, 200), vec2(1050, 170), vec2(1040, 120), }); const polygon = [_]Vec2{ vec2(990, 140), vec2(1040, 65), vec2(1040, 115), vec2(1090, 40), }; g.setFillColor(Color.DarkGray); g.fillPolygon(&polygon); g.setStrokeColor(Color.Yellow); g.setLineWidth(3); g.drawPolygon(&polygon); g.setFillColor(Color.Blue.darker()); g.fillRoundRect(70, 430, 200, 120, 30); g.setLineWidth(7); g.setStrokeColor(Color.Blue); g.drawRoundRect(70, 430, 200, 120, 30); g.setStrokeColor(Color.Orange); g.setLineWidth(3); g.drawPoint(220, 220); g.drawLine(240, 220, 300, 320); // Svg. g.translate(0, 570); g.setFillColor(Color.White); g.fillRect(0, 0, 400, 140); g.drawSvgContent(zig_logo_svg) catch unreachable; g.resetTransform(); // Rasterize big svg. g.drawImage(650, 150, tiger_head_image); // g.drawSvgPathStr(0, 0, // \\M394,106c-10.2,7.3-24,12-37.7,12c-29,0-51.1-20.8-51.1-48.3c0-27.3,22.5-48.1,52-48.1 // \\c14.3,0,29.2,5.5,38.9,14l-13,15c-7.1-6.3-16.8-10-25.9-10c-17,0-30.2,12.9-30.2,29.5c0,16.8,13.3,29.6,30.3,29.6 // \\c5.7,0,12.8-2.3,19-5.5L394,106z // ) catch unreachable; // Curves. g.resetTransform(); g.setLineWidth(3); g.setStrokeColor(Color.Yellow); g.drawQuadraticBezierCurve(0, 0, 200, 0, 200, 200); g.drawCubicBezierCurve(0, 0, 200, 0, 0, 200, 200, 200); // Images. g.drawImageSized(450, 290, @intToFloat(f32, game_char_image.width) / 3, @intToFloat(f32, game_char_image.height) / 3, game_char_image.id); g.setFillColor(Color.Blue.lighter()); const fps = 1000 / delta_ms; g.setFont(font_id, 26); g.fillTextFmt(1100, 10, "fps {d:.1}", .{fps}); renderer.endFrame(); } fn initAssets(alloc: std.mem.Allocator) !void { const MaxFileSize = 20e6; font_id = try gctx.addFontFromPathTTF(srcPath() ++ "/../../examples/assets/NunitoSans-Regular.ttf"); const emoji_font = try gctx.addFontFromPathTTF(srcPath() ++ "/../../examples/assets/NotoColorEmoji.ttf"); gctx.addFallbackFont(emoji_font); const game_char_data = try std.fs.cwd().readFileAlloc(alloc, srcPath() ++ "/../../examples/assets/game-char.png", MaxFileSize); defer alloc.free(game_char_data); game_char_image = try gctx.createImage(game_char_data); zig_logo_svg = try std.fs.cwd().readFileAlloc(alloc, srcPath() ++ "/../../examples/assets/zig-logo-dark.svg", MaxFileSize); const tiger_head_svg = try std.fs.cwd().readFileAlloc(alloc, srcPath() ++ "/../../examples/assets/tiger-head.svg", MaxFileSize); defer alloc.free(tiger_head_svg); var parser = graphics.svg.SvgParser.init(alloc); defer parser.deinit(); // TODO: Make this work for vulkan. if (build_options.GraphicsBackend != .Vulkan) { rasterizeTigerHead(tiger_head_svg); } } fn deinitAssets(alloc: std.mem.Allocator) void { alloc.free(zig_logo_svg); } fn rasterizeTigerHead(tiger_head_svg: []const u8) void { // Renders the svg to an image and then the image is drawn. // The graphics context also supports drawing the svg directly to the main frame buffer, although it isn't recommended for large svgs like the tiger head. tiger_head_image = gctx.createImageFromBitmap(600, 600, null, true); gctx.bindImageBuffer(tiger_head_image); gctx.setFillColor(Color.Transparent); gctx.fillRect(0, 0, 600, 600); gctx.translate(200, 200); gctx.drawSvgContent(tiger_head_svg) catch unreachable; gctx.endCmd(); } // Below is the bootstrap code for wasm. var galloc: std.mem.Allocator = undefined; var zig_logo_id: u32 = undefined; var game_char_id: u32 = undefined; var nunito_font_id: u32 = undefined; var noto_emoji_id: u32 = undefined; var tiger_head_id: u32 = undefined; var loaded_assets: u32 = 0; pub usingnamespace if (IsWasm) struct { export fn wasmInit() *const u8 { const alloc = stdx.heap.getDefaultAllocator(); galloc = alloc; stdx.wasm.init(alloc); dispatcher = platform.EventDispatcher.init(alloc); win = platform.Window.init(alloc, .{ .title = "Demo", .width = 1200, .height = 720, .anti_alias = true, }) catch unreachable; win.addDefaultHandlers(&dispatcher); renderer.init(alloc, &win); gctx = renderer.getGraphics(); const S = struct { fn onFetchResult(_: ?*anyopaque, e: platform.FetchResultEvent) void { if (e.fetch_id == zig_logo_id) { zig_logo_svg = galloc.dupe(u8, e.buf) catch unreachable; loaded_assets += 1; } else if (e.fetch_id == game_char_id) { game_char_image = gctx.createImage(e.buf) catch unreachable; loaded_assets += 1; } else if (e.fetch_id == nunito_font_id) { font_id = gctx.addFontTTF(e.buf); loaded_assets += 1; } else if (e.fetch_id == tiger_head_id) { rasterizeTigerHead(e.buf); loaded_assets += 1; } else if (e.fetch_id == noto_emoji_id) { const emoji_font = gctx.addFontTTF(e.buf); gctx.addFallbackFont(emoji_font); loaded_assets += 1; } } }; dispatcher.addOnFetchResult(null, S.onFetchResult); // TODO: Should be able to create async resources. In the case of fonts, it would use the default font. In the case of images it would be blank. zig_logo_id = stdx.fs.readFileWasm("./zig-logo-dark.svg"); game_char_id = stdx.fs.readFileWasm("./game-char.png"); nunito_font_id = stdx.fs.readFileWasm("./NunitoSans-Regular.ttf"); noto_emoji_id = stdx.fs.readFileWasm("./NotoColorEmoji.ttf"); tiger_head_id = stdx.fs.readFileWasm("./tiger-head.svg"); return stdx.wasm.js_buffer.writeResult(); } export fn wasmUpdate(cur_time_ms: f32, input_len: u32) *const u8 { stdx.wasm.js_buffer.input_buf.items.len = input_len; dispatcher.processEvents(); // Wait for assets to load in the browser before getting to main loop. if (loaded_assets < 5) { return stdx.wasm.js_buffer.writeResult(); } const now_ns = @floatToInt(u64, cur_time_ms * 1e6); const diff_ms = @intToFloat(f32, now_ns - last_frame_time_ns) / 1e6; last_frame_time_ns = now_ns; update(diff_ms); return stdx.wasm.js_buffer.writeResult(); } } else struct {}; fn srcPath() []const u8 { return (std.fs.path.dirname(@src().file) orelse unreachable); }
graphics/examples/demo.zig
const std = @import("std"); const expect = std.testing.expect; const math = std.math; const pi = std.math.pi; const e = std.math.e; const epsilon = 0.000001; test "@sqrt" { comptime testSqrt(); testSqrt(); } fn testSqrt() void { { var a: f16 = 4; expect(@sqrt(a) == 2); } { var a: f32 = 9; expect(@sqrt(a) == 3); var b: f32 = 1.1; expect(math.approxEq(f32, @sqrt(b), 1.0488088481701516, epsilon)); } { var a: f64 = 25; expect(@sqrt(a) == 5); } { const a: comptime_float = 25.0; expect(@sqrt(a) == 5.0); } // TODO https://github.com/ziglang/zig/issues/4026 //{ // var a: f128 = 49; // expect(@sqrt(a) == 7); //} { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 3.3, 4.4}; var result = @sqrt(v); expect(math.approxEq(f32, @sqrt(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @sqrt(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @sqrt(@as(f32, 3.3)), result[2], epsilon)); expect(math.approxEq(f32, @sqrt(@as(f32, 4.4)), result[3], epsilon)); } } test "more @sqrt f16 tests" { // TODO these are not all passing at comptime expect(@sqrt(@as(f16, 0.0)) == 0.0); expect(math.approxEq(f16, @sqrt(@as(f16, 2.0)), 1.414214, epsilon)); expect(math.approxEq(f16, @sqrt(@as(f16, 3.6)), 1.897367, epsilon)); expect(@sqrt(@as(f16, 4.0)) == 2.0); expect(math.approxEq(f16, @sqrt(@as(f16, 7.539840)), 2.745877, epsilon)); expect(math.approxEq(f16, @sqrt(@as(f16, 19.230934)), 4.385309, epsilon)); expect(@sqrt(@as(f16, 64.0)) == 8.0); expect(math.approxEq(f16, @sqrt(@as(f16, 64.1)), 8.006248, epsilon)); expect(math.approxEq(f16, @sqrt(@as(f16, 8942.230469)), 94.563370, epsilon)); // special cases expect(math.isPositiveInf(@sqrt(@as(f16, math.inf(f16))))); expect(@sqrt(@as(f16, 0.0)) == 0.0); expect(@sqrt(@as(f16, -0.0)) == -0.0); expect(math.isNan(@sqrt(@as(f16, -1.0)))); expect(math.isNan(@sqrt(@as(f16, math.nan(f16))))); } test "@sin" { comptime testSin(); testSin(); } fn testSin() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 0; expect(@sin(a) == 0); } { var a: f32 = 0; expect(@sin(a) == 0); } { var a: f64 = 0; expect(@sin(a) == 0); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 3.3, 4.4}; var result = @sin(v); expect(math.approxEq(f32, @sin(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @sin(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @sin(@as(f32, 3.3)), result[2], epsilon)); expect(math.approxEq(f32, @sin(@as(f32, 4.4)), result[3], epsilon)); } } test "@cos" { comptime testCos(); testCos(); } fn testCos() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 0; expect(@cos(a) == 1); } { var a: f32 = 0; expect(@cos(a) == 1); } { var a: f64 = 0; expect(@cos(a) == 1); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 3.3, 4.4}; var result = @cos(v); expect(math.approxEq(f32, @cos(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @cos(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @cos(@as(f32, 3.3)), result[2], epsilon)); expect(math.approxEq(f32, @cos(@as(f32, 4.4)), result[3], epsilon)); } } test "@exp" { comptime testExp(); testExp(); } fn testExp() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 0; expect(@exp(a) == 1); } { var a: f32 = 0; expect(@exp(a) == 1); } { var a: f64 = 0; expect(@exp(a) == 1); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 0.3, 0.4}; var result = @exp(v); expect(math.approxEq(f32, @exp(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @exp(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @exp(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @exp(@as(f32, 0.4)), result[3], epsilon)); } } test "@exp2" { comptime testExp2(); testExp2(); } fn testExp2() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 2; expect(@exp2(a) == 4); } { var a: f32 = 2; expect(@exp2(a) == 4); } { var a: f64 = 2; expect(@exp2(a) == 4); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 0.3, 0.4}; var result = @exp2(v); expect(math.approxEq(f32, @exp2(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @exp2(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @exp2(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @exp2(@as(f32, 0.4)), result[3], epsilon)); } } test "@log" { // Old musl (and glibc?), and our current math.ln implementation do not return 1 // so also accept those values. comptime testLog(); testLog(); } fn testLog() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = e; expect(math.approxEq(f16, @log(a), 1, epsilon)); } { var a: f32 = e; expect(@log(a) == 1 or @log(a) == @bitCast(f32, @as(u32, 0x3f7fffff))); } { var a: f64 = e; expect(@log(a) == 1 or @log(a) == @bitCast(f64, @as(u64, 0x3ff0000000000000))); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 0.3, 0.4}; var result = @log(v); expect(math.approxEq(f32, @log(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @log(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @log(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @log(@as(f32, 0.4)), result[3], epsilon)); } } test "@log2" { comptime testLog2(); testLog2(); } fn testLog2() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 4; expect(@log2(a) == 2); } { var a: f32 = 4; expect(@log2(a) == 2); } { var a: f64 = 4; expect(@log2(a) == 2); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 0.3, 0.4}; var result = @log2(v); expect(math.approxEq(f32, @log2(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @log2(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @log2(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @log2(@as(f32, 0.4)), result[3], epsilon)); } } test "@log10" { comptime testLog10(); testLog10(); } fn testLog10() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 100; expect(@log10(a) == 2); } { var a: f32 = 100; expect(@log10(a) == 2); } { var a: f64 = 1000; expect(@log10(a) == 3); } { var v: @Vector(4, f32) = [_]f32{1.1, 2.2, 0.3, 0.4}; var result = @log10(v); expect(math.approxEq(f32, @log10(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @log10(@as(f32, 2.2)), result[1], epsilon)); expect(math.approxEq(f32, @log10(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @log10(@as(f32, 0.4)), result[3], epsilon)); } } test "@fabs" { comptime testFabs(); testFabs(); } fn testFabs() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = -2.5; var b: f16 = 2.5; expect(@fabs(a) == 2.5); expect(@fabs(b) == 2.5); } { var a: f32 = -2.5; var b: f32 = 2.5; expect(@fabs(a) == 2.5); expect(@fabs(b) == 2.5); } { var a: f64 = -2.5; var b: f64 = 2.5; expect(@fabs(a) == 2.5); expect(@fabs(b) == 2.5); } { var v: @Vector(4, f32) = [_]f32{1.1, -2.2, 0.3, -0.4}; var result = @fabs(v); expect(math.approxEq(f32, @fabs(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @fabs(@as(f32, -2.2)), result[1], epsilon)); expect(math.approxEq(f32, @fabs(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @fabs(@as(f32, -0.4)), result[3], epsilon)); } } test "@floor" { comptime testFloor(); testFloor(); } fn testFloor() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 2.1; expect(@floor(a) == 2); } { var a: f32 = 2.1; expect(@floor(a) == 2); } { var a: f64 = 3.5; expect(@floor(a) == 3); } { var v: @Vector(4, f32) = [_]f32{1.1, -2.2, 0.3, -0.4}; var result = @floor(v); expect(math.approxEq(f32, @floor(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @floor(@as(f32, -2.2)), result[1], epsilon)); expect(math.approxEq(f32, @floor(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @floor(@as(f32, -0.4)), result[3], epsilon)); } } test "@ceil" { comptime testCeil(); testCeil(); } fn testCeil() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 2.1; expect(@ceil(a) == 3); } { var a: f32 = 2.1; expect(@ceil(a) == 3); } { var a: f64 = 3.5; expect(@ceil(a) == 4); } { var v: @Vector(4, f32) = [_]f32{1.1, -2.2, 0.3, -0.4}; var result = @ceil(v); expect(math.approxEq(f32, @ceil(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @ceil(@as(f32, -2.2)), result[1], epsilon)); expect(math.approxEq(f32, @ceil(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @ceil(@as(f32, -0.4)), result[3], epsilon)); } } test "@trunc" { comptime testTrunc(); testTrunc(); } fn testTrunc() void { // TODO test f128, and c_longdouble // https://github.com/ziglang/zig/issues/4026 { var a: f16 = 2.1; expect(@trunc(a) == 2); } { var a: f32 = 2.1; expect(@trunc(a) == 2); } { var a: f64 = -3.5; expect(@trunc(a) == -3); } { var v: @Vector(4, f32) = [_]f32{1.1, -2.2, 0.3, -0.4}; var result = @trunc(v); expect(math.approxEq(f32, @trunc(@as(f32, 1.1)), result[0], epsilon)); expect(math.approxEq(f32, @trunc(@as(f32, -2.2)), result[1], epsilon)); expect(math.approxEq(f32, @trunc(@as(f32, 0.3)), result[2], epsilon)); expect(math.approxEq(f32, @trunc(@as(f32, -0.4)), result[3], epsilon)); } } // TODO This is waiting on library support for the Windows build (not sure why the other's don't need it) //test "@nearbyint" { // comptime testNearbyInt(); // testNearbyInt(); //} //fn testNearbyInt() void { // // TODO test f16, f128, and c_longdouble // // https://github.com/ziglang/zig/issues/4026 // { // var a: f32 = 2.1; // expect(@nearbyint(a) == 2); // } // { // var a: f64 = -3.75; // expect(@nearbyint(a) == -4); // } //}
test/stage1/behavior/floatop.zig
const std = @import("../std.zig"); const testing = std.testing; const valgrind = std.valgrind; pub const MemCheckClientRequest = extern enum { MakeMemNoAccess = valgrind.ToolBase("MC"), MakeMemUndefined, MakeMemDefined, Discard, CheckMemIsAddressable, CheckMemIsDefined, DoLeakCheck, CountLeaks, GetVbits, SetVbits, CreateBlock, MakeMemDefinedIfAddressable, CountLeakBlocks, EnableAddrErrorReportingInRange, DisableAddrErrorReportingInRange, }; fn doMemCheckClientRequestExpr(default: usize, request: MemCheckClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize { return valgrind.doClientRequest(default, @intCast(usize, @enumToInt(request)), a1, a2, a3, a4, a5); } fn doMemCheckClientRequestStmt(request: MemCheckClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) void { _ = doMemCheckClientRequestExpr(0, request, a1, a2, a3, a4, a5); } /// Mark memory at qzz.ptr as unaddressable for qzz.len bytes. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemNoAccess(qzz: []u8) i1 { return @intCast(i1, doMemCheckClientRequestExpr(0, // default return .MakeMemNoAccess, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0)); } /// Similarly, mark memory at qzz.ptr as addressable but undefined /// for qzz.len bytes. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemUndefined(qzz: []u8) i1 { return @intCast(i1, doMemCheckClientRequestExpr(0, // default return .MakeMemUndefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0)); } /// Similarly, mark memory at qzz.ptr as addressable and defined /// for qzz.len bytes. pub fn makeMemDefined(qzz: []u8) i1 { // This returns -1 when run on Valgrind and 0 otherwise. return @intCast(i1, doMemCheckClientRequestExpr(0, // default return .MakeMemDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0)); } /// Similar to makeMemDefined except that addressability is /// not altered: bytes which are addressable are marked as defined, /// but those which are not addressable are left unchanged. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemDefinedIfAddressable(qzz: []u8) i1 { return @intCast(i1, doMemCheckClientRequestExpr(0, // default return .MakeMemDefinedIfAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0)); } /// Create a block-description handle. The description is an ascii /// string which is included in any messages pertaining to addresses /// within the specified memory range. Has no other effect on the /// properties of the memory range. pub fn createBlock(qzz: []u8, desc: [*]u8) usize { return doMemCheckClientRequestExpr(0, // default return .CreateBlock, @ptrToInt(qzz.ptr), qzz.len, @ptrToInt(desc), 0, 0); } /// Discard a block-description-handle. Returns 1 for an /// invalid handle, 0 for a valid handle. pub fn discard(blkindex) bool { return doMemCheckClientRequestExpr(0, // default return .Discard, 0, blkindex, 0, 0, 0) != 0; } /// Check that memory at qzz.ptr is addressable for qzz.len bytes. /// If suitable addressibility is not established, Valgrind prints an /// error message and returns the address of the first offending byte. /// Otherwise it returns zero. pub fn checkMemIsAddressable(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, .CheckMemIsAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0); } /// Check that memory at qzz.ptr is addressable and defined for /// qzz.len bytes. If suitable addressibility and definedness are not /// established, Valgrind prints an error message and returns the /// address of the first offending byte. Otherwise it returns zero. pub fn checkMemIsDefined(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, .CheckMemIsDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0); } /// Do a full memory leak check (like --leak-check=full) mid-execution. pub fn doLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 0, 0, 0, 0); } /// Same as doLeakCheck() but only showing the entries for /// which there was an increase in leaked bytes or leaked nr of blocks /// since the previous leak search. pub fn doAddedLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 1, 0, 0, 0); } /// Same as doAddedLeakCheck() but showing entries with /// increased or decreased leaked bytes/blocks since previous leak /// search. pub fn doChangedLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 2, 0, 0, 0); } /// Do a summary memory leak check (like --leak-check=summary) mid-execution. pub fn doQuickLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 1, 0, 0, 0, 0); } /// Return number of leaked, dubious, reachable and suppressed bytes found by /// all previous leak checks. const CountResult = struct { leaked: usize, dubious: usize, reachable: usize, suppressed: usize, }; pub fn countLeaks() CountResult { var res: CountResult = .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }; doMemCheckClientRequestStmt( .CountLeaks, @ptrToInt(&res.leaked), @ptrToInt(&res.dubious), @ptrToInt(&res.reachable), @ptrToInt(&res.suppressed), 0, ); return res; } test "countLeaks" { testing.expectEqual( @as(CountResult, .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }), countLeaks(), ); } pub fn countLeakBlocks() CountResult { var res: CountResult = .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }; doMemCheckClientRequestStmt( .CountLeakBlocks, @ptrToInt(&res.leaked), @ptrToInt(&res.dubious), @ptrToInt(&res.reachable), @ptrToInt(&res.suppressed), 0, ); return res; } test "countLeakBlocks" { testing.expectEqual( @as(CountResult, .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }), countLeakBlocks(), ); } /// Get the validity data for addresses zza and copy it /// into the provided zzvbits array. Return values: /// 0 if not running on valgrind /// 1 success /// 2 [previously indicated unaligned arrays; these are now allowed] /// 3 if any parts of zzsrc/zzvbits are not addressable. /// The metadata is not copied in cases 0, 2 or 3 so it should be /// impossible to segfault your system by using this call. pub fn getVbits(zza: []u8, zzvbits: []u8) u2 { std.debug.assert(zzvbits.len >= zza.len / 8); return @intCast(u2, doMemCheckClientRequestExpr(0, .GetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0)); } /// Set the validity data for addresses zza, copying it /// from the provided zzvbits array. Return values: /// 0 if not running on valgrind /// 1 success /// 2 [previously indicated unaligned arrays; these are now allowed] /// 3 if any parts of zza/zzvbits are not addressable. /// The metadata is not copied in cases 0, 2 or 3 so it should be /// impossible to segfault your system by using this call. pub fn setVbits(zzvbits: []u8, zza: []u8) u2 { std.debug.assert(zzvbits.len >= zza.len / 8); return @intCast(u2, doMemCheckClientRequestExpr(0, .SetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0)); } /// Disable and re-enable reporting of addressing errors in the /// specified address range. pub fn disableAddrErrorReportingInRange(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, // default return .DisableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0); } pub fn enableAddrErrorReportingInRange(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, // default return .EnableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0); }
lib/std/valgrind/memcheck.zig
const posix = @import("posix.zig"); pub const iovec = posix.iovec; pub const iovec_const = posix.iovec_const; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const mode_t = u0; pub const time_t = i64; // match https://github.com/CraneStation/wasi-libc pub const timespec = struct { tv_sec: time_t, tv_nsec: isize, pub fn fromTimestamp(tm: timestamp_t) timespec { const tv_sec: timestamp_t = tm / 1_000_000_000; const tv_nsec = tm - tv_sec * 1_000_000_000; return timespec{ .tv_sec = @intCast(time_t, tv_sec), .tv_nsec = @intCast(isize, tv_nsec), }; } pub fn toTimestamp(ts: timespec) timestamp_t { const tm = @intCast(timestamp_t, ts.tv_sec * 1_000_000_000) + @intCast(timestamp_t, ts.tv_nsec); return tm; } }; pub const kernel_stat = struct { dev: device_t, ino: inode_t, mode: mode_t, filetype: filetype_t, nlink: linkcount_t, size: filesize_t, atim: timespec, mtim: timespec, ctim: timespec, const Self = @This(); pub fn fromFilestat(stat: filestat_t) Self { return Self{ .dev = stat.dev, .ino = stat.ino, .mode = 0, .filetype = stat.filetype, .nlink = stat.nlink, .size = stat.size, .atim = stat.atime(), .mtim = stat.mtime(), .ctim = stat.ctime(), }; } pub fn atime(self: Self) timespec { return self.atim; } pub fn mtime(self: Self) timespec { return self.mtim; } pub fn ctime(self: Self) timespec { return self.ctim; } }; pub const AT_REMOVEDIR: u32 = 1; // there's no AT_REMOVEDIR in WASI, but we simulate here to match other OSes // As defined in the wasi_snapshot_preview1 spec file: // https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/typenames.witx pub const advice_t = u8; pub const ADVICE_NORMAL: advice_t = 0; pub const ADVICE_SEQUENTIAL: advice_t = 1; pub const ADVICE_RANDOM: advice_t = 2; pub const ADVICE_WILLNEED: advice_t = 3; pub const ADVICE_DONTNEED: advice_t = 4; pub const ADVICE_NOREUSE: advice_t = 5; pub const clockid_t = u32; pub const CLOCK_REALTIME: clockid_t = 0; pub const CLOCK_MONOTONIC: clockid_t = 1; pub const CLOCK_PROCESS_CPUTIME_ID: clockid_t = 2; pub const CLOCK_THREAD_CPUTIME_ID: clockid_t = 3; pub const device_t = u64; pub const dircookie_t = u64; pub const DIRCOOKIE_START: dircookie_t = 0; pub const dirnamlen_t = u32; pub const dirent_t = extern struct { d_next: dircookie_t, d_ino: inode_t, d_namlen: dirnamlen_t, d_type: filetype_t, }; pub const errno_t = u16; pub const ESUCCESS: errno_t = 0; pub const E2BIG: errno_t = 1; pub const EACCES: errno_t = 2; pub const EADDRINUSE: errno_t = 3; pub const EADDRNOTAVAIL: errno_t = 4; pub const EAFNOSUPPORT: errno_t = 5; pub const EAGAIN: errno_t = 6; pub const EALREADY: errno_t = 7; pub const EBADF: errno_t = 8; pub const EBADMSG: errno_t = 9; pub const EBUSY: errno_t = 10; pub const ECANCELED: errno_t = 11; pub const ECHILD: errno_t = 12; pub const ECONNABORTED: errno_t = 13; pub const ECONNREFUSED: errno_t = 14; pub const ECONNRESET: errno_t = 15; pub const EDEADLK: errno_t = 16; pub const EDESTADDRREQ: errno_t = 17; pub const EDOM: errno_t = 18; pub const EDQUOT: errno_t = 19; pub const EEXIST: errno_t = 20; pub const EFAULT: errno_t = 21; pub const EFBIG: errno_t = 22; pub const EHOSTUNREACH: errno_t = 23; pub const EIDRM: errno_t = 24; pub const EILSEQ: errno_t = 25; pub const EINPROGRESS: errno_t = 26; pub const EINTR: errno_t = 27; pub const EINVAL: errno_t = 28; pub const EIO: errno_t = 29; pub const EISCONN: errno_t = 30; pub const EISDIR: errno_t = 31; pub const ELOOP: errno_t = 32; pub const EMFILE: errno_t = 33; pub const EMLINK: errno_t = 34; pub const EMSGSIZE: errno_t = 35; pub const EMULTIHOP: errno_t = 36; pub const ENAMETOOLONG: errno_t = 37; pub const ENETDOWN: errno_t = 38; pub const ENETRESET: errno_t = 39; pub const ENETUNREACH: errno_t = 40; pub const ENFILE: errno_t = 41; pub const ENOBUFS: errno_t = 42; pub const ENODEV: errno_t = 43; pub const ENOENT: errno_t = 44; pub const ENOEXEC: errno_t = 45; pub const ENOLCK: errno_t = 46; pub const ENOLINK: errno_t = 47; pub const ENOMEM: errno_t = 48; pub const ENOMSG: errno_t = 49; pub const ENOPROTOOPT: errno_t = 50; pub const ENOSPC: errno_t = 51; pub const ENOSYS: errno_t = 52; pub const ENOTCONN: errno_t = 53; pub const ENOTDIR: errno_t = 54; pub const ENOTEMPTY: errno_t = 55; pub const ENOTRECOVERABLE: errno_t = 56; pub const ENOTSOCK: errno_t = 57; pub const ENOTSUP: errno_t = 58; pub const ENOTTY: errno_t = 59; pub const ENXIO: errno_t = 60; pub const EOVERFLOW: errno_t = 61; pub const EOWNERDEAD: errno_t = 62; pub const EPERM: errno_t = 63; pub const EPIPE: errno_t = 64; pub const EPROTO: errno_t = 65; pub const EPROTONOSUPPORT: errno_t = 66; pub const EPROTOTYPE: errno_t = 67; pub const ERANGE: errno_t = 68; pub const EROFS: errno_t = 69; pub const ESPIPE: errno_t = 70; pub const ESRCH: errno_t = 71; pub const ESTALE: errno_t = 72; pub const ETIMEDOUT: errno_t = 73; pub const ETXTBSY: errno_t = 74; pub const EXDEV: errno_t = 75; pub const ENOTCAPABLE: errno_t = 76; pub const event_t = extern struct { userdata: userdata_t, @"error": errno_t, @"type": eventtype_t, fd_readwrite: eventfdreadwrite_t, }; pub const eventfdreadwrite_t = extern struct { nbytes: filesize_t, flags: eventrwflags_t, }; pub const eventrwflags_t = u16; pub const EVENT_FD_READWRITE_HANGUP: eventrwflags_t = 0x0001; pub const eventtype_t = u8; pub const EVENTTYPE_CLOCK: eventtype_t = 0; pub const EVENTTYPE_FD_READ: eventtype_t = 1; pub const EVENTTYPE_FD_WRITE: eventtype_t = 2; pub const exitcode_t = u32; pub const fd_t = u32; pub const fdflags_t = u16; pub const FDFLAG_APPEND: fdflags_t = 0x0001; pub const FDFLAG_DSYNC: fdflags_t = 0x0002; pub const FDFLAG_NONBLOCK: fdflags_t = 0x0004; pub const FDFLAG_RSYNC: fdflags_t = 0x0008; pub const FDFLAG_SYNC: fdflags_t = 0x0010; pub const fdstat_t = extern struct { fs_filetype: filetype_t, fs_flags: fdflags_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t, }; pub const filedelta_t = i64; pub const filesize_t = u64; pub const filestat_t = extern struct { dev: device_t, ino: inode_t, filetype: filetype_t, nlink: linkcount_t, size: filesize_t, atim: timestamp_t, mtim: timestamp_t, ctim: timestamp_t, pub fn atime(self: filestat_t) timespec { return timespec.fromTimestamp(self.atim); } pub fn mtime(self: filestat_t) timespec { return timespec.fromTimestamp(self.mtim); } pub fn ctime(self: filestat_t) timespec { return timespec.fromTimestamp(self.ctim); } }; pub const filetype_t = u8; pub const FILETYPE_UNKNOWN: filetype_t = 0; pub const FILETYPE_BLOCK_DEVICE: filetype_t = 1; pub const FILETYPE_CHARACTER_DEVICE: filetype_t = 2; pub const FILETYPE_DIRECTORY: filetype_t = 3; pub const FILETYPE_REGULAR_FILE: filetype_t = 4; pub const FILETYPE_SOCKET_DGRAM: filetype_t = 5; pub const FILETYPE_SOCKET_STREAM: filetype_t = 6; pub const FILETYPE_SYMBOLIC_LINK: filetype_t = 7; pub const fstflags_t = u16; pub const FILESTAT_SET_ATIM: fstflags_t = 0x0001; pub const FILESTAT_SET_ATIM_NOW: fstflags_t = 0x0002; pub const FILESTAT_SET_MTIM: fstflags_t = 0x0004; pub const FILESTAT_SET_MTIM_NOW: fstflags_t = 0x0008; pub const inode_t = u64; pub const ino_t = inode_t; pub const linkcount_t = u64; pub const lookupflags_t = u32; pub const LOOKUP_SYMLINK_FOLLOW: lookupflags_t = 0x00000001; pub const oflags_t = u16; pub const O_CREAT: oflags_t = 0x0001; pub const O_DIRECTORY: oflags_t = 0x0002; pub const O_EXCL: oflags_t = 0x0004; pub const O_TRUNC: oflags_t = 0x0008; pub const preopentype_t = u8; pub const PREOPENTYPE_DIR: preopentype_t = 0; pub const prestat_t = extern struct { pr_type: preopentype_t, u: prestat_u_t, }; pub const prestat_dir_t = extern struct { pr_name_len: usize, }; pub const prestat_u_t = extern union { dir: prestat_dir_t, }; pub const riflags_t = u16; pub const SOCK_RECV_PEEK: riflags_t = 0x0001; pub const SOCK_RECV_WAITALL: riflags_t = 0x0002; pub const rights_t = u64; pub const RIGHT_FD_DATASYNC: rights_t = 0x0000000000000001; pub const RIGHT_FD_READ: rights_t = 0x0000000000000002; pub const RIGHT_FD_SEEK: rights_t = 0x0000000000000004; pub const RIGHT_FD_FDSTAT_SET_FLAGS: rights_t = 0x0000000000000008; pub const RIGHT_FD_SYNC: rights_t = 0x0000000000000010; pub const RIGHT_FD_TELL: rights_t = 0x0000000000000020; pub const RIGHT_FD_WRITE: rights_t = 0x0000000000000040; pub const RIGHT_FD_ADVISE: rights_t = 0x0000000000000080; pub const RIGHT_FD_ALLOCATE: rights_t = 0x0000000000000100; pub const RIGHT_PATH_CREATE_DIRECTORY: rights_t = 0x0000000000000200; pub const RIGHT_PATH_CREATE_FILE: rights_t = 0x0000000000000400; pub const RIGHT_PATH_LINK_SOURCE: rights_t = 0x0000000000000800; pub const RIGHT_PATH_LINK_TARGET: rights_t = 0x0000000000001000; pub const RIGHT_PATH_OPEN: rights_t = 0x0000000000002000; pub const RIGHT_FD_READDIR: rights_t = 0x0000000000004000; pub const RIGHT_PATH_READLINK: rights_t = 0x0000000000008000; pub const RIGHT_PATH_RENAME_SOURCE: rights_t = 0x0000000000010000; pub const RIGHT_PATH_RENAME_TARGET: rights_t = 0x0000000000020000; pub const RIGHT_PATH_FILESTAT_GET: rights_t = 0x0000000000040000; pub const RIGHT_PATH_FILESTAT_SET_SIZE: rights_t = 0x0000000000080000; pub const RIGHT_PATH_FILESTAT_SET_TIMES: rights_t = 0x0000000000100000; pub const RIGHT_FD_FILESTAT_GET: rights_t = 0x0000000000200000; pub const RIGHT_FD_FILESTAT_SET_SIZE: rights_t = 0x0000000000400000; pub const RIGHT_FD_FILESTAT_SET_TIMES: rights_t = 0x0000000000800000; pub const RIGHT_PATH_SYMLINK: rights_t = 0x0000000001000000; pub const RIGHT_PATH_REMOVE_DIRECTORY: rights_t = 0x0000000002000000; pub const RIGHT_PATH_UNLINK_FILE: rights_t = 0x0000000004000000; pub const RIGHT_POLL_FD_READWRITE: rights_t = 0x0000000008000000; pub const RIGHT_SOCK_SHUTDOWN: rights_t = 0x0000000010000000; pub const RIGHT_ALL: rights_t = RIGHT_FD_DATASYNC | RIGHT_FD_READ | RIGHT_FD_SEEK | RIGHT_FD_FDSTAT_SET_FLAGS | RIGHT_FD_SYNC | RIGHT_FD_TELL | RIGHT_FD_WRITE | RIGHT_FD_ADVISE | RIGHT_FD_ALLOCATE | RIGHT_PATH_CREATE_DIRECTORY | RIGHT_PATH_CREATE_FILE | RIGHT_PATH_LINK_SOURCE | RIGHT_PATH_LINK_TARGET | RIGHT_PATH_OPEN | RIGHT_FD_READDIR | RIGHT_PATH_READLINK | RIGHT_PATH_RENAME_SOURCE | RIGHT_PATH_RENAME_TARGET | RIGHT_PATH_FILESTAT_GET | RIGHT_PATH_FILESTAT_SET_SIZE | RIGHT_PATH_FILESTAT_SET_TIMES | RIGHT_FD_FILESTAT_GET | RIGHT_FD_FILESTAT_SET_SIZE | RIGHT_FD_FILESTAT_SET_TIMES | RIGHT_PATH_SYMLINK | RIGHT_PATH_REMOVE_DIRECTORY | RIGHT_PATH_UNLINK_FILE | RIGHT_POLL_FD_READWRITE | RIGHT_SOCK_SHUTDOWN; pub const roflags_t = u16; pub const SOCK_RECV_DATA_TRUNCATED: roflags_t = 0x0001; pub const sdflags_t = u8; pub const SHUT_RD: sdflags_t = 0x01; pub const SHUT_WR: sdflags_t = 0x02; pub const siflags_t = u16; pub const signal_t = u8; pub const SIGNONE: signal_t = 0; pub const SIGHUP: signal_t = 1; pub const SIGINT: signal_t = 2; pub const SIGQUIT: signal_t = 3; pub const SIGILL: signal_t = 4; pub const SIGTRAP: signal_t = 5; pub const SIGABRT: signal_t = 6; pub const SIGBUS: signal_t = 7; pub const SIGFPE: signal_t = 8; pub const SIGKILL: signal_t = 9; pub const SIGUSR1: signal_t = 10; pub const SIGSEGV: signal_t = 11; pub const SIGUSR2: signal_t = 12; pub const SIGPIPE: signal_t = 13; pub const SIGALRM: signal_t = 14; pub const SIGTERM: signal_t = 15; pub const SIGCHLD: signal_t = 16; pub const SIGCONT: signal_t = 17; pub const SIGSTOP: signal_t = 18; pub const SIGTSTP: signal_t = 19; pub const SIGTTIN: signal_t = 20; pub const SIGTTOU: signal_t = 21; pub const SIGURG: signal_t = 22; pub const SIGXCPU: signal_t = 23; pub const SIGXFSZ: signal_t = 24; pub const SIGVTALRM: signal_t = 25; pub const SIGPROF: signal_t = 26; pub const SIGWINCH: signal_t = 27; pub const SIGPOLL: signal_t = 28; pub const SIGPWR: signal_t = 29; pub const SIGSYS: signal_t = 30; pub const subclockflags_t = u16; pub const SUBSCRIPTION_CLOCK_ABSTIME: subclockflags_t = 0x0001; pub const subscription_t = extern struct { userdata: userdata_t, u: subscription_u_t, }; pub const subscription_clock_t = extern struct { id: clockid_t, timeout: timestamp_t, precision: timestamp_t, flags: subclockflags_t, }; pub const subscription_fd_readwrite_t = extern struct { fd: fd_t, }; pub const subscription_u_t = extern struct { tag: eventtype_t, u: subscription_u_u_t, }; pub const subscription_u_u_t = extern union { clock: subscription_clock_t, fd_read: subscription_fd_readwrite_t, fd_write: subscription_fd_readwrite_t, }; pub const timestamp_t = u64; pub const userdata_t = u64; pub const whence_t = u8; pub const WHENCE_SET: whence_t = 0; pub const WHENCE_CUR: whence_t = 1; pub const WHENCE_END: whence_t = 2;
lib/std/os/bits/wasi.zig
const std = @import("std"); const testing = std.testing; const console_ = @import("console.zig"); const Console = console_.Console; const Precision = console_.Precision; const video = @import("video.zig"); const audio = @import("audio.zig"); fn testRom( comptime precision: Precision, comptime rom: []const u8, cycles: usize, comptime buttons: ?[]const u8, expect_addr: u16, expect_val: u8, ) !void { var video_context = try video.Context(.pure).init(testing.allocator); defer video_context.deinit(testing.allocator); var audio_context = try audio.Context(.pure).init(testing.allocator); defer audio_context.deinit(testing.allocator); var console = Console(.{ .precision = precision, .method = .pure }).alloc(); console.init(testing.allocator, video_context.getPixelBuffer(), &audio_context); defer console.deinit(); try console.loadRom("roms/nes-test-roms/" ++ rom); console.cpu.reset(); if (buttons) |b| { console.controller.holdButtons(b); } while (console.cpu.cycles < cycles) { console.cpu.runStep(); } try testing.expectEqual(expect_val, console.cpu.mem.peek(expect_addr)); } fn testBlarggRom(comptime precision: Precision, comptime rom: []const u8, cycles: usize) !void { return testRom(precision, rom, cycles, null, 0x00f0, 0x01); } fn testBlarggRom2(comptime precision: Precision, comptime rom: []const u8, cycles: usize) !void { return testRom(precision, rom, cycles, null, 0x00f8, 0x01); } test "nestest.nes basic cpu accuracy" { try testRom(.fast, "other/nestest.nes", 700000, "S", 0x0000, 0x00); try testRom(.accurate, "other/nestest.nes", 700000, "S", 0x0000, 0x00); } test "blargg apu tests" { try testBlarggRom(.fast, "blargg_apu_2005.07.30/01.len_ctr.nes", 450000); try testBlarggRom(.accurate, "blargg_apu_2005.07.30/01.len_ctr.nes", 450000); try testBlarggRom(.fast, "blargg_apu_2005.07.30/02.len_table.nes", 25000); try testBlarggRom(.accurate, "blargg_apu_2005.07.30/02.len_table.nes", 25000); try testBlarggRom(.fast, "blargg_apu_2005.07.30/03.irq_flag.nes", 220000); try testBlarggRom(.accurate, "blargg_apu_2005.07.30/03.irq_flag.nes", 220000); } test "blargg ppu tests" { try testBlarggRom(.accurate, "blargg_ppu_tests_2005.09.15b/vram_access.nes", 120000); try testBlarggRom(.accurate, "blargg_ppu_tests_2005.09.15b/palette_ram.nes", 120000); try testBlarggRom(.fast, "blargg_ppu_tests_2005.09.15b/sprite_ram.nes", 120000); try testBlarggRom(.accurate, "blargg_ppu_tests_2005.09.15b/sprite_ram.nes", 120000); } test "blargg ppu sprite 0 tests" { try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/01.basics.nes", 800000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/01.basics.nes", 800000); try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/02.alignment.nes", 750000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/02.alignment.nes", 750000); try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/03.corners.nes", 450000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/03.corners.nes", 450000); try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/04.flip.nes", 400000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/04.flip.nes", 400000); //try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/07.screen_bottom.nes", 575000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/07.screen_bottom.nes", 575000); try testBlarggRom2(.fast, "sprite_hit_tests_2005.10.05/08.double_height.nes", 575000); try testBlarggRom2(.accurate, "sprite_hit_tests_2005.10.05/08.double_height.nes", 575000); } test { _ = @import("apu.zig"); _ = @import("audio.zig"); _ = @import("cart.zig"); _ = @import("console.zig"); _ = @import("controller.zig"); _ = @import("cpu.zig"); _ = @import("cpu/accurate.zig"); _ = @import("cpu/fast.zig"); _ = @import("flags.zig"); _ = @import("ines.zig"); _ = @import("instruction.zig"); _ = @import("interface.zig"); _ = @import("main.zig"); _ = @import("mapper/common.zig"); _ = @import("mapper/nrom.zig"); _ = @import("mapper/mmc1.zig"); _ = @import("mapper.zig"); _ = @import("ppu/accurate.zig"); _ = @import("ppu/common.zig"); _ = @import("ppu/fast.zig"); _ = @import("ppu.zig"); _ = @import("video.zig"); }
src/tests.zig
const std = @import("std"); const version = @import("version"); const zzz = @import("zzz"); const Engine = @import("Engine.zig"); const Dependency = @import("Dependency.zig"); const api = @import("api.zig"); const cache = @import("cache.zig"); const utils = @import("utils.zig"); const Allocator = std.mem.Allocator; const testing = std.testing; const assert = std.debug.assert; pub const name = "pkg"; pub const Resolution = version.Semver; pub const ResolutionEntry = struct { repository: []const u8, user: []const u8, name: []const u8, semver: version.Semver, dep_idx: ?usize, pub fn format( entry: ResolutionEntry, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) @TypeOf(writer).Error!void { _ = fmt; _ = options; try writer.print("{s}/{s}/{s}: {} -> {}", .{ entry.repository, entry.user, entry.name, entry.semver, entry.dep_idx, }); } }; pub const FetchError = @typeInfo(@typeInfo(@TypeOf(api.getLatest)).Fn.return_type.?).ErrorUnion.error_set || @typeInfo(@typeInfo(@TypeOf(fetch)).Fn.return_type.?).ErrorUnion.error_set; const FetchQueue = Engine.MultiQueueImpl(Resolution, FetchError); const ResolutionTable = std.ArrayListUnmanaged(ResolutionEntry); pub fn deserializeLockfileEntry( allocator: *Allocator, it: *std.mem.TokenIterator(u8), resolutions: *ResolutionTable, ) !void { const repo = it.next() orelse return error.NoRepo; try resolutions.append(allocator, .{ .repository = if (std.mem.eql(u8, repo, "default")) "astrolabe.pm" else repo, .user = it.next() orelse return error.NoUser, .name = it.next() orelse return error.NoName, .semver = try version.Semver.parse(allocator, it.next() orelse return error.NoVersion), .dep_idx = null, }); } pub fn serializeResolutions( resolutions: []const ResolutionEntry, writer: anytype, ) !void { for (resolutions) |resolution| if (resolution.dep_idx != null) try writer.print("pkg {s} {s} {s} {}\n", .{ resolution.repository, resolution.user, resolution.name, resolution.semver, }); } fn findResolution(dep: Dependency.Source, resolutions: []const ResolutionEntry) ?usize { return for (resolutions) |entry, j| { if (std.mem.eql(u8, dep.pkg.repository, entry.repository) and std.mem.eql(u8, dep.pkg.user, entry.user) and std.mem.eql(u8, dep.pkg.name, entry.name) and dep.pkg.version.contains(entry.semver)) { break j; } } else null; } fn findMatch(dep_table: []const Dependency.Source, dep_idx: usize, edges: []const Engine.Edge) ?usize { // TODO: handle different version range kinds const dep = dep_table[dep_idx].pkg; return for (edges) |edge| { const other = dep_table[edge.to].pkg; if (std.mem.eql(u8, dep.repository, other.repository) and std.mem.eql(u8, dep.user, other.user) and std.mem.eql(u8, dep.name, other.name) and (dep.version.contains(other.version.min) or other.version.contains(dep.version.min))) { break edge.to; } } else null; } fn updateBasePaths( arena: *std.heap.ArenaAllocator, base_path: []const u8, deps: *std.ArrayListUnmanaged(Dependency), ) !void { for (deps.items) |*dep| if (dep.src == .local) { const resolved = try std.fs.path.resolve( arena.child_allocator, &.{ base_path, dep.src.local.path }, ); defer arena.child_allocator.free(resolved); dep.src.local.path = try std.fs.path.relative(&arena.allocator, ".", resolved); }; } fn fetch( arena: *std.heap.ArenaAllocator, dep: Dependency.Source, semver: Resolution, deps: *std.ArrayListUnmanaged(Dependency), path: *?[]const u8, ) !void { const allocator = arena.child_allocator; const entry_name = try std.fmt.allocPrint(allocator, "{s}-{s}-{}-{s}", .{ dep.pkg.name, dep.pkg.user, semver, dep.pkg.repository, }); defer allocator.free(entry_name); var entry = try cache.getEntry(entry_name); defer entry.deinit(); if (!try entry.isDone()) { try api.getPkg( allocator, dep.pkg.repository, dep.pkg.user, dep.pkg.name, semver, entry.dir, ); try entry.done(); } const base_path = try std.fs.path.join(arena.child_allocator, &.{ ".gyro", entry_name, "pkg" }); defer arena.child_allocator.free(base_path); const manifest = try entry.dir.openFile("manifest.zzz", .{}); defer manifest.close(); const text = try manifest.reader().readAllAlloc(&arena.allocator, std.math.maxInt(usize)); var ztree = zzz.ZTree(1, 1000){}; var root = try ztree.appendText(text); if (utils.zFindChild(root, "deps")) |deps_node| { var it = utils.ZChildIterator.init(deps_node); while (it.next()) |node| try deps.append( allocator, try Dependency.fromZNode(allocator, node), ); } try updateBasePaths(arena, base_path, deps); path.* = try utils.joinPathConvertSep(arena, &.{ ".gyro", entry_name, "pkg", (try utils.zFindString(root, "root")) orelse { std.log.err("fatal: manifest missing pkg root path: {s}/{s}/{s} {}", .{ dep.pkg.repository, dep.pkg.user, dep.pkg.name, semver, }); return error.Explained; }, }); } pub fn dedupeResolveAndFetch( dep_table: []const Dependency.Source, resolutions: []const ResolutionEntry, fetch_queue: *FetchQueue, i: usize, ) FetchError!void { const arena = &fetch_queue.items(.arena)[i]; const dep_idx = fetch_queue.items(.edge)[i].to; if (findResolution(dep_table[dep_idx], resolutions)) |res_idx| { if (resolutions[res_idx].dep_idx) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else if (findMatch(dep_table, dep_idx, fetch_queue.items(.edge)[0..i])) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else { fetch_queue.items(.result)[i] = .{ .fill_resolution = res_idx, }; } } else if (findMatch(dep_table, dep_idx, fetch_queue.items(.edge)[0..i])) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else { fetch_queue.items(.result)[i] = .{ .new_entry = try api.getLatest( &arena.allocator, dep_table[dep_idx].pkg.repository, dep_table[dep_idx].pkg.user, dep_table[dep_idx].pkg.name, dep_table[dep_idx].pkg.version, ), }; } const resolution = switch (fetch_queue.items(.result)[i]) { .fill_resolution => |res_idx| resolutions[res_idx].semver, .new_entry => |semver| semver, else => unreachable, }; try fetch( arena, dep_table[dep_idx], resolution, &fetch_queue.items(.deps)[i], &fetch_queue.items(.path)[i], ); assert(fetch_queue.items(.path)[i] != null); } pub fn updateResolution( allocator: *Allocator, resolutions: *ResolutionTable, dep_table: []const Dependency.Source, fetch_queue: *FetchQueue, i: usize, ) !void { switch (fetch_queue.items(.result)[i]) { .fill_resolution => |res_idx| { const dep_idx = fetch_queue.items(.edge)[i].to; assert(resolutions.items[res_idx].dep_idx == null); resolutions.items[res_idx].dep_idx = dep_idx; }, .new_entry => |semver| { const dep_idx = fetch_queue.items(.edge)[i].to; const pkg = &dep_table[dep_idx].pkg; try resolutions.append(allocator, .{ .repository = pkg.repository, .user = pkg.user, .name = pkg.name, .semver = semver, .dep_idx = dep_idx, }); }, .replace_me => |dep_idx| fetch_queue.items(.edge)[i].to = dep_idx, .err => |err| return err, else => unreachable, } } test "deserializeLockfileEntry" { const lines = [_][]const u8{ "default matt something 0.1.0", "my_own_repository matt foo 0.2.0", }; var expected = ResolutionTable{}; defer expected.deinit(testing.allocator); try expected.append(testing.allocator, .{ .repository = "astrolabe.pm", .user = "matt", .name = "something", .semver = .{ .major = 0, .minor = 1, .patch = 0, }, .dep_idx = null, }); try expected.append(testing.allocator, .{ .repository = "my_own_repository", .user = "matt", .name = "foo", .semver = .{ .major = 0, .minor = 2, .patch = 0, }, .dep_idx = null, }); var resolutions = ResolutionTable{}; defer resolutions.deinit(testing.allocator); for (lines) |line| { var it = std.mem.tokenize(u8, line, " "); try deserializeLockfileEntry(testing.allocator, &it, &resolutions); } for (resolutions.items) |resolution, i| { try testing.expectEqualStrings(expected.items[i].repository, resolution.repository); try testing.expectEqualStrings(expected.items[i].user, resolution.user); try testing.expectEqualStrings(expected.items[i].name, resolution.name); try testing.expectEqual(expected.items[i].semver, resolution.semver); } } test "serializeResolutions" { var resolutions = ResolutionTable{}; defer resolutions.deinit(testing.allocator); try resolutions.append(testing.allocator, .{ .repository = "astrolabe.pm", .user = "matt", .name = "something", .semver = .{ .major = 0, .minor = 1, .patch = 0, }, .dep_idx = null, }); try resolutions.append(testing.allocator, .{ .repository = "my_own_repository", .user = "matt", .name = "foo", .semver = .{ .major = 0, .minor = 2, .patch = 0, }, .dep_idx = null, }); var buf: [4096]u8 = undefined; var fb = std.io.fixedBufferStream(&buf); const expected = \\pkg astrolabe.pm matt something 0.1.0 \\pkg my_own_repository matt foo 0.2.0 \\ ; try serializeResolutions(resolutions.items, fb.writer()); try testing.expectEqualStrings(expected, buf[0..expected.len]); } test "dedupeResolveAndFetch: existing resolution" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const dep = Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "matt", .name = "foo", .version = .{ .min = .{ .major = 0, .minor = 2, .patch = 0, }, .kind = .caret, }, }, }; const resolution = ResolutionEntry{ .repository = "astrolabe.pm", .user = "matt", .name = "foo", .semver = .{ .major = 0, .minor = 2, .patch = 0, }, .dep_idx = 5, }; var fetch_queue = FetchQueue{}; defer fetch_queue.deinit(testing.allocator); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 0, .alias = "blarg", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); try dedupeResolveAndFetch(&arena, &.{dep}, &.{resolution}, &fetch_queue, 0); try testing.expectEqual(resolution.dep_idx, fetch_queue.items(.result)[0].replace_me); } test "dedupeResolveAndFetch: resolution without index" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const dep = Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "version", .version = .{ .min = .{ .major = 0, .minor = 1, .patch = 0, }, .kind = .caret, }, }, }; var resolutions = ResolutionTable{}; defer resolutions.deinit(testing.allocator); try resolutions.append(testing.allocator, .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "glob", .semver = .{ .major = 0, .minor = 0, .patch = 0, }, .dep_idx = null, }); try resolutions.append(testing.allocator, .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "version", .semver = .{ .major = 0, .minor = 1, .patch = 0, }, .dep_idx = null, }); var fetch_queue = FetchQueue{}; defer fetch_queue.deinit(testing.allocator); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 0, .alias = "blarg", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); try dedupeResolveAndFetch(&arena, &.{dep}, resolutions.items, &fetch_queue, 0); try testing.expectEqual(@as(usize, 1), fetch_queue.items(.result)[0].fill_resolution); try updateResolution(testing.allocator, &resolutions, &.{dep}, fetch_queue, 0); try testing.expectEqual(@as(?usize, 0), resolutions.items[1].dep_idx); } test "dedupeResolveAndFetch: new entry" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const deps = &.{ Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "download", .version = .{ .min = .{ .major = 0, .minor = 1, .patch = 0, }, .kind = .caret, }, }, }, Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "download", .version = .{ .min = .{ .major = 0, .minor = 1, .patch = 2, }, .kind = .caret, }, }, }, }; var resolutions = ResolutionTable{}; defer resolutions.deinit(testing.allocator); var fetch_queue = FetchQueue{}; defer fetch_queue.deinit(testing.allocator); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 0, .alias = "foo", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 1, .alias = "blarg", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); for (fetch_queue.items(.edge)) |_, i| try dedupeResolveAndFetch(&arena, deps, resolutions.items, &fetch_queue, i); for (fetch_queue.items(.edge)) |_, i| try updateResolution(testing.allocator, &resolutions, deps, fetch_queue, i); try testing.expect(fetch_queue.items(.result)[0] == .new_entry); try testing.expectEqual(@TypeOf(fetch_queue.items(.result)[0]){ .replace_me = 0 }, fetch_queue.items(.result)[1]); try testing.expectEqual(@as(usize, 0), fetch_queue.items(.result)[1].replace_me); try testing.expectEqual(@as(?usize, 0), resolutions.items[0].dep_idx); } test "dedupeResolveAndFetch: collision in batch" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const deps = &.{ Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "download", .version = .{ .min = .{ .major = 0, .minor = 1, .patch = 0, }, .kind = .caret, }, }, }, Dependency.Source{ .pkg = .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "download", .version = .{ .min = .{ .major = 0, .minor = 1, .patch = 2, }, .kind = .caret, }, }, }, }; var resolutions = ResolutionTable{}; defer resolutions.deinit(testing.allocator); try resolutions.append(testing.allocator, .{ .repository = "astrolabe.pm", .user = "mattnite", .name = "download", .semver = .{ .major = 0, .minor = 1, .patch = 2, }, .dep_idx = null, }); var fetch_queue = FetchQueue{}; defer fetch_queue.deinit(testing.allocator); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 0, .alias = "foo", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); try fetch_queue.append(testing.allocator, .{ .edge = .{ .from = .{ .root = .normal, }, .to = 1, .alias = "blarg", }, .deps = std.ArrayListUnmanaged(Dependency){}, }); for (fetch_queue.items(.edge)) |_, i| try dedupeResolveAndFetch(&arena, deps, resolutions.items, &fetch_queue, i); for (fetch_queue.items(.edge)) |_, i| try updateResolution(testing.allocator, &resolutions, deps, fetch_queue, i); try testing.expectEqual(@as(usize, 0), fetch_queue.items(.result)[0].fill_resolution); try testing.expectEqual(fetch_queue.items(.edge)[0].to, fetch_queue.items(.result)[1].replace_me); try testing.expectEqual(@as(?usize, 0), resolutions.items[0].dep_idx); }
src/pkg.zig
const fmath = @import("index.zig"); pub fn pow(comptime T: type, x: T, y: T) -> T { switch (T) { f32 => @inlineCall(pow32, x, y), f64 => @inlineCall(pow64, x, y), else => @compileError("pow not implemented for " ++ @typeName(T)), } } fn isOddInteger(x: f64) -> bool { const r = fmath.modf(x); r.fpart == 0.0 and i64(r.ipart) & 1 == 1 } // This implementation is taken from the go stlib, musl is a bit more complex. fn pow32(x: f32, y: f32) -> f32 { // pow(x, +-0) = 1 for all x // pow(1, y) = 1 for all y if (y == 0 or x == 1) { return 1; } // pow(nan, y) = nan for all y // pow(x, nan) = nan for all x if (fmath.isNan(x) or fmath.isNan(y)) { return fmath.nan(f32); } // pow(x, 1) = x for all x if (y == 1) { return x; } // special case sqrt if (y == 0.5) { return fmath.sqrt(x); } if (y == -0.5) { return 1 / fmath.sqrt(x); } if (x == 0) { if (y < 0) { // pow(+-0, y) = +- 0 for y an odd integer if (isOddInteger(y)) { return fmath.copysign(f32, fmath.inf(f32), x); } // pow(+-0, y) = +inf for y an even integer else { return fmath.inf(f32); } } else { if (isOddInteger(y)) { return x; } else { return 0; } } } if (fmath.isInf(y)) { // pow(-1, inf) = -1 for all x if (x == -1) { return -1; } // pow(x, +inf) = +0 for |x| < 1 // pow(x, -inf) = +0 for |x| > 1 else if ((fmath.fabs(x) < 1) == fmath.isPositiveInf(y)) { return 0; } // pow(x, -inf) = +inf for |x| < 1 // pow(x, +inf) = +inf for |x| > 1 else { return fmath.inf(f32); } } if (fmath.isInf(x)) { if (fmath.isNegativeInf(x)) { return pow32(1 / x, -y); } // pow(+inf, y) = +0 for y < 0 else if (y < 0) { return 0; } // pow(+inf, y) = +0 for y > 0 else if (y > 0) { return fmath.inf(f32); } } var ay = y; var flip = false; if (ay < 0) { ay = -ay; flip = true; } const r1 = fmath.modf(ay); var yi = r1.ipart; var yf = r1.fpart; if (yf != 0 and x < 0) { return fmath.nan(f32); } if (yi >= 1 << 31) { return fmath.exp(y * fmath.log(x)); } // a = a1 * 2^ae var a1: f32 = 1.0; var ae: i32 = 0; // a *= x^yf if (yf != 0) { if (yf > 0.5) { yf -= 1; yi += 1; } a1 = fmath.exp(yf * fmath.log(x)); } // a *= x^yi const r2 = fmath.frexp(x); var xe = r2.exponent; var x1 = r2.significand; var i = i32(yi); while (i != 0) : (i >>= 1) { if (i & 1 == 1) { a1 *= x1; ae += xe; } x1 *= x1; xe <<= 1; if (x1 < 0.5) { x1 += x1; xe -= 1; } } // a *= a1 * 2^ae if (flip) { a1 = 1 / a1; ae = -ae; } fmath.scalbn(a1, ae) } // This implementation is taken from the go stlib, musl is a bit more complex. fn pow64(x: f64, y: f64) -> f64 { // pow(x, +-0) = 1 for all x // pow(1, y) = 1 for all y if (y == 0 or x == 1) { return 1; } // pow(nan, y) = nan for all y // pow(x, nan) = nan for all x if (fmath.isNan(x) or fmath.isNan(y)) { return fmath.nan(f64); } // pow(x, 1) = x for all x if (y == 1) { return x; } // special case sqrt if (y == 0.5) { return fmath.sqrt(x); } if (y == -0.5) { return 1 / fmath.sqrt(x); } if (x == 0) { if (y < 0) { // pow(+-0, y) = +- 0 for y an odd integer if (isOddInteger(y)) { return fmath.copysign(f64, fmath.inf(f64), x); } // pow(+-0, y) = +inf for y an even integer else { return fmath.inf(f64); } } else { if (isOddInteger(y)) { return x; } else { return 0; } } } if (fmath.isInf(y)) { // pow(-1, inf) = -1 for all x if (x == -1) { return -1; } // pow(x, +inf) = +0 for |x| < 1 // pow(x, -inf) = +0 for |x| > 1 else if ((fmath.fabs(x) < 1) == fmath.isInf(y)) { return 0; } // pow(x, -inf) = +inf for |x| < 1 // pow(x, +inf) = +inf for |x| > 1 else { return fmath.inf(f64); } } if (fmath.isInf(x)) { if (fmath.isInf(x)) { return pow64(1 / x, -y); } // pow(+inf, y) = +0 for y < 0 else if (y < 0) { return 0; } // pow(+inf, y) = +0 for y > 0 else if (y > 0) { return fmath.inf(f64); } } var ay = y; var flip = false; if (ay < 0) { ay = -ay; flip = true; } const r1 = fmath.modf(ay); var yi = r1.ipart; var yf = r1.fpart; if (yf != 0 and x < 0) { return fmath.nan(f64); } if (yi >= 1 << 63) { return fmath.exp(y * fmath.log(x)); } // a = a1 * 2^ae var a1: f64 = 1.0; var ae: i32 = 0; // a *= x^yf if (yf != 0) { if (yf > 0.5) { yf -= 1; yi += 1; } a1 = fmath.exp(yf * fmath.log(x)); } // a *= x^yi const r2 = fmath.frexp(x); var xe = r2.exponent; var x1 = r2.significand; var i = i64(yi); while (i != 0) : (i >>= 1) { if (i & 1 == 1) { a1 *= x1; ae += xe; } x1 *= x1; xe <<= 1; if (x1 < 0.5) { x1 += x1; xe -= 1; } } // a *= a1 * 2^ae if (flip) { a1 = 1 / a1; ae = -ae; } fmath.scalbn(a1, ae) } test "pow" { fmath.assert(pow(f32, 0.2, 3.3) == pow32(0.2, 3.3)); fmath.assert(pow(f64, 0.2, 3.3) == pow64(0.2, 3.3)); } test "pow32" { const epsilon = 0.000001; // fmath.assert(fmath.approxEq(f32, pow32(0.0, 3.3), 0.0, epsilon)); // TODO: Handle div zero fmath.assert(fmath.approxEq(f32, pow32(0.8923, 3.3), 0.686572, epsilon)); fmath.assert(fmath.approxEq(f32, pow32(0.2, 3.3), 0.004936, epsilon)); fmath.assert(fmath.approxEq(f32, pow32(1.5, 3.3), 3.811546, epsilon)); fmath.assert(fmath.approxEq(f32, pow32(37.45, 3.3), 155736.703125, epsilon)); fmath.assert(fmath.approxEq(f32, pow32(89.123, 3.3), 2722489.5, epsilon)); } test "pow64" { const epsilon = 0.000001; // fmath.assert(fmath.approxEq(f32, pow32(0.0, 3.3), 0.0, epsilon)); // TODO: Handle div zero fmath.assert(fmath.approxEq(f64, pow64(0.8923, 3.3), 0.686572, epsilon)); fmath.assert(fmath.approxEq(f64, pow64(0.2, 3.3), 0.004936, epsilon)); fmath.assert(fmath.approxEq(f64, pow64(1.5, 3.3), 3.811546, epsilon)); fmath.assert(fmath.approxEq(f64, pow64(37.45, 3.3), 155736.7160616, epsilon)); fmath.assert(fmath.approxEq(f64, pow64(89.123, 3.3), 2722490.231436, epsilon)); }
src/pow.zig
pub const JET_bitConfigStoreReadControlInhibitRead = @as(u32, 1); pub const JET_bitConfigStoreReadControlDisableAll = @as(u32, 2); pub const JET_bitConfigStoreReadControlDefault = @as(u32, 0); pub const JET_bitDefragmentBatchStart = @as(u32, 1); pub const JET_bitDefragmentBatchStop = @as(u32, 2); pub const JET_bitDefragmentAvailSpaceTreesOnly = @as(u32, 64); pub const JET_bitDefragmentNoPartialMerges = @as(u32, 128); pub const JET_bitDefragmentBTree = @as(u32, 256); pub const JET_cbtypNull = @as(u32, 0); pub const JET_cbtypFinalize = @as(u32, 1); pub const JET_cbtypBeforeInsert = @as(u32, 2); pub const JET_cbtypAfterInsert = @as(u32, 4); pub const JET_cbtypBeforeReplace = @as(u32, 8); pub const JET_cbtypAfterReplace = @as(u32, 16); pub const JET_cbtypBeforeDelete = @as(u32, 32); pub const JET_cbtypAfterDelete = @as(u32, 64); pub const JET_cbtypUserDefinedDefaultValue = @as(u32, 128); pub const JET_cbtypOnlineDefragCompleted = @as(u32, 256); pub const JET_cbtypFreeCursorLS = @as(u32, 512); pub const JET_cbtypFreeTableLS = @as(u32, 1024); pub const JET_bitTableInfoUpdatable = @as(u32, 1); pub const JET_bitTableInfoBookmark = @as(u32, 2); pub const JET_bitTableInfoRollback = @as(u32, 4); pub const JET_bitObjectSystem = @as(u32, 2147483648); pub const JET_bitObjectTableFixedDDL = @as(u32, 1073741824); pub const JET_bitObjectTableTemplate = @as(u32, 536870912); pub const JET_bitObjectTableDerived = @as(u32, 268435456); pub const JET_bitObjectTableNoFixedVarColumnsInDerivedTables = @as(u32, 67108864); pub const JET_MAX_COMPUTERNAME_LENGTH = @as(u32, 15); pub const JET_bitDurableCommitCallbackLogUnavailable = @as(u32, 1); pub const JET_cbBookmarkMost = @as(u32, 256); pub const JET_cbNameMost = @as(u32, 64); pub const JET_cbFullNameMost = @as(u32, 255); pub const JET_cbColumnLVPageOverhead = @as(u32, 82); pub const JET_cbLVDefaultValueMost = @as(u32, 255); pub const JET_cbColumnMost = @as(u32, 255); pub const JET_cbLVColumnMost = @as(u32, 2147483647); pub const JET_cbKeyMost8KBytePage = @as(u32, 2000); pub const JET_cbKeyMost4KBytePage = @as(u32, 1000); pub const JET_cbKeyMost2KBytePage = @as(u32, 500); pub const JET_cbKeyMostMin = @as(u32, 255); pub const JET_cbKeyMost = @as(u32, 255); pub const JET_cbLimitKeyMost = @as(u32, 256); pub const JET_cbPrimaryKeyMost = @as(u32, 255); pub const JET_cbSecondaryKeyMost = @as(u32, 255); pub const JET_ccolKeyMost = @as(u32, 16); pub const JET_ccolMost = @as(u32, 65248); pub const JET_ccolFixedMost = @as(u32, 127); pub const JET_ccolVarMost = @as(u32, 128); pub const JET_EventLoggingDisable = @as(u32, 0); pub const JET_EventLoggingLevelMin = @as(u32, 1); pub const JET_EventLoggingLevelLow = @as(u32, 25); pub const JET_EventLoggingLevelMedium = @as(u32, 50); pub const JET_EventLoggingLevelHigh = @as(u32, 75); pub const JET_EventLoggingLevelMax = @as(u32, 100); pub const JET_IOPriorityNormal = @as(u32, 0); pub const JET_IOPriorityLow = @as(u32, 1); pub const JET_configDefault = @as(u32, 1); pub const JET_configRemoveQuotas = @as(u32, 2); pub const JET_configLowDiskFootprint = @as(u32, 4); pub const JET_configMediumDiskFootprint = @as(u32, 8); pub const JET_configLowMemory = @as(u32, 16); pub const JET_configDynamicMediumMemory = @as(u32, 32); pub const JET_configLowPower = @as(u32, 64); pub const JET_configSSDProfileIO = @as(u32, 128); pub const JET_configRunSilent = @as(u32, 256); pub const JET_configUnthrottledMemory = @as(u32, 512); pub const JET_configHighConcurrencyScaling = @as(u32, 1024); pub const JET_paramSystemPath = @as(u32, 0); pub const JET_paramTempPath = @as(u32, 1); pub const JET_paramLogFilePath = @as(u32, 2); pub const JET_paramBaseName = @as(u32, 3); pub const JET_paramEventSource = @as(u32, 4); pub const JET_paramMaxSessions = @as(u32, 5); pub const JET_paramMaxOpenTables = @as(u32, 6); pub const JET_paramPreferredMaxOpenTables = @as(u32, 7); pub const JET_paramCachedClosedTables = @as(u32, 125); pub const JET_paramMaxCursors = @as(u32, 8); pub const JET_paramMaxVerPages = @as(u32, 9); pub const JET_paramPreferredVerPages = @as(u32, 63); pub const JET_paramGlobalMinVerPages = @as(u32, 81); pub const JET_paramVersionStoreTaskQueueMax = @as(u32, 105); pub const JET_paramMaxTemporaryTables = @as(u32, 10); pub const JET_paramLogFileSize = @as(u32, 11); pub const JET_paramLogBuffers = @as(u32, 12); pub const JET_paramWaitLogFlush = @as(u32, 13); pub const JET_paramLogCheckpointPeriod = @as(u32, 14); pub const JET_paramLogWaitingUserMax = @as(u32, 15); pub const JET_paramCommitDefault = @as(u32, 16); pub const JET_paramCircularLog = @as(u32, 17); pub const JET_paramDbExtensionSize = @as(u32, 18); pub const JET_paramPageTempDBMin = @as(u32, 19); pub const JET_paramPageFragment = @as(u32, 20); pub const JET_paramEnableFileCache = @as(u32, 126); pub const JET_paramVerPageSize = @as(u32, 128); pub const JET_paramConfiguration = @as(u32, 129); pub const JET_paramEnableAdvanced = @as(u32, 130); pub const JET_paramMaxColtyp = @as(u32, 131); pub const JET_paramBatchIOBufferMax = @as(u32, 22); pub const JET_paramCacheSize = @as(u32, 41); pub const JET_paramCacheSizeMin = @as(u32, 60); pub const JET_paramCacheSizeMax = @as(u32, 23); pub const JET_paramCheckpointDepthMax = @as(u32, 24); pub const JET_paramLRUKCorrInterval = @as(u32, 25); pub const JET_paramLRUKHistoryMax = @as(u32, 26); pub const JET_paramLRUKPolicy = @as(u32, 27); pub const JET_paramLRUKTimeout = @as(u32, 28); pub const JET_paramLRUKTrxCorrInterval = @as(u32, 29); pub const JET_paramOutstandingIOMax = @as(u32, 30); pub const JET_paramStartFlushThreshold = @as(u32, 31); pub const JET_paramStopFlushThreshold = @as(u32, 32); pub const JET_paramEnableViewCache = @as(u32, 127); pub const JET_paramCheckpointIOMax = @as(u32, 135); pub const JET_paramTableClass1Name = @as(u32, 137); pub const JET_paramTableClass2Name = @as(u32, 138); pub const JET_paramTableClass3Name = @as(u32, 139); pub const JET_paramTableClass4Name = @as(u32, 140); pub const JET_paramTableClass5Name = @as(u32, 141); pub const JET_paramTableClass6Name = @as(u32, 142); pub const JET_paramTableClass7Name = @as(u32, 143); pub const JET_paramTableClass8Name = @as(u32, 144); pub const JET_paramTableClass9Name = @as(u32, 145); pub const JET_paramTableClass10Name = @as(u32, 146); pub const JET_paramTableClass11Name = @as(u32, 147); pub const JET_paramTableClass12Name = @as(u32, 148); pub const JET_paramTableClass13Name = @as(u32, 149); pub const JET_paramTableClass14Name = @as(u32, 150); pub const JET_paramTableClass15Name = @as(u32, 151); pub const JET_paramIOPriority = @as(u32, 152); pub const JET_paramRecovery = @as(u32, 34); pub const JET_paramEnableOnlineDefrag = @as(u32, 35); pub const JET_paramCheckFormatWhenOpenFail = @as(u32, 44); pub const JET_paramEnableTempTableVersioning = @as(u32, 46); pub const JET_paramIgnoreLogVersion = @as(u32, 47); pub const JET_paramDeleteOldLogs = @as(u32, 48); pub const JET_paramEventSourceKey = @as(u32, 49); pub const JET_paramNoInformationEvent = @as(u32, 50); pub const JET_paramEventLoggingLevel = @as(u32, 51); pub const JET_paramDeleteOutOfRangeLogs = @as(u32, 52); pub const JET_paramAccessDeniedRetryPeriod = @as(u32, 53); pub const JET_paramEnableIndexChecking = @as(u32, 45); pub const JET_paramEnableIndexCleanup = @as(u32, 54); pub const JET_paramDatabasePageSize = @as(u32, 64); pub const JET_paramDisableCallbacks = @as(u32, 65); pub const JET_paramLogFileCreateAsynch = @as(u32, 69); pub const JET_paramErrorToString = @as(u32, 70); pub const JET_paramZeroDatabaseDuringBackup = @as(u32, 71); pub const JET_paramUnicodeIndexDefault = @as(u32, 72); pub const JET_paramRuntimeCallback = @as(u32, 73); pub const JET_paramCleanupMismatchedLogFiles = @as(u32, 77); pub const JET_paramRecordUpgradeDirtyLevel = @as(u32, 78); pub const JET_paramOSSnapshotTimeout = @as(u32, 82); pub const JET_paramExceptionAction = @as(u32, 98); pub const JET_paramEventLogCache = @as(u32, 99); pub const JET_paramCreatePathIfNotExist = @as(u32, 100); pub const JET_paramPageHintCacheSize = @as(u32, 101); pub const JET_paramOneDatabasePerSession = @as(u32, 102); pub const JET_paramMaxInstances = @as(u32, 104); pub const JET_paramDisablePerfmon = @as(u32, 107); pub const JET_paramIndexTuplesLengthMin = @as(u32, 110); pub const JET_paramIndexTuplesLengthMax = @as(u32, 111); pub const JET_paramIndexTuplesToIndexMax = @as(u32, 112); pub const JET_paramAlternateDatabaseRecoveryPath = @as(u32, 113); pub const JET_paramIndexTupleIncrement = @as(u32, 132); pub const JET_paramIndexTupleStart = @as(u32, 133); pub const JET_paramKeyMost = @as(u32, 134); pub const JET_paramLegacyFileNames = @as(u32, 136); pub const JET_paramEnablePersistedCallbacks = @as(u32, 156); pub const JET_paramWaypointLatency = @as(u32, 153); pub const JET_paramDefragmentSequentialBTrees = @as(u32, 160); pub const JET_paramDefragmentSequentialBTreesDensityCheckFrequency = @as(u32, 161); pub const JET_paramIOThrottlingTimeQuanta = @as(u32, 162); pub const JET_paramLVChunkSizeMost = @as(u32, 163); pub const JET_paramMaxCoalesceReadSize = @as(u32, 164); pub const JET_paramMaxCoalesceWriteSize = @as(u32, 165); pub const JET_paramMaxCoalesceReadGapSize = @as(u32, 166); pub const JET_paramMaxCoalesceWriteGapSize = @as(u32, 167); pub const JET_paramEnableDBScanInRecovery = @as(u32, 169); pub const JET_paramDbScanThrottle = @as(u32, 170); pub const JET_paramDbScanIntervalMinSec = @as(u32, 171); pub const JET_paramDbScanIntervalMaxSec = @as(u32, 172); pub const JET_paramCachePriority = @as(u32, 177); pub const JET_paramMaxTransactionSize = @as(u32, 178); pub const JET_paramPrereadIOMax = @as(u32, 179); pub const JET_paramEnableDBScanSerialization = @as(u32, 180); pub const JET_paramHungIOThreshold = @as(u32, 181); pub const JET_paramHungIOActions = @as(u32, 182); pub const JET_paramMinDataForXpress = @as(u32, 183); pub const JET_paramEnableShrinkDatabase = @as(u32, 184); pub const JET_paramProcessFriendlyName = @as(u32, 186); pub const JET_paramDurableCommitCallback = @as(u32, 187); pub const JET_paramEnableSqm = @as(u32, 188); pub const JET_paramConfigStoreSpec = @as(u32, 189); pub const JET_paramUseFlushForWriteDurability = @as(u32, 214); pub const JET_paramEnableRBS = @as(u32, 215); pub const JET_paramRBSFilePath = @as(u32, 216); pub const JET_paramMaxValueInvalid = @as(u32, 217); pub const JET_sesparamCommitDefault = @as(u32, 4097); pub const JET_sesparamTransactionLevel = @as(u32, 4099); pub const JET_sesparamOperationContext = @as(u32, 4100); pub const JET_sesparamCorrelationID = @as(u32, 4101); pub const JET_sesparamMaxValueInvalid = @as(u32, 4110); pub const JET_bitESE98FileNames = @as(u32, 1); pub const JET_bitEightDotThreeSoftCompat = @as(u32, 2); pub const JET_bitHungIOEvent = @as(u32, 1); pub const JET_bitShrinkDatabaseOff = @as(u32, 0); pub const JET_bitShrinkDatabaseOn = @as(u32, 1); pub const JET_bitShrinkDatabaseRealtime = @as(u32, 2); pub const JET_bitShrinkDatabaseTrim = @as(u32, 1); pub const JET_bitReplayIgnoreMissingDB = @as(u32, 4); pub const JET_bitRecoveryWithoutUndo = @as(u32, 8); pub const JET_bitTruncateLogsAfterRecovery = @as(u32, 16); pub const JET_bitReplayMissingMapEntryDB = @as(u32, 32); pub const JET_bitLogStreamMustExist = @as(u32, 64); pub const JET_bitReplayIgnoreLostLogs = @as(u32, 128); pub const JET_bitKeepDbAttachedAtEndOfRecovery = @as(u32, 4096); pub const JET_bitTermComplete = @as(u32, 1); pub const JET_bitTermAbrupt = @as(u32, 2); pub const JET_bitTermStopBackup = @as(u32, 4); pub const JET_bitTermDirty = @as(u32, 8); pub const JET_bitIdleFlushBuffers = @as(u32, 1); pub const JET_bitIdleCompact = @as(u32, 2); pub const JET_bitIdleStatus = @as(u32, 4); pub const JET_bitDbReadOnly = @as(u32, 1); pub const JET_bitDbExclusive = @as(u32, 2); pub const JET_bitDbDeleteCorruptIndexes = @as(u32, 16); pub const JET_bitDbDeleteUnicodeIndexes = @as(u32, 1024); pub const JET_bitDbUpgrade = @as(u32, 512); pub const JET_bitDbEnableBackgroundMaintenance = @as(u32, 2048); pub const JET_bitDbPurgeCacheOnAttach = @as(u32, 4096); pub const JET_bitForceDetach = @as(u32, 1); pub const JET_bitDbRecoveryOff = @as(u32, 8); pub const JET_bitDbShadowingOff = @as(u32, 128); pub const JET_bitDbOverwriteExisting = @as(u32, 512); pub const JET_bitBackupIncremental = @as(u32, 1); pub const JET_bitBackupAtomic = @as(u32, 4); pub const JET_bitBackupSnapshot = @as(u32, 16); pub const JET_bitBackupEndNormal = @as(u32, 1); pub const JET_bitBackupEndAbort = @as(u32, 2); pub const JET_bitBackupTruncateDone = @as(u32, 256); pub const JET_bitTableCreateFixedDDL = @as(u32, 1); pub const JET_bitTableCreateTemplateTable = @as(u32, 2); pub const JET_bitTableCreateNoFixedVarColumnsInDerivedTables = @as(u32, 4); pub const JET_bitTableCreateImmutableStructure = @as(u32, 8); pub const JET_bitColumnFixed = @as(u32, 1); pub const JET_bitColumnTagged = @as(u32, 2); pub const JET_bitColumnNotNULL = @as(u32, 4); pub const JET_bitColumnVersion = @as(u32, 8); pub const JET_bitColumnAutoincrement = @as(u32, 16); pub const JET_bitColumnUpdatable = @as(u32, 32); pub const JET_bitColumnTTKey = @as(u32, 64); pub const JET_bitColumnTTDescending = @as(u32, 128); pub const JET_bitColumnMultiValued = @as(u32, 1024); pub const JET_bitColumnEscrowUpdate = @as(u32, 2048); pub const JET_bitColumnUnversioned = @as(u32, 4096); pub const JET_bitColumnMaybeNull = @as(u32, 8192); pub const JET_bitColumnFinalize = @as(u32, 16384); pub const JET_bitColumnUserDefinedDefault = @as(u32, 32768); pub const JET_bitColumnDeleteOnZero = @as(u32, 131072); pub const JET_bitColumnCompressed = @as(u32, 524288); pub const JET_bitDeleteColumnIgnoreTemplateColumns = @as(u32, 1); pub const JET_bitMoveFirst = @as(u32, 0); pub const JET_bitNoMove = @as(u32, 2); pub const JET_bitNewKey = @as(u32, 1); pub const JET_bitStrLimit = @as(u32, 2); pub const JET_bitSubStrLimit = @as(u32, 4); pub const JET_bitNormalizedKey = @as(u32, 8); pub const JET_bitKeyDataZeroLength = @as(u32, 16); pub const JET_bitFullColumnStartLimit = @as(u32, 256); pub const JET_bitFullColumnEndLimit = @as(u32, 512); pub const JET_bitPartialColumnStartLimit = @as(u32, 1024); pub const JET_bitPartialColumnEndLimit = @as(u32, 2048); pub const JET_bitRangeInclusive = @as(u32, 1); pub const JET_bitRangeUpperLimit = @as(u32, 2); pub const JET_bitRangeInstantDuration = @as(u32, 4); pub const JET_bitRangeRemove = @as(u32, 8); pub const JET_bitReadLock = @as(u32, 1); pub const JET_bitWriteLock = @as(u32, 2); pub const JET_MoveFirst = @as(u32, 2147483648); pub const JET_MovePrevious = @as(i32, -1); pub const JET_MoveLast = @as(u32, 2147483647); pub const JET_bitMoveKeyNE = @as(u32, 1); pub const JET_bitSeekEQ = @as(u32, 1); pub const JET_bitSeekLT = @as(u32, 2); pub const JET_bitSeekLE = @as(u32, 4); pub const JET_bitSeekGE = @as(u32, 8); pub const JET_bitSeekGT = @as(u32, 16); pub const JET_bitSetIndexRange = @as(u32, 32); pub const JET_bitCheckUniqueness = @as(u32, 64); pub const JET_bitBookmarkPermitVirtualCurrency = @as(u32, 1); pub const JET_bitIndexColumnMustBeNull = @as(u32, 1); pub const JET_bitIndexColumnMustBeNonNull = @as(u32, 2); pub const JET_bitRecordInIndex = @as(u32, 1); pub const JET_bitRecordNotInIndex = @as(u32, 2); pub const JET_bitIndexUnique = @as(u32, 1); pub const JET_bitIndexPrimary = @as(u32, 2); pub const JET_bitIndexDisallowNull = @as(u32, 4); pub const JET_bitIndexIgnoreNull = @as(u32, 8); pub const JET_bitIndexIgnoreAnyNull = @as(u32, 32); pub const JET_bitIndexIgnoreFirstNull = @as(u32, 64); pub const JET_bitIndexLazyFlush = @as(u32, 128); pub const JET_bitIndexEmpty = @as(u32, 256); pub const JET_bitIndexUnversioned = @as(u32, 512); pub const JET_bitIndexSortNullsHigh = @as(u32, 1024); pub const JET_bitIndexUnicode = @as(u32, 2048); pub const JET_bitIndexTuples = @as(u32, 4096); pub const JET_bitIndexTupleLimits = @as(u32, 8192); pub const JET_bitIndexCrossProduct = @as(u32, 16384); pub const JET_bitIndexKeyMost = @as(u32, 32768); pub const JET_bitIndexDisallowTruncation = @as(u32, 65536); pub const JET_bitIndexNestedTable = @as(u32, 131072); pub const JET_bitIndexDotNetGuid = @as(u32, 262144); pub const JET_bitIndexImmutableStructure = @as(u32, 524288); pub const JET_bitKeyAscending = @as(u32, 0); pub const JET_bitKeyDescending = @as(u32, 1); pub const JET_bitTableDenyWrite = @as(u32, 1); pub const JET_bitTableDenyRead = @as(u32, 2); pub const JET_bitTableReadOnly = @as(u32, 4); pub const JET_bitTableUpdatable = @as(u32, 8); pub const JET_bitTablePermitDDL = @as(u32, 16); pub const JET_bitTableNoCache = @as(u32, 32); pub const JET_bitTablePreread = @as(u32, 64); pub const JET_bitTableOpportuneRead = @as(u32, 128); pub const JET_bitTableSequential = @as(u32, 32768); pub const JET_bitTableClassMask = @as(u32, 2031616); pub const JET_bitTableClassNone = @as(u32, 0); pub const JET_bitTableClass1 = @as(u32, 65536); pub const JET_bitTableClass2 = @as(u32, 131072); pub const JET_bitTableClass3 = @as(u32, 196608); pub const JET_bitTableClass4 = @as(u32, 262144); pub const JET_bitTableClass5 = @as(u32, 327680); pub const JET_bitTableClass6 = @as(u32, 393216); pub const JET_bitTableClass7 = @as(u32, 458752); pub const JET_bitTableClass8 = @as(u32, 524288); pub const JET_bitTableClass9 = @as(u32, 589824); pub const JET_bitTableClass10 = @as(u32, 655360); pub const JET_bitTableClass11 = @as(u32, 720896); pub const JET_bitTableClass12 = @as(u32, 786432); pub const JET_bitTableClass13 = @as(u32, 851968); pub const JET_bitTableClass14 = @as(u32, 917504); pub const JET_bitTableClass15 = @as(u32, 983040); pub const JET_bitLSReset = @as(u32, 1); pub const JET_bitLSCursor = @as(u32, 2); pub const JET_bitLSTable = @as(u32, 4); pub const JET_bitPrereadForward = @as(u32, 1); pub const JET_bitPrereadBackward = @as(u32, 2); pub const JET_bitPrereadFirstPage = @as(u32, 4); pub const JET_bitPrereadNormalizedKey = @as(u32, 8); pub const JET_bitTTIndexed = @as(u32, 1); pub const JET_bitTTUnique = @as(u32, 2); pub const JET_bitTTUpdatable = @as(u32, 4); pub const JET_bitTTScrollable = @as(u32, 8); pub const JET_bitTTSortNullsHigh = @as(u32, 16); pub const JET_bitTTForceMaterialization = @as(u32, 32); pub const JET_bitTTErrorOnDuplicateInsertion = @as(u32, 32); pub const JET_bitTTForwardOnly = @as(u32, 64); pub const JET_bitTTIntrinsicLVsOnly = @as(u32, 128); pub const JET_bitTTDotNetGuid = @as(u32, 256); pub const JET_bitSetAppendLV = @as(u32, 1); pub const JET_bitSetOverwriteLV = @as(u32, 4); pub const JET_bitSetSizeLV = @as(u32, 8); pub const JET_bitSetZeroLength = @as(u32, 32); pub const JET_bitSetSeparateLV = @as(u32, 64); pub const JET_bitSetUniqueMultiValues = @as(u32, 128); pub const JET_bitSetUniqueNormalizedMultiValues = @as(u32, 256); pub const JET_bitSetRevertToDefaultValue = @as(u32, 512); pub const JET_bitSetIntrinsicLV = @as(u32, 1024); pub const JET_bitSetUncompressed = @as(u32, 65536); pub const JET_bitSetCompressed = @as(u32, 131072); pub const JET_bitSetContiguousLV = @as(u32, 262144); pub const JET_bitSpaceHintsUtilizeParentSpace = @as(u32, 1); pub const JET_bitCreateHintAppendSequential = @as(u32, 2); pub const JET_bitCreateHintHotpointSequential = @as(u32, 4); pub const JET_bitRetrieveHintReserve1 = @as(u32, 8); pub const JET_bitRetrieveHintTableScanForward = @as(u32, 16); pub const JET_bitRetrieveHintTableScanBackward = @as(u32, 32); pub const JET_bitRetrieveHintReserve2 = @as(u32, 64); pub const JET_bitRetrieveHintReserve3 = @as(u32, 128); pub const JET_bitDeleteHintTableSequential = @as(u32, 256); pub const JET_prepInsert = @as(u32, 0); pub const JET_prepReplace = @as(u32, 2); pub const JET_prepCancel = @as(u32, 3); pub const JET_prepReplaceNoLock = @as(u32, 4); pub const JET_prepInsertCopy = @as(u32, 5); pub const JET_prepInsertCopyDeleteOriginal = @as(u32, 7); pub const JET_prepInsertCopyReplaceOriginal = @as(u32, 9); pub const JET_sqmDisable = @as(u32, 0); pub const JET_sqmEnable = @as(u32, 1); pub const JET_sqmFromCEIP = @as(u32, 2); pub const JET_bitUpdateCheckESE97Compatibility = @as(u32, 1); pub const JET_bitEscrowNoRollback = @as(u32, 1); pub const JET_bitRetrieveCopy = @as(u32, 1); pub const JET_bitRetrieveFromIndex = @as(u32, 2); pub const JET_bitRetrieveFromPrimaryBookmark = @as(u32, 4); pub const JET_bitRetrieveTag = @as(u32, 8); pub const JET_bitRetrieveNull = @as(u32, 16); pub const JET_bitRetrieveIgnoreDefault = @as(u32, 32); pub const JET_bitRetrieveTuple = @as(u32, 2048); pub const JET_bitZeroLength = @as(u32, 1); pub const JET_bitEnumerateCopy = @as(u32, 1); pub const JET_bitEnumerateIgnoreDefault = @as(u32, 32); pub const JET_bitEnumeratePresenceOnly = @as(u32, 131072); pub const JET_bitEnumerateTaggedOnly = @as(u32, 262144); pub const JET_bitEnumerateCompressOutput = @as(u32, 524288); pub const JET_bitEnumerateIgnoreUserDefinedDefault = @as(u32, 1048576); pub const JET_bitEnumerateInRecordOnly = @as(u32, 2097152); pub const JET_bitRecordSizeInCopyBuffer = @as(u32, 1); pub const JET_bitRecordSizeRunningTotal = @as(u32, 2); pub const JET_bitRecordSizeLocal = @as(u32, 4); pub const JET_bitTransactionReadOnly = @as(u32, 1); pub const JET_bitCommitLazyFlush = @as(u32, 1); pub const JET_bitWaitLastLevel0Commit = @as(u32, 2); pub const JET_bitWaitAllLevel0Commit = @as(u32, 8); pub const JET_bitForceNewLog = @as(u32, 16); pub const JET_bitRollbackAll = @as(u32, 1); pub const JET_bitIncrementalSnapshot = @as(u32, 1); pub const JET_bitCopySnapshot = @as(u32, 2); pub const JET_bitContinueAfterThaw = @as(u32, 4); pub const JET_bitExplicitPrepare = @as(u32, 8); pub const JET_bitAllDatabasesSnapshot = @as(u32, 1); pub const JET_bitAbortSnapshot = @as(u32, 1); pub const JET_DbInfoFilename = @as(u32, 0); pub const JET_DbInfoConnect = @as(u32, 1); pub const JET_DbInfoCountry = @as(u32, 2); pub const JET_DbInfoLCID = @as(u32, 3); pub const JET_DbInfoLangid = @as(u32, 3); pub const JET_DbInfoCp = @as(u32, 4); pub const JET_DbInfoCollate = @as(u32, 5); pub const JET_DbInfoOptions = @as(u32, 6); pub const JET_DbInfoTransactions = @as(u32, 7); pub const JET_DbInfoVersion = @as(u32, 8); pub const JET_DbInfoIsam = @as(u32, 9); pub const JET_DbInfoFilesize = @as(u32, 10); pub const JET_DbInfoSpaceOwned = @as(u32, 11); pub const JET_DbInfoSpaceAvailable = @as(u32, 12); pub const JET_DbInfoUpgrade = @as(u32, 13); pub const JET_DbInfoMisc = @as(u32, 14); pub const JET_DbInfoDBInUse = @as(u32, 15); pub const JET_DbInfoPageSize = @as(u32, 17); pub const JET_DbInfoFileType = @as(u32, 19); pub const JET_DbInfoFilesizeOnDisk = @as(u32, 21); pub const JET_dbstateJustCreated = @as(u32, 1); pub const JET_dbstateDirtyShutdown = @as(u32, 2); pub const JET_dbstateCleanShutdown = @as(u32, 3); pub const JET_dbstateBeingConverted = @as(u32, 4); pub const JET_dbstateForceDetach = @as(u32, 5); pub const JET_filetypeUnknown = @as(u32, 0); pub const JET_filetypeDatabase = @as(u32, 1); pub const JET_filetypeLog = @as(u32, 3); pub const JET_filetypeCheckpoint = @as(u32, 4); pub const JET_filetypeTempDatabase = @as(u32, 5); pub const JET_filetypeFlushMap = @as(u32, 7); pub const JET_revertstateNone = @as(u32, 0); pub const JET_revertstateInProgress = @as(u32, 1); pub const JET_revertstateCopingLogs = @as(u32, 2); pub const JET_revertstateCompleted = @as(u32, 3); pub const JET_bitDeleteAllExistingLogs = @as(u32, 1); pub const JET_coltypNil = @as(u32, 0); pub const JET_coltypBit = @as(u32, 1); pub const JET_coltypUnsignedByte = @as(u32, 2); pub const JET_coltypShort = @as(u32, 3); pub const JET_coltypLong = @as(u32, 4); pub const JET_coltypCurrency = @as(u32, 5); pub const JET_coltypIEEESingle = @as(u32, 6); pub const JET_coltypIEEEDouble = @as(u32, 7); pub const JET_coltypDateTime = @as(u32, 8); pub const JET_coltypBinary = @as(u32, 9); pub const JET_coltypText = @as(u32, 10); pub const JET_coltypLongBinary = @as(u32, 11); pub const JET_coltypLongText = @as(u32, 12); pub const JET_coltypMax = @as(u32, 13); pub const JET_coltypSLV = @as(u32, 13); pub const JET_coltypUnsignedLong = @as(u32, 14); pub const JET_coltypLongLong = @as(u32, 15); pub const JET_coltypGUID = @as(u32, 16); pub const JET_coltypUnsignedShort = @as(u32, 17); pub const JET_coltypUnsignedLongLong = @as(u32, 18); pub const JET_ColInfoGrbitNonDerivedColumnsOnly = @as(u32, 2147483648); pub const JET_ColInfoGrbitMinimalInfo = @as(u32, 1073741824); pub const JET_ColInfoGrbitSortByColumnid = @as(u32, 536870912); pub const JET_objtypNil = @as(u32, 0); pub const JET_objtypTable = @as(u32, 1); pub const JET_bitCompactStats = @as(u32, 32); pub const JET_bitCompactRepair = @as(u32, 64); pub const JET_snpRepair = @as(u32, 2); pub const JET_snpCompact = @as(u32, 4); pub const JET_snpRestore = @as(u32, 8); pub const JET_snpBackup = @as(u32, 9); pub const JET_snpUpgrade = @as(u32, 10); pub const JET_snpScrub = @as(u32, 11); pub const JET_snpUpgradeRecordFormat = @as(u32, 12); pub const JET_sntBegin = @as(u32, 5); pub const JET_sntRequirements = @as(u32, 7); pub const JET_sntProgress = @as(u32, 0); pub const JET_sntComplete = @as(u32, 6); pub const JET_sntFail = @as(u32, 3); pub const JET_ExceptionMsgBox = @as(u32, 1); pub const JET_ExceptionNone = @as(u32, 2); pub const JET_ExceptionFailFast = @as(u32, 4); pub const JET_OnlineDefragDisable = @as(u32, 0); pub const JET_OnlineDefragAllOBSOLETE = @as(u32, 1); pub const JET_OnlineDefragDatabases = @as(u32, 2); pub const JET_OnlineDefragSpaceTrees = @as(u32, 4); pub const JET_OnlineDefragAll = @as(u32, 65535); pub const JET_bitResizeDatabaseOnlyGrow = @as(u32, 1); pub const JET_bitResizeDatabaseOnlyShrink = @as(u32, 2); pub const JET_bitStopServiceAll = @as(u32, 0); pub const JET_bitStopServiceBackgroundUserTasks = @as(u32, 2); pub const JET_bitStopServiceQuiesceCaches = @as(u32, 4); pub const JET_bitStopServiceResume = @as(u32, 2147483648); pub const JET_errSuccess = @as(u32, 0); pub const JET_wrnNyi = @as(i32, -1); pub const JET_errRfsFailure = @as(i32, -100); pub const JET_errRfsNotArmed = @as(i32, -101); pub const JET_errFileClose = @as(i32, -102); pub const JET_errOutOfThreads = @as(i32, -103); pub const JET_errTooManyIO = @as(i32, -105); pub const JET_errTaskDropped = @as(i32, -106); pub const JET_errInternalError = @as(i32, -107); pub const JET_errDisabledFunctionality = @as(i32, -112); pub const JET_errUnloadableOSFunctionality = @as(i32, -113); pub const JET_errDatabaseBufferDependenciesCorrupted = @as(i32, -255); pub const JET_wrnRemainingVersions = @as(u32, 321); pub const JET_errPreviousVersion = @as(i32, -322); pub const JET_errPageBoundary = @as(i32, -323); pub const JET_errKeyBoundary = @as(i32, -324); pub const JET_errBadPageLink = @as(i32, -327); pub const JET_errBadBookmark = @as(i32, -328); pub const JET_errNTSystemCallFailed = @as(i32, -334); pub const JET_errBadParentPageLink = @as(i32, -338); pub const JET_errSPAvailExtCacheOutOfSync = @as(i32, -340); pub const JET_errSPAvailExtCorrupted = @as(i32, -341); pub const JET_errSPAvailExtCacheOutOfMemory = @as(i32, -342); pub const JET_errSPOwnExtCorrupted = @as(i32, -343); pub const JET_errDbTimeCorrupted = @as(i32, -344); pub const JET_wrnUniqueKey = @as(u32, 345); pub const JET_errKeyTruncated = @as(i32, -346); pub const JET_errDatabaseLeakInSpace = @as(i32, -348); pub const JET_errBadEmptyPage = @as(i32, -351); pub const JET_errBadLineCount = @as(i32, -354); pub const JET_errPageTagCorrupted = @as(i32, -357); pub const JET_errNodeCorrupted = @as(i32, -358); pub const JET_wrnSeparateLongValue = @as(u32, 406); pub const JET_errKeyTooBig = @as(i32, -408); pub const JET_errCannotSeparateIntrinsicLV = @as(i32, -416); pub const JET_errSeparatedLongValue = @as(i32, -421); pub const JET_errMustBeSeparateLongValue = @as(i32, -423); pub const JET_errInvalidPreread = @as(i32, -424); pub const JET_errInvalidLoggedOperation = @as(i32, -500); pub const JET_errLogFileCorrupt = @as(i32, -501); pub const JET_errNoBackupDirectory = @as(i32, -503); pub const JET_errBackupDirectoryNotEmpty = @as(i32, -504); pub const JET_errBackupInProgress = @as(i32, -505); pub const JET_errRestoreInProgress = @as(i32, -506); pub const JET_errMissingPreviousLogFile = @as(i32, -509); pub const JET_errLogWriteFail = @as(i32, -510); pub const JET_errLogDisabledDueToRecoveryFailure = @as(i32, -511); pub const JET_errCannotLogDuringRecoveryRedo = @as(i32, -512); pub const JET_errLogGenerationMismatch = @as(i32, -513); pub const JET_errBadLogVersion = @as(i32, -514); pub const JET_errInvalidLogSequence = @as(i32, -515); pub const JET_errLoggingDisabled = @as(i32, -516); pub const JET_errLogBufferTooSmall = @as(i32, -517); pub const JET_errLogSequenceEnd = @as(i32, -519); pub const JET_errNoBackup = @as(i32, -520); pub const JET_errInvalidBackupSequence = @as(i32, -521); pub const JET_errBackupNotAllowedYet = @as(i32, -523); pub const JET_errDeleteBackupFileFail = @as(i32, -524); pub const JET_errMakeBackupDirectoryFail = @as(i32, -525); pub const JET_errInvalidBackup = @as(i32, -526); pub const JET_errRecoveredWithErrors = @as(i32, -527); pub const JET_errMissingLogFile = @as(i32, -528); pub const JET_errLogDiskFull = @as(i32, -529); pub const JET_errBadLogSignature = @as(i32, -530); pub const JET_errBadDbSignature = @as(i32, -531); pub const JET_errBadCheckpointSignature = @as(i32, -532); pub const JET_errCheckpointCorrupt = @as(i32, -533); pub const JET_errMissingPatchPage = @as(i32, -534); pub const JET_errBadPatchPage = @as(i32, -535); pub const JET_errRedoAbruptEnded = @as(i32, -536); pub const JET_errPatchFileMissing = @as(i32, -538); pub const JET_errDatabaseLogSetMismatch = @as(i32, -539); pub const JET_errDatabaseStreamingFileMismatch = @as(i32, -540); pub const JET_errLogFileSizeMismatch = @as(i32, -541); pub const JET_errCheckpointFileNotFound = @as(i32, -542); pub const JET_errRequiredLogFilesMissing = @as(i32, -543); pub const JET_errSoftRecoveryOnBackupDatabase = @as(i32, -544); pub const JET_errLogFileSizeMismatchDatabasesConsistent = @as(i32, -545); pub const JET_errLogSectorSizeMismatch = @as(i32, -546); pub const JET_errLogSectorSizeMismatchDatabasesConsistent = @as(i32, -547); pub const JET_errLogSequenceEndDatabasesConsistent = @as(i32, -548); pub const JET_errStreamingDataNotLogged = @as(i32, -549); pub const JET_errDatabaseDirtyShutdown = @as(i32, -550); pub const JET_errDatabaseInconsistent = @as(i32, -550); pub const JET_errConsistentTimeMismatch = @as(i32, -551); pub const JET_errDatabasePatchFileMismatch = @as(i32, -552); pub const JET_errEndingRestoreLogTooLow = @as(i32, -553); pub const JET_errStartingRestoreLogTooHigh = @as(i32, -554); pub const JET_errGivenLogFileHasBadSignature = @as(i32, -555); pub const JET_errGivenLogFileIsNotContiguous = @as(i32, -556); pub const JET_errMissingRestoreLogFiles = @as(i32, -557); pub const JET_wrnExistingLogFileHasBadSignature = @as(u32, 558); pub const JET_wrnExistingLogFileIsNotContiguous = @as(u32, 559); pub const JET_errMissingFullBackup = @as(i32, -560); pub const JET_errBadBackupDatabaseSize = @as(i32, -561); pub const JET_errDatabaseAlreadyUpgraded = @as(i32, -562); pub const JET_errDatabaseIncompleteUpgrade = @as(i32, -563); pub const JET_wrnSkipThisRecord = @as(u32, 564); pub const JET_errMissingCurrentLogFiles = @as(i32, -565); pub const JET_errDbTimeTooOld = @as(i32, -566); pub const JET_errDbTimeTooNew = @as(i32, -567); pub const JET_errMissingFileToBackup = @as(i32, -569); pub const JET_errLogTornWriteDuringHardRestore = @as(i32, -570); pub const JET_errLogTornWriteDuringHardRecovery = @as(i32, -571); pub const JET_errLogCorruptDuringHardRestore = @as(i32, -573); pub const JET_errLogCorruptDuringHardRecovery = @as(i32, -574); pub const JET_errMustDisableLoggingForDbUpgrade = @as(i32, -575); pub const JET_errBadRestoreTargetInstance = @as(i32, -577); pub const JET_wrnTargetInstanceRunning = @as(u32, 578); pub const JET_errRecoveredWithoutUndo = @as(i32, -579); pub const JET_errDatabasesNotFromSameSnapshot = @as(i32, -580); pub const JET_errSoftRecoveryOnSnapshot = @as(i32, -581); pub const JET_errCommittedLogFilesMissing = @as(i32, -582); pub const JET_errSectorSizeNotSupported = @as(i32, -583); pub const JET_errRecoveredWithoutUndoDatabasesConsistent = @as(i32, -584); pub const JET_wrnCommittedLogFilesLost = @as(u32, 585); pub const JET_errCommittedLogFileCorrupt = @as(i32, -586); pub const JET_wrnCommittedLogFilesRemoved = @as(u32, 587); pub const JET_wrnFinishWithUndo = @as(u32, 588); pub const JET_errLogSequenceChecksumMismatch = @as(i32, -590); pub const JET_wrnDatabaseRepaired = @as(u32, 595); pub const JET_errPageInitializedMismatch = @as(i32, -596); pub const JET_errUnicodeTranslationBufferTooSmall = @as(i32, -601); pub const JET_errUnicodeTranslationFail = @as(i32, -602); pub const JET_errUnicodeNormalizationNotSupported = @as(i32, -603); pub const JET_errUnicodeLanguageValidationFailure = @as(i32, -604); pub const JET_errExistingLogFileHasBadSignature = @as(i32, -610); pub const JET_errExistingLogFileIsNotContiguous = @as(i32, -611); pub const JET_errLogReadVerifyFailure = @as(i32, -612); pub const JET_errCheckpointDepthTooDeep = @as(i32, -614); pub const JET_errRestoreOfNonBackupDatabase = @as(i32, -615); pub const JET_errLogFileNotCopied = @as(i32, -616); pub const JET_errTransactionTooLong = @as(i32, -618); pub const JET_errEngineFormatVersionNoLongerSupportedTooLow = @as(i32, -619); pub const JET_errEngineFormatVersionNotYetImplementedTooHigh = @as(i32, -620); pub const JET_errEngineFormatVersionParamTooLowForRequestedFeature = @as(i32, -621); pub const JET_errEngineFormatVersionSpecifiedTooLowForLogVersion = @as(i32, -622); pub const JET_errEngineFormatVersionSpecifiedTooLowForDatabaseVersion = @as(i32, -623); pub const JET_errBackupAbortByServer = @as(i32, -801); pub const JET_errInvalidGrbit = @as(i32, -900); pub const JET_errTermInProgress = @as(i32, -1000); pub const JET_errFeatureNotAvailable = @as(i32, -1001); pub const JET_errInvalidName = @as(i32, -1002); pub const JET_errInvalidParameter = @as(i32, -1003); pub const JET_wrnColumnNull = @as(u32, 1004); pub const JET_wrnBufferTruncated = @as(u32, 1006); pub const JET_wrnDatabaseAttached = @as(u32, 1007); pub const JET_errDatabaseFileReadOnly = @as(i32, -1008); pub const JET_wrnSortOverflow = @as(u32, 1009); pub const JET_errInvalidDatabaseId = @as(i32, -1010); pub const JET_errOutOfMemory = @as(i32, -1011); pub const JET_errOutOfDatabaseSpace = @as(i32, -1012); pub const JET_errOutOfCursors = @as(i32, -1013); pub const JET_errOutOfBuffers = @as(i32, -1014); pub const JET_errTooManyIndexes = @as(i32, -1015); pub const JET_errTooManyKeys = @as(i32, -1016); pub const JET_errRecordDeleted = @as(i32, -1017); pub const JET_errReadVerifyFailure = @as(i32, -1018); pub const JET_errPageNotInitialized = @as(i32, -1019); pub const JET_errOutOfFileHandles = @as(i32, -1020); pub const JET_errDiskReadVerificationFailure = @as(i32, -1021); pub const JET_errDiskIO = @as(i32, -1022); pub const JET_errInvalidPath = @as(i32, -1023); pub const JET_errInvalidSystemPath = @as(i32, -1024); pub const JET_errInvalidLogDirectory = @as(i32, -1025); pub const JET_errRecordTooBig = @as(i32, -1026); pub const JET_errTooManyOpenDatabases = @as(i32, -1027); pub const JET_errInvalidDatabase = @as(i32, -1028); pub const JET_errNotInitialized = @as(i32, -1029); pub const JET_errAlreadyInitialized = @as(i32, -1030); pub const JET_errInitInProgress = @as(i32, -1031); pub const JET_errFileAccessDenied = @as(i32, -1032); pub const JET_errBufferTooSmall = @as(i32, -1038); pub const JET_wrnSeekNotEqual = @as(u32, 1039); pub const JET_errTooManyColumns = @as(i32, -1040); pub const JET_errContainerNotEmpty = @as(i32, -1043); pub const JET_errInvalidFilename = @as(i32, -1044); pub const JET_errInvalidBookmark = @as(i32, -1045); pub const JET_errColumnInUse = @as(i32, -1046); pub const JET_errInvalidBufferSize = @as(i32, -1047); pub const JET_errColumnNotUpdatable = @as(i32, -1048); pub const JET_errIndexInUse = @as(i32, -1051); pub const JET_errLinkNotSupported = @as(i32, -1052); pub const JET_errNullKeyDisallowed = @as(i32, -1053); pub const JET_errNotInTransaction = @as(i32, -1054); pub const JET_wrnNoErrorInfo = @as(u32, 1055); pub const JET_errMustRollback = @as(i32, -1057); pub const JET_wrnNoIdleActivity = @as(u32, 1058); pub const JET_errTooManyActiveUsers = @as(i32, -1059); pub const JET_errInvalidCountry = @as(i32, -1061); pub const JET_errInvalidLanguageId = @as(i32, -1062); pub const JET_errInvalidCodePage = @as(i32, -1063); pub const JET_errInvalidLCMapStringFlags = @as(i32, -1064); pub const JET_errVersionStoreEntryTooBig = @as(i32, -1065); pub const JET_errVersionStoreOutOfMemoryAndCleanupTimedOut = @as(i32, -1066); pub const JET_wrnNoWriteLock = @as(u32, 1067); pub const JET_wrnColumnSetNull = @as(u32, 1068); pub const JET_errVersionStoreOutOfMemory = @as(i32, -1069); pub const JET_errCannotIndex = @as(i32, -1071); pub const JET_errRecordNotDeleted = @as(i32, -1072); pub const JET_errTooManyMempoolEntries = @as(i32, -1073); pub const JET_errOutOfObjectIDs = @as(i32, -1074); pub const JET_errOutOfLongValueIDs = @as(i32, -1075); pub const JET_errOutOfAutoincrementValues = @as(i32, -1076); pub const JET_errOutOfDbtimeValues = @as(i32, -1077); pub const JET_errOutOfSequentialIndexValues = @as(i32, -1078); pub const JET_errRunningInOneInstanceMode = @as(i32, -1080); pub const JET_errRunningInMultiInstanceMode = @as(i32, -1081); pub const JET_errSystemParamsAlreadySet = @as(i32, -1082); pub const JET_errSystemPathInUse = @as(i32, -1083); pub const JET_errLogFilePathInUse = @as(i32, -1084); pub const JET_errTempPathInUse = @as(i32, -1085); pub const JET_errInstanceNameInUse = @as(i32, -1086); pub const JET_errSystemParameterConflict = @as(i32, -1087); pub const JET_errInstanceUnavailable = @as(i32, -1090); pub const JET_errDatabaseUnavailable = @as(i32, -1091); pub const JET_errInstanceUnavailableDueToFatalLogDiskFull = @as(i32, -1092); pub const JET_errInvalidSesparamId = @as(i32, -1093); pub const JET_errTooManyRecords = @as(i32, -1094); pub const JET_errInvalidDbparamId = @as(i32, -1095); pub const JET_errOutOfSessions = @as(i32, -1101); pub const JET_errWriteConflict = @as(i32, -1102); pub const JET_errTransTooDeep = @as(i32, -1103); pub const JET_errInvalidSesid = @as(i32, -1104); pub const JET_errWriteConflictPrimaryIndex = @as(i32, -1105); pub const JET_errInTransaction = @as(i32, -1108); pub const JET_errRollbackRequired = @as(i32, -1109); pub const JET_errTransReadOnly = @as(i32, -1110); pub const JET_errSessionWriteConflict = @as(i32, -1111); pub const JET_errRecordTooBigForBackwardCompatibility = @as(i32, -1112); pub const JET_errCannotMaterializeForwardOnlySort = @as(i32, -1113); pub const JET_errSesidTableIdMismatch = @as(i32, -1114); pub const JET_errInvalidInstance = @as(i32, -1115); pub const JET_errDirtyShutdown = @as(i32, -1116); pub const JET_errReadPgnoVerifyFailure = @as(i32, -1118); pub const JET_errReadLostFlushVerifyFailure = @as(i32, -1119); pub const JET_errFileSystemCorruption = @as(i32, -1121); pub const JET_wrnShrinkNotPossible = @as(u32, 1122); pub const JET_errRecoveryVerifyFailure = @as(i32, -1123); pub const JET_errFilteredMoveNotSupported = @as(i32, -1124); pub const JET_errDatabaseDuplicate = @as(i32, -1201); pub const JET_errDatabaseInUse = @as(i32, -1202); pub const JET_errDatabaseNotFound = @as(i32, -1203); pub const JET_errDatabaseInvalidName = @as(i32, -1204); pub const JET_errDatabaseInvalidPages = @as(i32, -1205); pub const JET_errDatabaseCorrupted = @as(i32, -1206); pub const JET_errDatabaseLocked = @as(i32, -1207); pub const JET_errCannotDisableVersioning = @as(i32, -1208); pub const JET_errInvalidDatabaseVersion = @as(i32, -1209); pub const JET_errDatabase200Format = @as(i32, -1210); pub const JET_errDatabase400Format = @as(i32, -1211); pub const JET_errDatabase500Format = @as(i32, -1212); pub const JET_errPageSizeMismatch = @as(i32, -1213); pub const JET_errTooManyInstances = @as(i32, -1214); pub const JET_errDatabaseSharingViolation = @as(i32, -1215); pub const JET_errAttachedDatabaseMismatch = @as(i32, -1216); pub const JET_errDatabaseInvalidPath = @as(i32, -1217); pub const JET_errDatabaseIdInUse = @as(i32, -1218); pub const JET_errForceDetachNotAllowed = @as(i32, -1219); pub const JET_errCatalogCorrupted = @as(i32, -1220); pub const JET_errPartiallyAttachedDB = @as(i32, -1221); pub const JET_errDatabaseSignInUse = @as(i32, -1222); pub const JET_errDatabaseCorruptedNoRepair = @as(i32, -1224); pub const JET_errInvalidCreateDbVersion = @as(i32, -1225); pub const JET_errDatabaseNotReady = @as(i32, -1230); pub const JET_errDatabaseAttachedForRecovery = @as(i32, -1231); pub const JET_errTransactionsNotReadyDuringRecovery = @as(i32, -1232); pub const JET_wrnTableEmpty = @as(u32, 1301); pub const JET_errTableLocked = @as(i32, -1302); pub const JET_errTableDuplicate = @as(i32, -1303); pub const JET_errTableInUse = @as(i32, -1304); pub const JET_errObjectNotFound = @as(i32, -1305); pub const JET_errDensityInvalid = @as(i32, -1307); pub const JET_errTableNotEmpty = @as(i32, -1308); pub const JET_errInvalidTableId = @as(i32, -1310); pub const JET_errTooManyOpenTables = @as(i32, -1311); pub const JET_errIllegalOperation = @as(i32, -1312); pub const JET_errTooManyOpenTablesAndCleanupTimedOut = @as(i32, -1313); pub const JET_errObjectDuplicate = @as(i32, -1314); pub const JET_errInvalidObject = @as(i32, -1316); pub const JET_errCannotDeleteTempTable = @as(i32, -1317); pub const JET_errCannotDeleteSystemTable = @as(i32, -1318); pub const JET_errCannotDeleteTemplateTable = @as(i32, -1319); pub const JET_errExclusiveTableLockRequired = @as(i32, -1322); pub const JET_errFixedDDL = @as(i32, -1323); pub const JET_errFixedInheritedDDL = @as(i32, -1324); pub const JET_errCannotNestDDL = @as(i32, -1325); pub const JET_errDDLNotInheritable = @as(i32, -1326); pub const JET_wrnTableInUseBySystem = @as(u32, 1327); pub const JET_errInvalidSettings = @as(i32, -1328); pub const JET_errClientRequestToStopJetService = @as(i32, -1329); pub const JET_errCannotAddFixedVarColumnToDerivedTable = @as(i32, -1330); pub const JET_errIndexCantBuild = @as(i32, -1401); pub const JET_errIndexHasPrimary = @as(i32, -1402); pub const JET_errIndexDuplicate = @as(i32, -1403); pub const JET_errIndexNotFound = @as(i32, -1404); pub const JET_errIndexMustStay = @as(i32, -1405); pub const JET_errIndexInvalidDef = @as(i32, -1406); pub const JET_errInvalidCreateIndex = @as(i32, -1409); pub const JET_errTooManyOpenIndexes = @as(i32, -1410); pub const JET_errMultiValuedIndexViolation = @as(i32, -1411); pub const JET_errIndexBuildCorrupted = @as(i32, -1412); pub const JET_errPrimaryIndexCorrupted = @as(i32, -1413); pub const JET_errSecondaryIndexCorrupted = @as(i32, -1414); pub const JET_wrnCorruptIndexDeleted = @as(u32, 1415); pub const JET_errInvalidIndexId = @as(i32, -1416); pub const JET_wrnPrimaryIndexOutOfDate = @as(u32, 1417); pub const JET_wrnSecondaryIndexOutOfDate = @as(u32, 1418); pub const JET_errIndexTuplesSecondaryIndexOnly = @as(i32, -1430); pub const JET_errIndexTuplesTooManyColumns = @as(i32, -1431); pub const JET_errIndexTuplesOneColumnOnly = @as(i32, -1431); pub const JET_errIndexTuplesNonUniqueOnly = @as(i32, -1432); pub const JET_errIndexTuplesTextBinaryColumnsOnly = @as(i32, -1433); pub const JET_errIndexTuplesTextColumnsOnly = @as(i32, -1433); pub const JET_errIndexTuplesVarSegMacNotAllowed = @as(i32, -1434); pub const JET_errIndexTuplesInvalidLimits = @as(i32, -1435); pub const JET_errIndexTuplesCannotRetrieveFromIndex = @as(i32, -1436); pub const JET_errIndexTuplesKeyTooSmall = @as(i32, -1437); pub const JET_errInvalidLVChunkSize = @as(i32, -1438); pub const JET_errColumnCannotBeEncrypted = @as(i32, -1439); pub const JET_errCannotIndexOnEncryptedColumn = @as(i32, -1440); pub const JET_errColumnLong = @as(i32, -1501); pub const JET_errColumnNoChunk = @as(i32, -1502); pub const JET_errColumnDoesNotFit = @as(i32, -1503); pub const JET_errNullInvalid = @as(i32, -1504); pub const JET_errColumnIndexed = @as(i32, -1505); pub const JET_errColumnTooBig = @as(i32, -1506); pub const JET_errColumnNotFound = @as(i32, -1507); pub const JET_errColumnDuplicate = @as(i32, -1508); pub const JET_errMultiValuedColumnMustBeTagged = @as(i32, -1509); pub const JET_errColumnRedundant = @as(i32, -1510); pub const JET_errInvalidColumnType = @as(i32, -1511); pub const JET_wrnColumnMaxTruncated = @as(u32, 1512); pub const JET_errTaggedNotNULL = @as(i32, -1514); pub const JET_errNoCurrentIndex = @as(i32, -1515); pub const JET_errKeyIsMade = @as(i32, -1516); pub const JET_errBadColumnId = @as(i32, -1517); pub const JET_errBadItagSequence = @as(i32, -1518); pub const JET_errColumnInRelationship = @as(i32, -1519); pub const JET_wrnCopyLongValue = @as(u32, 1520); pub const JET_errCannotBeTagged = @as(i32, -1521); pub const JET_errDefaultValueTooBig = @as(i32, -1524); pub const JET_errMultiValuedDuplicate = @as(i32, -1525); pub const JET_errLVCorrupted = @as(i32, -1526); pub const JET_errMultiValuedDuplicateAfterTruncation = @as(i32, -1528); pub const JET_errDerivedColumnCorruption = @as(i32, -1529); pub const JET_errInvalidPlaceholderColumn = @as(i32, -1530); pub const JET_wrnColumnSkipped = @as(u32, 1531); pub const JET_wrnColumnNotLocal = @as(u32, 1532); pub const JET_wrnColumnMoreTags = @as(u32, 1533); pub const JET_wrnColumnTruncated = @as(u32, 1534); pub const JET_wrnColumnPresent = @as(u32, 1535); pub const JET_wrnColumnSingleValue = @as(u32, 1536); pub const JET_wrnColumnDefault = @as(u32, 1537); pub const JET_errColumnCannotBeCompressed = @as(i32, -1538); pub const JET_wrnColumnNotInRecord = @as(u32, 1539); pub const JET_errColumnNoEncryptionKey = @as(i32, -1540); pub const JET_wrnColumnReference = @as(u32, 1541); pub const JET_errRecordNotFound = @as(i32, -1601); pub const JET_errRecordNoCopy = @as(i32, -1602); pub const JET_errNoCurrentRecord = @as(i32, -1603); pub const JET_errRecordPrimaryChanged = @as(i32, -1604); pub const JET_errKeyDuplicate = @as(i32, -1605); pub const JET_errAlreadyPrepared = @as(i32, -1607); pub const JET_errKeyNotMade = @as(i32, -1608); pub const JET_errUpdateNotPrepared = @as(i32, -1609); pub const JET_wrnDataHasChanged = @as(u32, 1610); pub const JET_errDataHasChanged = @as(i32, -1611); pub const JET_wrnKeyChanged = @as(u32, 1618); pub const JET_errLanguageNotSupported = @as(i32, -1619); pub const JET_errDecompressionFailed = @as(i32, -1620); pub const JET_errUpdateMustVersion = @as(i32, -1621); pub const JET_errDecryptionFailed = @as(i32, -1622); pub const JET_errEncryptionBadItag = @as(i32, -1623); pub const JET_errTooManySorts = @as(i32, -1701); pub const JET_errInvalidOnSort = @as(i32, -1702); pub const JET_errTempFileOpenError = @as(i32, -1803); pub const JET_errTooManyAttachedDatabases = @as(i32, -1805); pub const JET_errDiskFull = @as(i32, -1808); pub const JET_errPermissionDenied = @as(i32, -1809); pub const JET_errFileNotFound = @as(i32, -1811); pub const JET_errFileInvalidType = @as(i32, -1812); pub const JET_wrnFileOpenReadOnly = @as(u32, 1813); pub const JET_errFileAlreadyExists = @as(i32, -1814); pub const JET_errAfterInitialization = @as(i32, -1850); pub const JET_errLogCorrupted = @as(i32, -1852); pub const JET_errInvalidOperation = @as(i32, -1906); pub const JET_errAccessDenied = @as(i32, -1907); pub const JET_wrnIdleFull = @as(u32, 1908); pub const JET_errTooManySplits = @as(i32, -1909); pub const JET_errSessionSharingViolation = @as(i32, -1910); pub const JET_errEntryPointNotFound = @as(i32, -1911); pub const JET_errSessionContextAlreadySet = @as(i32, -1912); pub const JET_errSessionContextNotSetByThisThread = @as(i32, -1913); pub const JET_errSessionInUse = @as(i32, -1914); pub const JET_errRecordFormatConversionFailed = @as(i32, -1915); pub const JET_errOneDatabasePerSession = @as(i32, -1916); pub const JET_errRollbackError = @as(i32, -1917); pub const JET_errFlushMapVersionUnsupported = @as(i32, -1918); pub const JET_errFlushMapDatabaseMismatch = @as(i32, -1919); pub const JET_errFlushMapUnrecoverable = @as(i32, -1920); pub const JET_wrnDefragAlreadyRunning = @as(u32, 2000); pub const JET_wrnDefragNotRunning = @as(u32, 2001); pub const JET_errDatabaseAlreadyRunningMaintenance = @as(i32, -2004); pub const JET_wrnCallbackNotRegistered = @as(u32, 2100); pub const JET_errCallbackFailed = @as(i32, -2101); pub const JET_errCallbackNotResolved = @as(i32, -2102); pub const JET_errSpaceHintsInvalid = @as(i32, -2103); pub const JET_errOSSnapshotInvalidSequence = @as(i32, -2401); pub const JET_errOSSnapshotTimeOut = @as(i32, -2402); pub const JET_errOSSnapshotNotAllowed = @as(i32, -2403); pub const JET_errOSSnapshotInvalidSnapId = @as(i32, -2404); pub const JET_errLSCallbackNotSpecified = @as(i32, -3000); pub const JET_errLSAlreadySet = @as(i32, -3001); pub const JET_errLSNotSet = @as(i32, -3002); pub const JET_errFileIOSparse = @as(i32, -4000); pub const JET_errFileIOBeyondEOF = @as(i32, -4001); pub const JET_errFileIOAbort = @as(i32, -4002); pub const JET_errFileIORetry = @as(i32, -4003); pub const JET_errFileIOFail = @as(i32, -4004); pub const JET_errFileCompressed = @as(i32, -4005); pub const JET_BASE_NAME_LENGTH = @as(u32, 3); pub const JET_bitDumpMinimum = @as(u32, 1); pub const JET_bitDumpMaximum = @as(u32, 2); pub const JET_bitDumpCacheMinimum = @as(u32, 4); pub const JET_bitDumpCacheMaximum = @as(u32, 8); pub const JET_bitDumpCacheIncludeDirtyPages = @as(u32, 16); pub const JET_bitDumpCacheIncludeCachedPages = @as(u32, 32); pub const JET_bitDumpCacheIncludeCorruptedPages = @as(u32, 64); pub const JET_bitDumpCacheNoDecommit = @as(u32, 128); //-------------------------------------------------------------------------------- // Section: Types (95) //-------------------------------------------------------------------------------- pub const JET_OSSNAPID = usize; pub const JET_LS = usize; pub const JET_PFNSTATUS = fn( sesid: ?JET_SESID, snp: u32, snt: u32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const JET_RSTMAP_A = extern struct { szDatabaseName: ?PSTR, szNewDatabaseName: ?PSTR, }; pub const JET_RSTMAP_W = extern struct { szDatabaseName: ?PWSTR, szNewDatabaseName: ?PWSTR, }; pub const CONVERT_A = extern struct { szOldDll: ?PSTR, Anonymous: extern union { fFlags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const CONVERT_W = extern struct { szOldDll: ?PWSTR, Anonymous: extern union { fFlags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const JET_CALLBACK = fn( sesid: ?JET_SESID, dbid: u32, tableid: JET_TABLEID, cbtyp: u32, pvArg1: ?*anyopaque, pvArg2: ?*anyopaque, pvContext: ?*anyopaque, ulUnused: JET_API_PTR, ) callconv(@import("std").os.windows.WINAPI) i32; pub const JET_SNPROG = extern struct { cbStruct: u32, cunitDone: u32, cunitTotal: u32, }; pub const JET_DBINFOUPGRADE = extern struct { cbStruct: u32, cbFilesizeLow: u32, cbFilesizeHigh: u32, cbFreeSpaceRequiredLow: u32, cbFreeSpaceRequiredHigh: u32, csecToUpgrade: u32, Anonymous: extern union { ulFlags: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const JET_OBJECTLIST = extern struct { cbStruct: u32, tableid: JET_TABLEID, cRecord: u32, columnidcontainername: u32, columnidobjectname: u32, columnidobjtyp: u32, columniddtCreate: u32, columniddtUpdate: u32, columnidgrbit: u32, columnidflags: u32, columnidcRecord: u32, columnidcPage: u32, }; pub const JET_COLUMNLIST = extern struct { cbStruct: u32, tableid: JET_TABLEID, cRecord: u32, columnidPresentationOrder: u32, columnidcolumnname: u32, columnidcolumnid: u32, columnidcoltyp: u32, columnidCountry: u32, columnidLangid: u32, columnidCp: u32, columnidCollate: u32, columnidcbMax: u32, columnidgrbit: u32, columnidDefault: u32, columnidBaseTableName: u32, columnidBaseColumnName: u32, columnidDefinitionName: u32, }; pub const JET_COLUMNDEF = extern struct { cbStruct: u32, columnid: u32, coltyp: u32, wCountry: u16, langid: u16, cp: u16, wCollate: u16, cbMax: u32, grbit: u32, }; pub const JET_COLUMNBASE_A = extern struct { cbStruct: u32, columnid: u32, coltyp: u32, wCountry: u16, langid: u16, cp: u16, wFiller: u16, cbMax: u32, grbit: u32, szBaseTableName: [256]CHAR, szBaseColumnName: [256]CHAR, }; pub const JET_COLUMNBASE_W = extern struct { cbStruct: u32, columnid: u32, coltyp: u32, wCountry: u16, langid: u16, cp: u16, wFiller: u16, cbMax: u32, grbit: u32, szBaseTableName: [256]u16, szBaseColumnName: [256]u16, }; pub const JET_INDEXLIST = extern struct { cbStruct: u32, tableid: JET_TABLEID, cRecord: u32, columnidindexname: u32, columnidgrbitIndex: u32, columnidcKey: u32, columnidcEntry: u32, columnidcPage: u32, columnidcColumn: u32, columnidiColumn: u32, columnidcolumnid: u32, columnidcoltyp: u32, columnidCountry: u32, columnidLangid: u32, columnidCp: u32, columnidCollate: u32, columnidgrbitColumn: u32, columnidcolumnname: u32, columnidLCMapFlags: u32, }; pub const JET_COLUMNCREATE_A = extern struct { cbStruct: u32, szColumnName: ?PSTR, coltyp: u32, cbMax: u32, grbit: u32, pvDefault: ?*anyopaque, cbDefault: u32, cp: u32, columnid: u32, err: i32, }; pub const JET_COLUMNCREATE_W = extern struct { cbStruct: u32, szColumnName: ?PWSTR, coltyp: u32, cbMax: u32, grbit: u32, pvDefault: ?*anyopaque, cbDefault: u32, cp: u32, columnid: u32, err: i32, }; pub const JET_USERDEFINEDDEFAULT_A = extern struct { szCallback: ?PSTR, pbUserData: ?*u8, cbUserData: u32, szDependantColumns: ?PSTR, }; pub const JET_USERDEFINEDDEFAULT_W = extern struct { szCallback: ?PWSTR, pbUserData: ?*u8, cbUserData: u32, szDependantColumns: ?PWSTR, }; pub const JET_CONDITIONALCOLUMN_A = extern struct { cbStruct: u32, szColumnName: ?PSTR, grbit: u32, }; pub const JET_CONDITIONALCOLUMN_W = extern struct { cbStruct: u32, szColumnName: ?PWSTR, grbit: u32, }; pub const JET_UNICODEINDEX = extern struct { lcid: u32, dwMapFlags: u32, }; pub const JET_UNICODEINDEX2 = extern struct { szLocaleName: ?PWSTR, dwMapFlags: u32, }; pub const JET_TUPLELIMITS = extern struct { chLengthMin: u32, chLengthMax: u32, chToIndexMax: u32, cchIncrement: u32, ichStart: u32, }; pub const JET_SPACEHINTS = extern struct { cbStruct: u32, ulInitialDensity: u32, cbInitial: u32, grbit: u32, ulMaintDensity: u32, ulGrowth: u32, cbMinExtent: u32, cbMaxExtent: u32, }; pub const JET_INDEXCREATE_A = extern struct { cbStruct: u32, szIndexName: ?PSTR, szKey: ?PSTR, cbKey: u32, grbit: u32, ulDensity: u32, Anonymous1: extern union { lcid: u32, pidxunicode: ?*JET_UNICODEINDEX, }, Anonymous2: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_A, cConditionalColumn: u32, err: i32, cbKeyMost: u32, }; pub const JET_INDEXCREATE_W = extern struct { cbStruct: u32, szIndexName: ?PWSTR, szKey: ?PWSTR, cbKey: u32, grbit: u32, ulDensity: u32, Anonymous1: extern union { lcid: u32, pidxunicode: ?*JET_UNICODEINDEX, }, Anonymous2: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_W, cConditionalColumn: u32, err: i32, cbKeyMost: u32, }; pub const JET_INDEXCREATE2_A = extern struct { cbStruct: u32, szIndexName: ?PSTR, szKey: ?PSTR, cbKey: u32, grbit: u32, ulDensity: u32, Anonymous1: extern union { lcid: u32, pidxunicode: ?*JET_UNICODEINDEX, }, Anonymous2: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_A, cConditionalColumn: u32, err: i32, cbKeyMost: u32, pSpacehints: ?*JET_SPACEHINTS, }; pub const JET_INDEXCREATE2_W = extern struct { cbStruct: u32, szIndexName: ?PWSTR, szKey: ?PWSTR, cbKey: u32, grbit: u32, ulDensity: u32, Anonymous1: extern union { lcid: u32, pidxunicode: ?*JET_UNICODEINDEX, }, Anonymous2: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_W, cConditionalColumn: u32, err: i32, cbKeyMost: u32, pSpacehints: ?*JET_SPACEHINTS, }; pub const JET_INDEXCREATE3_A = extern struct { cbStruct: u32, szIndexName: ?PSTR, szKey: ?PSTR, cbKey: u32, grbit: u32, ulDensity: u32, pidxunicode: ?*JET_UNICODEINDEX2, Anonymous: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_A, cConditionalColumn: u32, err: i32, cbKeyMost: u32, pSpacehints: ?*JET_SPACEHINTS, }; pub const JET_INDEXCREATE3_W = extern struct { cbStruct: u32, szIndexName: ?PWSTR, szKey: ?PWSTR, cbKey: u32, grbit: u32, ulDensity: u32, pidxunicode: ?*JET_UNICODEINDEX2, Anonymous: extern union { cbVarSegMac: u32, ptuplelimits: ?*JET_TUPLELIMITS, }, rgconditionalcolumn: ?*JET_CONDITIONALCOLUMN_W, cConditionalColumn: u32, err: i32, cbKeyMost: u32, pSpacehints: ?*JET_SPACEHINTS, }; pub const JET_TABLECREATE_A = extern struct { cbStruct: u32, szTableName: ?PSTR, szTemplateTableName: ?PSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_A, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE_A, cIndexes: u32, grbit: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE_W = extern struct { cbStruct: u32, szTableName: ?PWSTR, szTemplateTableName: ?PWSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_W, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE_W, cIndexes: u32, grbit: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE2_A = extern struct { cbStruct: u32, szTableName: ?PSTR, szTemplateTableName: ?PSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_A, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE_A, cIndexes: u32, szCallback: ?PSTR, cbtyp: u32, grbit: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE2_W = extern struct { cbStruct: u32, szTableName: ?PWSTR, szTemplateTableName: ?PWSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_W, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE_W, cIndexes: u32, szCallback: ?PWSTR, cbtyp: u32, grbit: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE3_A = extern struct { cbStruct: u32, szTableName: ?PSTR, szTemplateTableName: ?PSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_A, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE2_A, cIndexes: u32, szCallback: ?PSTR, cbtyp: u32, grbit: u32, pSeqSpacehints: ?*JET_SPACEHINTS, pLVSpacehints: ?*JET_SPACEHINTS, cbSeparateLV: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE3_W = extern struct { cbStruct: u32, szTableName: ?PWSTR, szTemplateTableName: ?PWSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_W, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE2_W, cIndexes: u32, szCallback: ?PWSTR, cbtyp: u32, grbit: u32, pSeqSpacehints: ?*JET_SPACEHINTS, pLVSpacehints: ?*JET_SPACEHINTS, cbSeparateLV: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE4_A = extern struct { cbStruct: u32, szTableName: ?PSTR, szTemplateTableName: ?PSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_A, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE3_A, cIndexes: u32, szCallback: ?PSTR, cbtyp: u32, grbit: u32, pSeqSpacehints: ?*JET_SPACEHINTS, pLVSpacehints: ?*JET_SPACEHINTS, cbSeparateLV: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_TABLECREATE4_W = extern struct { cbStruct: u32, szTableName: ?PWSTR, szTemplateTableName: ?PWSTR, ulPages: u32, ulDensity: u32, rgcolumncreate: ?*JET_COLUMNCREATE_W, cColumns: u32, rgindexcreate: ?*JET_INDEXCREATE3_W, cIndexes: u32, szCallback: ?PWSTR, cbtyp: u32, grbit: u32, pSeqSpacehints: ?*JET_SPACEHINTS, pLVSpacehints: ?*JET_SPACEHINTS, cbSeparateLV: u32, tableid: JET_TABLEID, cCreated: u32, }; pub const JET_OPENTEMPORARYTABLE = extern struct { cbStruct: u32, prgcolumndef: ?*const JET_COLUMNDEF, ccolumn: u32, pidxunicode: ?*JET_UNICODEINDEX, grbit: u32, prgcolumnid: ?*u32, cbKeyMost: u32, cbVarSegMac: u32, tableid: JET_TABLEID, }; pub const JET_OPENTEMPORARYTABLE2 = extern struct { cbStruct: u32, prgcolumndef: ?*const JET_COLUMNDEF, ccolumn: u32, pidxunicode: ?*JET_UNICODEINDEX2, grbit: u32, prgcolumnid: ?*u32, cbKeyMost: u32, cbVarSegMac: u32, tableid: JET_TABLEID, }; pub const JET_RETINFO = extern struct { cbStruct: u32, ibLongValue: u32, itagSequence: u32, columnidNextTagged: u32, }; pub const JET_SETINFO = extern struct { cbStruct: u32, ibLongValue: u32, itagSequence: u32, }; pub const JET_RECPOS = extern struct { cbStruct: u32, centriesLT: u32, centriesInRange: u32, centriesTotal: u32, }; pub const JET_RECORDLIST = extern struct { cbStruct: u32, tableid: JET_TABLEID, cRecord: u32, columnidBookmark: u32, }; pub const JET_INDEXRANGE = extern struct { cbStruct: u32, tableid: JET_TABLEID, grbit: u32, }; pub const JET_RELOP = enum(i32) { Equals = 0, PrefixEquals = 1, NotEquals = 2, LessThanOrEqual = 3, LessThan = 4, GreaterThanOrEqual = 5, GreaterThan = 6, BitmaskEqualsZero = 7, BitmaskNotEqualsZero = 8, }; pub const JET_relopEquals = JET_RELOP.Equals; pub const JET_relopPrefixEquals = JET_RELOP.PrefixEquals; pub const JET_relopNotEquals = JET_RELOP.NotEquals; pub const JET_relopLessThanOrEqual = JET_RELOP.LessThanOrEqual; pub const JET_relopLessThan = JET_RELOP.LessThan; pub const JET_relopGreaterThanOrEqual = JET_RELOP.GreaterThanOrEqual; pub const JET_relopGreaterThan = JET_RELOP.GreaterThan; pub const JET_relopBitmaskEqualsZero = JET_RELOP.BitmaskEqualsZero; pub const JET_relopBitmaskNotEqualsZero = JET_RELOP.BitmaskNotEqualsZero; pub const JET_INDEX_COLUMN = extern struct { columnid: u32, relop: JET_RELOP, pv: ?*anyopaque, cb: u32, grbit: u32, }; pub const JET_INDEX_RANGE = extern struct { rgStartColumns: ?*JET_INDEX_COLUMN, cStartColumns: u32, rgEndColumns: ?*JET_INDEX_COLUMN, cEndColumns: u32, }; pub const JET_LOGTIME = extern struct { bSeconds: CHAR, bMinutes: CHAR, bHours: CHAR, bDay: CHAR, bMonth: CHAR, bYear: CHAR, Anonymous1: extern union { bFiller1: CHAR, Anonymous: extern struct { _bitfield: u8, }, }, Anonymous2: extern union { bFiller2: CHAR, Anonymous: extern struct { _bitfield: u8, }, }, }; pub const JET_BKLOGTIME = extern struct { bSeconds: CHAR, bMinutes: CHAR, bHours: CHAR, bDay: CHAR, bMonth: CHAR, bYear: CHAR, Anonymous1: extern union { bFiller1: CHAR, Anonymous: extern struct { _bitfield: u8, }, }, Anonymous2: extern union { bFiller2: CHAR, Anonymous: extern struct { _bitfield: u8, }, }, }; pub const JET_LGPOS = packed struct { ib: u16, isec: u16, lGeneration: i32, }; pub const JET_SIGNATURE = packed struct { ulRandom: u32, logtimeCreate: JET_LOGTIME, szComputerName: [16]CHAR, }; pub const JET_BKINFO = packed struct { lgposMark: JET_LGPOS, Anonymous: extern union { logtimeMark: JET_LOGTIME, bklogtimeMark: JET_BKLOGTIME, }, genLow: u32, genHigh: u32, }; pub const JET_DBINFOMISC = extern struct { ulVersion: u32, ulUpdate: u32, signDb: JET_SIGNATURE, dbstate: u32, lgposConsistent: JET_LGPOS, logtimeConsistent: JET_LOGTIME, logtimeAttach: JET_LOGTIME, lgposAttach: JET_LGPOS, logtimeDetach: JET_LOGTIME, lgposDetach: JET_LGPOS, signLog: JET_SIGNATURE, bkinfoFullPrev: JET_BKINFO, bkinfoIncPrev: JET_BKINFO, bkinfoFullCur: JET_BKINFO, fShadowingDisabled: u32, fUpgradeDb: u32, dwMajorVersion: u32, dwMinorVersion: u32, dwBuildNumber: u32, lSPNumber: i32, cbPageSize: u32, }; pub const JET_DBINFOMISC2 = extern struct { ulVersion: u32, ulUpdate: u32, signDb: JET_SIGNATURE, dbstate: u32, lgposConsistent: JET_LGPOS, logtimeConsistent: JET_LOGTIME, logtimeAttach: JET_LOGTIME, lgposAttach: JET_LGPOS, logtimeDetach: JET_LOGTIME, lgposDetach: JET_LGPOS, signLog: JET_SIGNATURE, bkinfoFullPrev: JET_BKINFO, bkinfoIncPrev: JET_BKINFO, bkinfoFullCur: JET_BKINFO, fShadowingDisabled: u32, fUpgradeDb: u32, dwMajorVersion: u32, dwMinorVersion: u32, dwBuildNumber: u32, lSPNumber: i32, cbPageSize: u32, genMinRequired: u32, genMaxRequired: u32, logtimeGenMaxCreate: JET_LOGTIME, ulRepairCount: u32, logtimeRepair: JET_LOGTIME, ulRepairCountOld: u32, ulECCFixSuccess: u32, logtimeECCFixSuccess: JET_LOGTIME, ulECCFixSuccessOld: u32, ulECCFixFail: u32, logtimeECCFixFail: JET_LOGTIME, ulECCFixFailOld: u32, ulBadChecksum: u32, logtimeBadChecksum: JET_LOGTIME, ulBadChecksumOld: u32, }; pub const JET_DBINFOMISC3 = extern struct { ulVersion: u32, ulUpdate: u32, signDb: JET_SIGNATURE, dbstate: u32, lgposConsistent: JET_LGPOS, logtimeConsistent: JET_LOGTIME, logtimeAttach: JET_LOGTIME, lgposAttach: JET_LGPOS, logtimeDetach: JET_LOGTIME, lgposDetach: JET_LGPOS, signLog: JET_SIGNATURE, bkinfoFullPrev: JET_BKINFO, bkinfoIncPrev: JET_BKINFO, bkinfoFullCur: JET_BKINFO, fShadowingDisabled: u32, fUpgradeDb: u32, dwMajorVersion: u32, dwMinorVersion: u32, dwBuildNumber: u32, lSPNumber: i32, cbPageSize: u32, genMinRequired: u32, genMaxRequired: u32, logtimeGenMaxCreate: JET_LOGTIME, ulRepairCount: u32, logtimeRepair: JET_LOGTIME, ulRepairCountOld: u32, ulECCFixSuccess: u32, logtimeECCFixSuccess: JET_LOGTIME, ulECCFixSuccessOld: u32, ulECCFixFail: u32, logtimeECCFixFail: JET_LOGTIME, ulECCFixFailOld: u32, ulBadChecksum: u32, logtimeBadChecksum: JET_LOGTIME, ulBadChecksumOld: u32, genCommitted: u32, }; pub const JET_DBINFOMISC4 = extern struct { ulVersion: u32, ulUpdate: u32, signDb: JET_SIGNATURE, dbstate: u32, lgposConsistent: JET_LGPOS, logtimeConsistent: JET_LOGTIME, logtimeAttach: JET_LOGTIME, lgposAttach: JET_LGPOS, logtimeDetach: JET_LOGTIME, lgposDetach: JET_LGPOS, signLog: JET_SIGNATURE, bkinfoFullPrev: JET_BKINFO, bkinfoIncPrev: JET_BKINFO, bkinfoFullCur: JET_BKINFO, fShadowingDisabled: u32, fUpgradeDb: u32, dwMajorVersion: u32, dwMinorVersion: u32, dwBuildNumber: u32, lSPNumber: i32, cbPageSize: u32, genMinRequired: u32, genMaxRequired: u32, logtimeGenMaxCreate: JET_LOGTIME, ulRepairCount: u32, logtimeRepair: JET_LOGTIME, ulRepairCountOld: u32, ulECCFixSuccess: u32, logtimeECCFixSuccess: JET_LOGTIME, ulECCFixSuccessOld: u32, ulECCFixFail: u32, logtimeECCFixFail: JET_LOGTIME, ulECCFixFailOld: u32, ulBadChecksum: u32, logtimeBadChecksum: JET_LOGTIME, ulBadChecksumOld: u32, genCommitted: u32, bkinfoCopyPrev: JET_BKINFO, bkinfoDiffPrev: JET_BKINFO, }; pub const JET_THREADSTATS = extern struct { cbStruct: u32, cPageReferenced: u32, cPageRead: u32, cPagePreread: u32, cPageDirtied: u32, cPageRedirtied: u32, cLogRecord: u32, cbLogRecord: u32, }; pub const JET_RSTINFO_A = extern struct { cbStruct: u32, rgrstmap: ?*JET_RSTMAP_A, crstmap: i32, lgposStop: JET_LGPOS, logtimeStop: JET_LOGTIME, pfnStatus: ?JET_PFNSTATUS, }; pub const JET_RSTINFO_W = extern struct { cbStruct: u32, rgrstmap: ?*JET_RSTMAP_W, crstmap: i32, lgposStop: JET_LGPOS, logtimeStop: JET_LOGTIME, pfnStatus: ?JET_PFNSTATUS, }; pub const JET_ERRCAT = enum(i32) { Unknown = 0, Error = 1, Operation = 2, Fatal = 3, IO = 4, Resource = 5, Memory = 6, Quota = 7, Disk = 8, Data = 9, Corruption = 10, Inconsistent = 11, Fragmentation = 12, Api = 13, Usage = 14, State = 15, Obsolete = 16, Max = 17, }; pub const JET_errcatUnknown = JET_ERRCAT.Unknown; pub const JET_errcatError = JET_ERRCAT.Error; pub const JET_errcatOperation = JET_ERRCAT.Operation; pub const JET_errcatFatal = JET_ERRCAT.Fatal; pub const JET_errcatIO = JET_ERRCAT.IO; pub const JET_errcatResource = JET_ERRCAT.Resource; pub const JET_errcatMemory = JET_ERRCAT.Memory; pub const JET_errcatQuota = JET_ERRCAT.Quota; pub const JET_errcatDisk = JET_ERRCAT.Disk; pub const JET_errcatData = JET_ERRCAT.Data; pub const JET_errcatCorruption = JET_ERRCAT.Corruption; pub const JET_errcatInconsistent = JET_ERRCAT.Inconsistent; pub const JET_errcatFragmentation = JET_ERRCAT.Fragmentation; pub const JET_errcatApi = JET_ERRCAT.Api; pub const JET_errcatUsage = JET_ERRCAT.Usage; pub const JET_errcatState = JET_ERRCAT.State; pub const JET_errcatObsolete = JET_ERRCAT.Obsolete; pub const JET_errcatMax = JET_ERRCAT.Max; pub const JET_ERRINFOBASIC_W = extern struct { cbStruct: u32, errValue: i32, errcatMostSpecific: JET_ERRCAT, rgCategoricalHierarchy: [8]u8, lSourceLine: u32, rgszSourceFile: [64]u16, }; pub const JET_PFNDURABLECOMMITCALLBACK = fn( instance: JET_INSTANCE, pCommitIdSeen: ?*JET_COMMIT_ID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const JET_INDEXCHECKING = enum(i32) { Off = 0, On = 1, DeferToOpenTable = 2, Max = 3, }; pub const JET_IndexCheckingOff = JET_INDEXCHECKING.Off; pub const JET_IndexCheckingOn = JET_INDEXCHECKING.On; pub const JET_IndexCheckingDeferToOpenTable = JET_INDEXCHECKING.DeferToOpenTable; pub const JET_IndexCheckingMax = JET_INDEXCHECKING.Max; pub const JET_OPERATIONCONTEXT = extern struct { ulUserID: u32, nOperationID: u8, nOperationType: u8, nClientType: u8, fFlags: u8, }; pub const JET_SETCOLUMN = extern struct { columnid: u32, pvData: ?*const anyopaque, cbData: u32, grbit: u32, ibLongValue: u32, itagSequence: u32, err: i32, }; pub const JET_SETSYSPARAM_A = extern struct { paramid: u32, lParam: JET_API_PTR, sz: ?[*:0]const u8, err: i32, }; pub const JET_SETSYSPARAM_W = extern struct { paramid: u32, lParam: JET_API_PTR, sz: ?[*:0]const u16, err: i32, }; pub const JET_RETRIEVECOLUMN = extern struct { columnid: u32, pvData: ?*anyopaque, cbData: u32, cbActual: u32, grbit: u32, ibLongValue: u32, itagSequence: u32, columnidNextTagged: u32, err: i32, }; pub const JET_ENUMCOLUMNID = extern struct { columnid: u32, ctagSequence: u32, rgtagSequence: ?*u32, }; pub const JET_ENUMCOLUMNVALUE = extern struct { itagSequence: u32, err: i32, cbData: u32, pvData: ?*anyopaque, }; pub const JET_ENUMCOLUMN = extern struct { columnid: u32, err: i32, Anonymous: extern union { Anonymous1: extern struct { cEnumColumnValue: u32, rgEnumColumnValue: ?*JET_ENUMCOLUMNVALUE, }, Anonymous2: extern struct { cbData: u32, pvData: ?*anyopaque, }, }, }; pub const JET_PFNREALLOC = fn( pvContext: ?*anyopaque, pv: ?*anyopaque, cb: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const JET_LOGINFO_A = extern struct { cbSize: u32, ulGenLow: u32, ulGenHigh: u32, szBaseName: [4]CHAR, }; pub const JET_LOGINFO_W = extern struct { cbSize: u32, ulGenLow: u32, ulGenHigh: u32, szBaseName: [4]u16, }; pub const JET_INSTANCE_INFO_A = extern struct { hInstanceId: JET_INSTANCE, szInstanceName: ?PSTR, cDatabases: JET_API_PTR, szDatabaseFileName: ?*?*i8, szDatabaseDisplayName: ?*?*i8, szDatabaseSLVFileName_Obsolete: ?*?*i8, }; pub const JET_INSTANCE_INFO_W = extern struct { hInstanceId: JET_INSTANCE, szInstanceName: ?PWSTR, cDatabases: JET_API_PTR, szDatabaseFileName: ?*?*u16, szDatabaseDisplayName: ?*?*u16, szDatabaseSLVFileName_Obsolete: ?*?*u16, }; pub const JET_INDEXID = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cbStruct: u32, rgbIndexId: [16]u8, }, .X86 => extern struct { cbStruct: u32, rgbIndexId: [12]u8, }, }; pub const JET_OBJECTINFO = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cbStruct: u32, objtyp: u32, dtCreate: f64, dtUpdate: f64, grbit: u32, flags: u32, cRecord: u32, cPage: u32, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbStruct: u32, objtyp: u32, dtCreate: f64, dtUpdate: f64, grbit: u32, flags: u32, cRecord: u32, cPage: u32, }, }; pub const JET_THREADSTATS2 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cbStruct: u32, cPageReferenced: u32, cPageRead: u32, cPagePreread: u32, cPageDirtied: u32, cPageRedirtied: u32, cLogRecord: u32, cbLogRecord: u32, cusecPageCacheMiss: u64, cPageCacheMiss: u32, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbStruct: u32, cPageReferenced: u32, cPageRead: u32, cPagePreread: u32, cPageDirtied: u32, cPageRedirtied: u32, cLogRecord: u32, cbLogRecord: u32, cusecPageCacheMiss: u64, cPageCacheMiss: u32, }, }; pub const JET_COMMIT_ID = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { signLog: JET_SIGNATURE, reserved: i32, commitId: i64, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug signLog: JET_SIGNATURE, reserved: i32, commitId: i64, }, }; pub const JET_RBSINFOMISC = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { lRBSGeneration: i32, logtimeCreate: JET_LOGTIME, logtimeCreatePrevRBS: JET_LOGTIME, ulMajor: u32, ulMinor: u32, cbLogicalFileSize: u64, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug lRBSGeneration: i32, logtimeCreate: JET_LOGTIME, logtimeCreatePrevRBS: JET_LOGTIME, ulMajor: u32, ulMinor: u32, cbLogicalFileSize: u64, }, }; pub const JET_RBSREVERTINFOMISC = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { lGenMinRevertStart: i32, lGenMaxRevertStart: i32, lGenMinRevertEnd: i32, lGenMaxRevertEnd: i32, logtimeRevertFrom: JET_LOGTIME, cSecRevert: u64, cPagesReverted: u64, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug lGenMinRevertStart: i32, lGenMaxRevertStart: i32, lGenMinRevertEnd: i32, lGenMaxRevertEnd: i32, logtimeRevertFrom: JET_LOGTIME, cSecRevert: u64, cPagesReverted: u64, }, }; pub const JET_RECSIZE = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cbData: u64, cbLongValueData: u64, cbOverhead: u64, cbLongValueOverhead: u64, cNonTaggedColumns: u64, cTaggedColumns: u64, cLongValues: u64, cMultiValues: u64, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbData: u64, cbLongValueData: u64, cbOverhead: u64, cbLongValueOverhead: u64, cNonTaggedColumns: u64, cTaggedColumns: u64, cLongValues: u64, cMultiValues: u64, }, }; pub const JET_RECSIZE2 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cbData: u64, cbLongValueData: u64, cbOverhead: u64, cbLongValueOverhead: u64, cNonTaggedColumns: u64, cTaggedColumns: u64, cLongValues: u64, cMultiValues: u64, cCompressedColumns: u64, cbDataCompressed: u64, cbLongValueDataCompressed: u64, }, .X86 => extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbData: u64, cbLongValueData: u64, cbOverhead: u64, cbLongValueOverhead: u64, cNonTaggedColumns: u64, cTaggedColumns: u64, cLongValues: u64, cMultiValues: u64, cCompressedColumns: u64, cbDataCompressed: u64, cbLongValueDataCompressed: u64, }, }; //-------------------------------------------------------------------------------- // Section: Functions (229) //-------------------------------------------------------------------------------- pub extern "ESENT" fn JetInit( pinstance: ?*JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetInit2( pinstance: ?*JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetInit3A( pinstance: ?*JET_INSTANCE, prstInfo: ?*JET_RSTINFO_A, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetInit3W( pinstance: ?*JET_INSTANCE, prstInfo: ?*JET_RSTINFO_W, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateInstanceA( pinstance: ?*JET_INSTANCE, szInstanceName: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateInstanceW( pinstance: ?*JET_INSTANCE, szInstanceName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateInstance2A( pinstance: ?*JET_INSTANCE, szInstanceName: ?*i8, szDisplayName: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateInstance2W( pinstance: ?*JET_INSTANCE, szInstanceName: ?*u16, szDisplayName: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetInstanceMiscInfo( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetTerm( instance: JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetTerm2( instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetStopService( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetStopServiceInstance( instance: JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetStopServiceInstance2( instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetStopBackup( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetStopBackupInstance( instance: JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; // This function from dll 'ESENT' is being skipped because it has some sort of issue pub fn JetSetSystemParameterA() void { @panic("this function is not working"); } // This function from dll 'ESENT' is being skipped because it has some sort of issue pub fn JetSetSystemParameterW() void { @panic("this function is not working"); } pub extern "ESENT" fn JetGetSystemParameterA( instance: JET_INSTANCE, sesid: ?JET_SESID, paramid: u32, plParam: ?*JET_API_PTR, // TODO: what to do with BytesParamIndex 5? szParam: ?*i8, cbMax: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetSystemParameterW( instance: JET_INSTANCE, sesid: ?JET_SESID, paramid: u32, plParam: ?*JET_API_PTR, // TODO: what to do with BytesParamIndex 5? szParam: ?*u16, cbMax: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEnableMultiInstanceA( psetsysparam: ?[*]JET_SETSYSPARAM_A, csetsysparam: u32, pcsetsucceed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEnableMultiInstanceW( psetsysparam: ?[*]JET_SETSYSPARAM_W, csetsysparam: u32, pcsetsucceed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetThreadStats( // TODO: what to do with BytesParamIndex 1? pvResult: ?*anyopaque, cbMax: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginSessionA( instance: JET_INSTANCE, psesid: ?*?JET_SESID, szUserName: ?*i8, szPassword: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginSessionW( instance: JET_INSTANCE, psesid: ?*?JET_SESID, szUserName: ?*u16, szPassword: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDupSession( sesid: ?JET_SESID, psesid: ?*?JET_SESID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEndSession( sesid: ?JET_SESID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetVersion( sesid: ?JET_SESID, pwVersion: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetIdle( sesid: ?JET_SESID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateDatabaseA( sesid: ?JET_SESID, szFilename: ?*i8, szConnect: ?*i8, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateDatabaseW( sesid: ?JET_SESID, szFilename: ?*u16, szConnect: ?*u16, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateDatabase2A( sesid: ?JET_SESID, szFilename: ?*i8, cpgDatabaseSizeMax: u32, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateDatabase2W( sesid: ?JET_SESID, szFilename: ?*u16, cpgDatabaseSizeMax: u32, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAttachDatabaseA( sesid: ?JET_SESID, szFilename: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAttachDatabaseW( sesid: ?JET_SESID, szFilename: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAttachDatabase2A( sesid: ?JET_SESID, szFilename: ?*i8, cpgDatabaseSizeMax: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAttachDatabase2W( sesid: ?JET_SESID, szFilename: ?*u16, cpgDatabaseSizeMax: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDetachDatabaseA( sesid: ?JET_SESID, szFilename: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDetachDatabaseW( sesid: ?JET_SESID, szFilename: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDetachDatabase2A( sesid: ?JET_SESID, szFilename: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDetachDatabase2W( sesid: ?JET_SESID, szFilename: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetObjectInfoA( sesid: ?JET_SESID, dbid: u32, objtyp: u32, szContainerName: ?*i8, szObjectName: ?*i8, // TODO: what to do with BytesParamIndex 6? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetObjectInfoW( sesid: ?JET_SESID, dbid: u32, objtyp: u32, szContainerName: ?*u16, szObjectName: ?*u16, // TODO: what to do with BytesParamIndex 6? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableInfoA( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableInfoW( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, lPages: u32, lDensity: u32, ptableid: ?*JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, lPages: u32, lDensity: u32, ptableid: ?*JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndexA( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndexW( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex2A( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE2_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex2W( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE2_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex3A( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE3_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex3W( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE3_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex4A( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE4_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateTableColumnIndex4W( sesid: ?JET_SESID, dbid: u32, ptablecreate: ?*JET_TABLECREATE4_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteTableA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteTableW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRenameTableA( sesid: ?JET_SESID, dbid: u32, szName: ?*i8, szNameNew: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRenameTableW( sesid: ?JET_SESID, dbid: u32, szName: ?*u16, szNameNew: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableColumnInfoA( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*i8, // TODO: what to do with BytesParamIndex 4? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableColumnInfoW( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*u16, // TODO: what to do with BytesParamIndex 4? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetColumnInfoA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, pColumnNameOrId: ?*i8, // TODO: what to do with BytesParamIndex 5? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetColumnInfoW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, pwColumnNameOrId: ?*u16, // TODO: what to do with BytesParamIndex 5? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAddColumnA( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*i8, pcolumndef: ?*const JET_COLUMNDEF, // TODO: what to do with BytesParamIndex 5? pvDefault: ?*const anyopaque, cbDefault: u32, pcolumnid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetAddColumnW( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*u16, pcolumndef: ?*const JET_COLUMNDEF, // TODO: what to do with BytesParamIndex 5? pvDefault: ?*const anyopaque, cbDefault: u32, pcolumnid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteColumnA( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteColumnW( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteColumn2A( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteColumn2W( sesid: ?JET_SESID, tableid: JET_TABLEID, szColumnName: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRenameColumnA( sesid: ?JET_SESID, tableid: JET_TABLEID, szName: ?*i8, szNameNew: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRenameColumnW( sesid: ?JET_SESID, tableid: JET_TABLEID, szName: ?*u16, szNameNew: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetColumnDefaultValueA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, szColumnName: ?*i8, // TODO: what to do with BytesParamIndex 5? pvData: ?*const anyopaque, cbData: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetColumnDefaultValueW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, szColumnName: ?*u16, // TODO: what to do with BytesParamIndex 5? pvData: ?*const anyopaque, cbData: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableIndexInfoA( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, // TODO: what to do with BytesParamIndex 4? pvResult: ?*anyopaque, cbResult: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTableIndexInfoW( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, // TODO: what to do with BytesParamIndex 4? pvResult: ?*anyopaque, cbResult: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetIndexInfoA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, szIndexName: ?*i8, // TODO: what to do with BytesParamIndex 5? pvResult: ?*anyopaque, cbResult: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetIndexInfoW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, szIndexName: ?*u16, // TODO: what to do with BytesParamIndex 5? pvResult: ?*anyopaque, cbResult: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndexA( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, grbit: u32, // TODO: what to do with BytesParamIndex 5? szKey: ?[*:0]const u8, cbKey: u32, lDensity: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndexW( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, grbit: u32, // TODO: what to do with BytesParamIndex 5? szKey: ?[*:0]const u16, cbKey: u32, lDensity: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex2A( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE_A, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex2W( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE_W, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex3A( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE2_A, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex3W( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE2_W, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex4A( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE3_A, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCreateIndex4W( sesid: ?JET_SESID, tableid: JET_TABLEID, pindexcreate: [*]JET_INDEXCREATE3_W, cIndexCreate: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteIndexA( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDeleteIndexW( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginTransaction( sesid: ?JET_SESID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginTransaction2( sesid: ?JET_SESID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginTransaction3( sesid: ?JET_SESID, trxid: i64, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCommitTransaction( sesid: ?JET_SESID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCommitTransaction2( sesid: ?JET_SESID, grbit: u32, cmsecDurableCommit: u32, pCommitId: ?*JET_COMMIT_ID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRollback( sesid: ?JET_SESID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetDatabaseInfoA( sesid: ?JET_SESID, dbid: u32, // TODO: what to do with BytesParamIndex 3? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetDatabaseInfoW( sesid: ?JET_SESID, dbid: u32, // TODO: what to do with BytesParamIndex 3? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetDatabaseFileInfoA( szDatabaseName: ?*i8, // TODO: what to do with BytesParamIndex 2? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetDatabaseFileInfoW( szDatabaseName: ?*u16, // TODO: what to do with BytesParamIndex 2? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenDatabaseA( sesid: ?JET_SESID, szFilename: ?*i8, szConnect: ?*i8, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenDatabaseW( sesid: ?JET_SESID, szFilename: ?*u16, szConnect: ?*u16, pdbid: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCloseDatabase( sesid: ?JET_SESID, dbid: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTableA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, // TODO: what to do with BytesParamIndex 4? pvParameters: ?*const anyopaque, cbParameters: u32, grbit: u32, ptableid: ?*JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTableW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, // TODO: what to do with BytesParamIndex 4? pvParameters: ?*const anyopaque, cbParameters: u32, grbit: u32, ptableid: ?*JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetTableSequential( sesid: ?JET_SESID, tableid: JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetResetTableSequential( sesid: ?JET_SESID, tableid: JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCloseTable( sesid: ?JET_SESID, tableid: JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDelete( sesid: ?JET_SESID, tableid: JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetUpdate( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvBookmark: ?*anyopaque, cbBookmark: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetUpdate2( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvBookmark: ?*anyopaque, cbBookmark: u32, pcbActual: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEscrowUpdate( sesid: ?JET_SESID, tableid: JET_TABLEID, columnid: u32, // TODO: what to do with BytesParamIndex 4? pv: ?*anyopaque, cbMax: u32, // TODO: what to do with BytesParamIndex 6? pvOld: ?*anyopaque, cbOldMax: u32, pcbOldActual: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRetrieveColumn( sesid: ?JET_SESID, tableid: JET_TABLEID, columnid: u32, // TODO: what to do with BytesParamIndex 4? pvData: ?*anyopaque, cbData: u32, pcbActual: ?*u32, grbit: u32, pretinfo: ?*JET_RETINFO, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRetrieveColumns( sesid: ?JET_SESID, tableid: JET_TABLEID, pretrievecolumn: ?[*]JET_RETRIEVECOLUMN, cretrievecolumn: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEnumerateColumns( sesid: ?JET_SESID, tableid: JET_TABLEID, cEnumColumnId: u32, rgEnumColumnId: ?[*]JET_ENUMCOLUMNID, pcEnumColumn: ?*u32, prgEnumColumn: ?*?*JET_ENUMCOLUMN, pfnRealloc: ?JET_PFNREALLOC, pvReallocContext: ?*anyopaque, cbDataMost: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetRecordSize( sesid: ?JET_SESID, tableid: JET_TABLEID, precsize: ?*JET_RECSIZE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetRecordSize2( sesid: ?JET_SESID, tableid: JET_TABLEID, precsize: ?*JET_RECSIZE2, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetColumn( sesid: ?JET_SESID, tableid: JET_TABLEID, columnid: u32, // TODO: what to do with BytesParamIndex 4? pvData: ?*const anyopaque, cbData: u32, grbit: u32, psetinfo: ?*JET_SETINFO, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetColumns( sesid: ?JET_SESID, tableid: JET_TABLEID, psetcolumn: ?[*]JET_SETCOLUMN, csetcolumn: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetPrepareUpdate( sesid: ?JET_SESID, tableid: JET_TABLEID, prep: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetRecordPosition( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? precpos: ?*JET_RECPOS, cbRecpos: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGotoPosition( sesid: ?JET_SESID, tableid: JET_TABLEID, precpos: ?*JET_RECPOS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetCursorInfo( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDupCursor( sesid: ?JET_SESID, tableid: JET_TABLEID, ptableid: ?*JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetCurrentIndexA( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? szIndexName: ?*i8, cbIndexName: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetCurrentIndexW( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? szIndexName: ?*u16, cbIndexName: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndexA( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndexW( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex2A( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex2W( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex3A( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, grbit: u32, itagSequence: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex3W( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, grbit: u32, itagSequence: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex4A( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*i8, pindexid: ?*JET_INDEXID, grbit: u32, itagSequence: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCurrentIndex4W( sesid: ?JET_SESID, tableid: JET_TABLEID, szIndexName: ?*u16, pindexid: ?*JET_INDEXID, grbit: u32, itagSequence: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetMove( sesid: ?JET_SESID, tableid: JET_TABLEID, cRow: i32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetCursorFilter( sesid: ?JET_SESID, tableid: JET_TABLEID, rgColumnFilters: [*]JET_INDEX_COLUMN, cColumnFilters: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLock( sesid: ?JET_SESID, tableid: JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetMakeKey( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvData: ?*const anyopaque, cbData: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSeek( sesid: ?JET_SESID, tableid: JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetPrereadKeys( sesid: ?JET_SESID, tableid: JET_TABLEID, rgpvKeys: [*]const ?*const anyopaque, rgcbKeys: [*]const u32, ckeys: i32, pckeysPreread: ?*i32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetPrereadIndexRanges( sesid: ?JET_SESID, tableid: JET_TABLEID, rgIndexRanges: [*]const JET_INDEX_RANGE, cIndexRanges: u32, pcRangesPreread: ?*u32, rgcolumnidPreread: [*]const u32, ccolumnidPreread: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetBookmark( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvBookmark: ?*anyopaque, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetSecondaryIndexBookmark( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvSecondaryKey: ?*anyopaque, cbSecondaryKeyMax: u32, pcbSecondaryKeyActual: ?*u32, // TODO: what to do with BytesParamIndex 6? pvPrimaryBookmark: ?*anyopaque, cbPrimaryBookmarkMax: u32, pcbPrimaryBookmarkActual: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCompactA( sesid: ?JET_SESID, szDatabaseSrc: ?*i8, szDatabaseDest: ?*i8, pfnStatus: ?JET_PFNSTATUS, pconvert: ?*CONVERT_A, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCompactW( sesid: ?JET_SESID, szDatabaseSrc: ?*u16, szDatabaseDest: ?*u16, pfnStatus: ?JET_PFNSTATUS, pconvert: ?*CONVERT_W, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragmentA( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, pcPasses: ?*u32, pcSeconds: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragmentW( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, pcPasses: ?*u32, pcSeconds: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragment2A( sesid: ?JET_SESID, dbid: u32, szTableName: ?*i8, pcPasses: ?*u32, pcSeconds: ?*u32, callback: ?JET_CALLBACK, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragment2W( sesid: ?JET_SESID, dbid: u32, szTableName: ?*u16, pcPasses: ?*u32, pcSeconds: ?*u32, callback: ?JET_CALLBACK, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragment3A( sesid: ?JET_SESID, szDatabaseName: ?*i8, szTableName: ?*i8, pcPasses: ?*u32, pcSeconds: ?*u32, callback: ?JET_CALLBACK, pvContext: ?*anyopaque, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetDefragment3W( sesid: ?JET_SESID, szDatabaseName: ?*u16, szTableName: ?*u16, pcPasses: ?*u32, pcSeconds: ?*u32, callback: ?JET_CALLBACK, pvContext: ?*anyopaque, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetDatabaseSizeA( sesid: ?JET_SESID, szDatabaseName: ?*i8, cpg: u32, pcpgReal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetDatabaseSizeW( sesid: ?JET_SESID, szDatabaseName: ?*u16, cpg: u32, pcpgReal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGrowDatabase( sesid: ?JET_SESID, dbid: u32, cpg: u32, pcpgReal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetResizeDatabase( sesid: ?JET_SESID, dbid: u32, cpgTarget: u32, pcpgActual: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetSessionContext( sesid: ?JET_SESID, ulContext: JET_API_PTR, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetResetSessionContext( sesid: ?JET_SESID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGotoBookmark( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvBookmark: ?*anyopaque, cbBookmark: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGotoSecondaryIndexBookmark( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvSecondaryKey: ?*anyopaque, cbSecondaryKey: u32, // TODO: what to do with BytesParamIndex 5? pvPrimaryBookmark: ?*anyopaque, cbPrimaryBookmark: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetIntersectIndexes( sesid: ?JET_SESID, rgindexrange: [*]JET_INDEXRANGE, cindexrange: u32, precordlist: ?*JET_RECORDLIST, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetComputeStats( sesid: ?JET_SESID, tableid: JET_TABLEID, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTempTable( sesid: ?JET_SESID, prgcolumndef: [*]const JET_COLUMNDEF, ccolumn: u32, grbit: u32, ptableid: ?*JET_TABLEID, prgcolumnid: [*]u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTempTable2( sesid: ?JET_SESID, prgcolumndef: [*]const JET_COLUMNDEF, ccolumn: u32, lcid: u32, grbit: u32, ptableid: ?*JET_TABLEID, prgcolumnid: [*]u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTempTable3( sesid: ?JET_SESID, prgcolumndef: [*]const JET_COLUMNDEF, ccolumn: u32, pidxunicode: ?*JET_UNICODEINDEX, grbit: u32, ptableid: ?*JET_TABLEID, prgcolumnid: [*]u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTemporaryTable( sesid: ?JET_SESID, popentemporarytable: ?*JET_OPENTEMPORARYTABLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenTemporaryTable2( sesid: ?JET_SESID, popentemporarytable: ?*JET_OPENTEMPORARYTABLE2, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBackupA( szBackupPath: ?*i8, grbit: u32, pfnStatus: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBackupW( szBackupPath: ?*u16, grbit: u32, pfnStatus: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBackupInstanceA( instance: JET_INSTANCE, szBackupPath: ?*i8, grbit: u32, pfnStatus: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBackupInstanceW( instance: JET_INSTANCE, szBackupPath: ?*u16, grbit: u32, pfnStatus: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestoreA( szSource: ?*i8, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestoreW( szSource: ?*u16, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestore2A( sz: ?*i8, szDest: ?*i8, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestore2W( sz: ?*u16, szDest: ?*u16, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestoreInstanceA( instance: JET_INSTANCE, sz: ?*i8, szDest: ?*i8, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRestoreInstanceW( instance: JET_INSTANCE, sz: ?*u16, szDest: ?*u16, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetIndexRange( sesid: ?JET_SESID, tableidSrc: JET_TABLEID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetIndexRecordCount( sesid: ?JET_SESID, tableid: JET_TABLEID, pcrec: ?*u32, crecMax: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRetrieveKey( sesid: ?JET_SESID, tableid: JET_TABLEID, // TODO: what to do with BytesParamIndex 3? pvKey: ?*anyopaque, cbMax: u32, pcbActual: ?*u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginExternalBackup( grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetBeginExternalBackupInstance( instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetAttachInfoA( // TODO: what to do with BytesParamIndex 1? szzDatabases: ?*i8, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetAttachInfoW( // TODO: what to do with BytesParamIndex 1? wszzDatabases: ?*u16, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetAttachInfoInstanceA( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? szzDatabases: ?*i8, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetAttachInfoInstanceW( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? szzDatabases: ?*u16, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenFileA( szFileName: ?*i8, phfFile: ?*JET_HANDLE, pulFileSizeLow: ?*u32, pulFileSizeHigh: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenFileW( szFileName: ?*u16, phfFile: ?*JET_HANDLE, pulFileSizeLow: ?*u32, pulFileSizeHigh: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenFileInstanceA( instance: JET_INSTANCE, szFileName: ?*i8, phfFile: ?*JET_HANDLE, pulFileSizeLow: ?*u32, pulFileSizeHigh: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOpenFileInstanceW( instance: JET_INSTANCE, szFileName: ?*u16, phfFile: ?*JET_HANDLE, pulFileSizeLow: ?*u32, pulFileSizeHigh: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetReadFile( hfFile: JET_HANDLE, // TODO: what to do with BytesParamIndex 2? pv: ?*anyopaque, cb: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetReadFileInstance( instance: JET_INSTANCE, hfFile: JET_HANDLE, // TODO: what to do with BytesParamIndex 3? pv: ?*anyopaque, cb: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCloseFile( hfFile: JET_HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetCloseFileInstance( instance: JET_INSTANCE, hfFile: JET_HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoA( // TODO: what to do with BytesParamIndex 1? szzLogs: ?*i8, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoW( // TODO: what to do with BytesParamIndex 1? szzLogs: ?*u16, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoInstanceA( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? szzLogs: ?*i8, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoInstanceW( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? wszzLogs: ?*u16, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoInstance2A( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? szzLogs: ?*i8, cbMax: u32, pcbActual: ?*u32, pLogInfo: ?*JET_LOGINFO_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLogInfoInstance2W( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? wszzLogs: ?*u16, cbMax: u32, pcbActual: ?*u32, pLogInfo: ?*JET_LOGINFO_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTruncateLogInfoInstanceA( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? szzLogs: ?*i8, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetTruncateLogInfoInstanceW( instance: JET_INSTANCE, // TODO: what to do with BytesParamIndex 2? wszzLogs: ?*u16, cbMax: u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetTruncateLog( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetTruncateLogInstance( instance: JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEndExternalBackup( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEndExternalBackupInstance( instance: JET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetEndExternalBackupInstance2( instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetExternalRestoreA( szCheckpointFilePath: ?*i8, szLogPath: ?*i8, rgrstmap: ?[*]JET_RSTMAP_A, crstfilemap: i32, szBackupLogPath: ?*i8, genLow: i32, genHigh: i32, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetExternalRestoreW( szCheckpointFilePath: ?*u16, szLogPath: ?*u16, rgrstmap: ?[*]JET_RSTMAP_W, crstfilemap: i32, szBackupLogPath: ?*u16, genLow: i32, genHigh: i32, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetExternalRestore2A( szCheckpointFilePath: ?*i8, szLogPath: ?*i8, rgrstmap: ?[*]JET_RSTMAP_A, crstfilemap: i32, szBackupLogPath: ?*i8, pLogInfo: ?*JET_LOGINFO_A, szTargetInstanceName: ?*i8, szTargetInstanceLogPath: ?*i8, szTargetInstanceCheckpointPath: ?*i8, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetExternalRestore2W( szCheckpointFilePath: ?*u16, szLogPath: ?*u16, rgrstmap: ?[*]JET_RSTMAP_W, crstfilemap: i32, szBackupLogPath: ?*u16, pLogInfo: ?*JET_LOGINFO_W, szTargetInstanceName: ?*u16, szTargetInstanceLogPath: ?*u16, szTargetInstanceCheckpointPath: ?*u16, pfn: ?JET_PFNSTATUS, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetRegisterCallback( sesid: ?JET_SESID, tableid: JET_TABLEID, cbtyp: u32, pCallback: ?JET_CALLBACK, pvContext: ?*anyopaque, phCallbackId: ?*JET_HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetUnregisterCallback( sesid: ?JET_SESID, tableid: JET_TABLEID, cbtyp: u32, hCallbackId: JET_HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetInstanceInfoA( pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_A, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetInstanceInfoW( pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_W, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetFreeBuffer( pbBuf: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetLS( sesid: ?JET_SESID, tableid: JET_TABLEID, ls: JET_LS, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetLS( sesid: ?JET_SESID, tableid: JET_TABLEID, pls: ?*JET_LS, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotPrepare( psnapId: ?*JET_OSSNAPID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotPrepareInstance( snapId: JET_OSSNAPID, instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotFreezeA( snapId: JET_OSSNAPID, pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_A, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotFreezeW( snapId: JET_OSSNAPID, pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_W, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotThaw( snapId: JET_OSSNAPID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotAbort( snapId: JET_OSSNAPID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotTruncateLog( snapId: JET_OSSNAPID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotTruncateLogInstance( snapId: JET_OSSNAPID, instance: JET_INSTANCE, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotGetFreezeInfoA( snapId: JET_OSSNAPID, pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_A, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotGetFreezeInfoW( snapId: JET_OSSNAPID, pcInstanceInfo: ?*u32, paInstanceInfo: ?*?*JET_INSTANCE_INFO_W, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetOSSnapshotEnd( snapId: JET_OSSNAPID, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetConfigureProcessForCrashDump( grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetErrorInfoW( pvContext: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? pvResult: ?*anyopaque, cbMax: u32, InfoLevel: u32, grbit: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetSetSessionParameter( sesid: ?JET_SESID, sesparamid: u32, // TODO: what to do with BytesParamIndex 3? pvParam: ?*anyopaque, cbParam: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "ESENT" fn JetGetSessionParameter( sesid: ?JET_SESID, sesparamid: u32, pvParam: [*]u8, cbParamMax: u32, pcbParamActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (85) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const JET_RSTMAP_ = thismodule.JET_RSTMAP_A; pub const CONVERT_ = thismodule.CONVERT_A; pub const JET_COLUMNBASE_ = thismodule.JET_COLUMNBASE_A; pub const JET_COLUMNCREATE_ = thismodule.JET_COLUMNCREATE_A; pub const JET_USERDEFINEDDEFAULT_ = thismodule.JET_USERDEFINEDDEFAULT_A; pub const JET_CONDITIONALCOLUMN_ = thismodule.JET_CONDITIONALCOLUMN_A; pub const JET_INDEXCREATE_ = thismodule.JET_INDEXCREATE_A; pub const JET_INDEXCREATE2_ = thismodule.JET_INDEXCREATE2_A; pub const JET_INDEXCREATE3_ = thismodule.JET_INDEXCREATE3_A; pub const JET_TABLECREATE_ = thismodule.JET_TABLECREATE_A; pub const JET_TABLECREATE2_ = thismodule.JET_TABLECREATE2_A; pub const JET_TABLECREATE3_ = thismodule.JET_TABLECREATE3_A; pub const JET_TABLECREATE4_ = thismodule.JET_TABLECREATE4_A; pub const JET_RSTINFO_ = thismodule.JET_RSTINFO_A; pub const JET_SETSYSPARAM_ = thismodule.JET_SETSYSPARAM_A; pub const JET_LOGINFO_ = thismodule.JET_LOGINFO_A; pub const JET_INSTANCE_INFO_ = thismodule.JET_INSTANCE_INFO_A; pub const JetInit3 = thismodule.JetInit3A; pub const JetCreateInstance = thismodule.JetCreateInstanceA; pub const JetCreateInstance2 = thismodule.JetCreateInstance2A; pub const JetSetSystemParameter = thismodule.JetSetSystemParameterA; pub const JetGetSystemParameter = thismodule.JetGetSystemParameterA; pub const JetEnableMultiInstance = thismodule.JetEnableMultiInstanceA; pub const JetBeginSession = thismodule.JetBeginSessionA; pub const JetCreateDatabase = thismodule.JetCreateDatabaseA; pub const JetCreateDatabase2 = thismodule.JetCreateDatabase2A; pub const JetAttachDatabase = thismodule.JetAttachDatabaseA; pub const JetAttachDatabase2 = thismodule.JetAttachDatabase2A; pub const JetDetachDatabase = thismodule.JetDetachDatabaseA; pub const JetDetachDatabase2 = thismodule.JetDetachDatabase2A; pub const JetGetObjectInfo = thismodule.JetGetObjectInfoA; pub const JetGetTableInfo = thismodule.JetGetTableInfoA; pub const JetCreateTable = thismodule.JetCreateTableA; pub const JetCreateTableColumnIndex = thismodule.JetCreateTableColumnIndexA; pub const JetCreateTableColumnIndex2 = thismodule.JetCreateTableColumnIndex2A; pub const JetCreateTableColumnIndex3 = thismodule.JetCreateTableColumnIndex3A; pub const JetCreateTableColumnIndex4 = thismodule.JetCreateTableColumnIndex4A; pub const JetDeleteTable = thismodule.JetDeleteTableA; pub const JetRenameTable = thismodule.JetRenameTableA; pub const JetGetTableColumnInfo = thismodule.JetGetTableColumnInfoA; pub const JetGetColumnInfo = thismodule.JetGetColumnInfoA; pub const JetAddColumn = thismodule.JetAddColumnA; pub const JetDeleteColumn = thismodule.JetDeleteColumnA; pub const JetDeleteColumn2 = thismodule.JetDeleteColumn2A; pub const JetRenameColumn = thismodule.JetRenameColumnA; pub const JetSetColumnDefaultValue = thismodule.JetSetColumnDefaultValueA; pub const JetGetTableIndexInfo = thismodule.JetGetTableIndexInfoA; pub const JetGetIndexInfo = thismodule.JetGetIndexInfoA; pub const JetCreateIndex = thismodule.JetCreateIndexA; pub const JetCreateIndex2 = thismodule.JetCreateIndex2A; pub const JetCreateIndex3 = thismodule.JetCreateIndex3A; pub const JetCreateIndex4 = thismodule.JetCreateIndex4A; pub const JetDeleteIndex = thismodule.JetDeleteIndexA; pub const JetGetDatabaseInfo = thismodule.JetGetDatabaseInfoA; pub const JetGetDatabaseFileInfo = thismodule.JetGetDatabaseFileInfoA; pub const JetOpenDatabase = thismodule.JetOpenDatabaseA; pub const JetOpenTable = thismodule.JetOpenTableA; pub const JetGetCurrentIndex = thismodule.JetGetCurrentIndexA; pub const JetSetCurrentIndex = thismodule.JetSetCurrentIndexA; pub const JetSetCurrentIndex2 = thismodule.JetSetCurrentIndex2A; pub const JetSetCurrentIndex3 = thismodule.JetSetCurrentIndex3A; pub const JetSetCurrentIndex4 = thismodule.JetSetCurrentIndex4A; pub const JetCompact = thismodule.JetCompactA; pub const JetDefragment = thismodule.JetDefragmentA; pub const JetDefragment2 = thismodule.JetDefragment2A; pub const JetDefragment3 = thismodule.JetDefragment3A; pub const JetSetDatabaseSize = thismodule.JetSetDatabaseSizeA; pub const JetBackup = thismodule.JetBackupA; pub const JetBackupInstance = thismodule.JetBackupInstanceA; pub const JetRestore = thismodule.JetRestoreA; pub const JetRestore2 = thismodule.JetRestore2A; pub const JetRestoreInstance = thismodule.JetRestoreInstanceA; pub const JetGetAttachInfo = thismodule.JetGetAttachInfoA; pub const JetGetAttachInfoInstance = thismodule.JetGetAttachInfoInstanceA; pub const JetOpenFile = thismodule.JetOpenFileA; pub const JetOpenFileInstance = thismodule.JetOpenFileInstanceA; pub const JetGetLogInfo = thismodule.JetGetLogInfoA; pub const JetGetLogInfoInstance = thismodule.JetGetLogInfoInstanceA; pub const JetGetLogInfoInstance2 = thismodule.JetGetLogInfoInstance2A; pub const JetGetTruncateLogInfoInstance = thismodule.JetGetTruncateLogInfoInstanceA; pub const JetExternalRestore = thismodule.JetExternalRestoreA; pub const JetExternalRestore2 = thismodule.JetExternalRestore2A; pub const JetGetInstanceInfo = thismodule.JetGetInstanceInfoA; pub const JetOSSnapshotFreeze = thismodule.JetOSSnapshotFreezeA; pub const JetOSSnapshotGetFreezeInfo = thismodule.JetOSSnapshotGetFreezeInfoA; }, .wide => struct { pub const JET_RSTMAP_ = thismodule.JET_RSTMAP_W; pub const CONVERT_ = thismodule.CONVERT_W; pub const JET_COLUMNBASE_ = thismodule.JET_COLUMNBASE_W; pub const JET_COLUMNCREATE_ = thismodule.JET_COLUMNCREATE_W; pub const JET_USERDEFINEDDEFAULT_ = thismodule.JET_USERDEFINEDDEFAULT_W; pub const JET_CONDITIONALCOLUMN_ = thismodule.JET_CONDITIONALCOLUMN_W; pub const JET_INDEXCREATE_ = thismodule.JET_INDEXCREATE_W; pub const JET_INDEXCREATE2_ = thismodule.JET_INDEXCREATE2_W; pub const JET_INDEXCREATE3_ = thismodule.JET_INDEXCREATE3_W; pub const JET_TABLECREATE_ = thismodule.JET_TABLECREATE_W; pub const JET_TABLECREATE2_ = thismodule.JET_TABLECREATE2_W; pub const JET_TABLECREATE3_ = thismodule.JET_TABLECREATE3_W; pub const JET_TABLECREATE4_ = thismodule.JET_TABLECREATE4_W; pub const JET_RSTINFO_ = thismodule.JET_RSTINFO_W; pub const JET_SETSYSPARAM_ = thismodule.JET_SETSYSPARAM_W; pub const JET_LOGINFO_ = thismodule.JET_LOGINFO_W; pub const JET_INSTANCE_INFO_ = thismodule.JET_INSTANCE_INFO_W; pub const JetInit3 = thismodule.JetInit3W; pub const JetCreateInstance = thismodule.JetCreateInstanceW; pub const JetCreateInstance2 = thismodule.JetCreateInstance2W; pub const JetSetSystemParameter = thismodule.JetSetSystemParameterW; pub const JetGetSystemParameter = thismodule.JetGetSystemParameterW; pub const JetEnableMultiInstance = thismodule.JetEnableMultiInstanceW; pub const JetBeginSession = thismodule.JetBeginSessionW; pub const JetCreateDatabase = thismodule.JetCreateDatabaseW; pub const JetCreateDatabase2 = thismodule.JetCreateDatabase2W; pub const JetAttachDatabase = thismodule.JetAttachDatabaseW; pub const JetAttachDatabase2 = thismodule.JetAttachDatabase2W; pub const JetDetachDatabase = thismodule.JetDetachDatabaseW; pub const JetDetachDatabase2 = thismodule.JetDetachDatabase2W; pub const JetGetObjectInfo = thismodule.JetGetObjectInfoW; pub const JetGetTableInfo = thismodule.JetGetTableInfoW; pub const JetCreateTable = thismodule.JetCreateTableW; pub const JetCreateTableColumnIndex = thismodule.JetCreateTableColumnIndexW; pub const JetCreateTableColumnIndex2 = thismodule.JetCreateTableColumnIndex2W; pub const JetCreateTableColumnIndex3 = thismodule.JetCreateTableColumnIndex3W; pub const JetCreateTableColumnIndex4 = thismodule.JetCreateTableColumnIndex4W; pub const JetDeleteTable = thismodule.JetDeleteTableW; pub const JetRenameTable = thismodule.JetRenameTableW; pub const JetGetTableColumnInfo = thismodule.JetGetTableColumnInfoW; pub const JetGetColumnInfo = thismodule.JetGetColumnInfoW; pub const JetAddColumn = thismodule.JetAddColumnW; pub const JetDeleteColumn = thismodule.JetDeleteColumnW; pub const JetDeleteColumn2 = thismodule.JetDeleteColumn2W; pub const JetRenameColumn = thismodule.JetRenameColumnW; pub const JetSetColumnDefaultValue = thismodule.JetSetColumnDefaultValueW; pub const JetGetTableIndexInfo = thismodule.JetGetTableIndexInfoW; pub const JetGetIndexInfo = thismodule.JetGetIndexInfoW; pub const JetCreateIndex = thismodule.JetCreateIndexW; pub const JetCreateIndex2 = thismodule.JetCreateIndex2W; pub const JetCreateIndex3 = thismodule.JetCreateIndex3W; pub const JetCreateIndex4 = thismodule.JetCreateIndex4W; pub const JetDeleteIndex = thismodule.JetDeleteIndexW; pub const JetGetDatabaseInfo = thismodule.JetGetDatabaseInfoW; pub const JetGetDatabaseFileInfo = thismodule.JetGetDatabaseFileInfoW; pub const JetOpenDatabase = thismodule.JetOpenDatabaseW; pub const JetOpenTable = thismodule.JetOpenTableW; pub const JetGetCurrentIndex = thismodule.JetGetCurrentIndexW; pub const JetSetCurrentIndex = thismodule.JetSetCurrentIndexW; pub const JetSetCurrentIndex2 = thismodule.JetSetCurrentIndex2W; pub const JetSetCurrentIndex3 = thismodule.JetSetCurrentIndex3W; pub const JetSetCurrentIndex4 = thismodule.JetSetCurrentIndex4W; pub const JetCompact = thismodule.JetCompactW; pub const JetDefragment = thismodule.JetDefragmentW; pub const JetDefragment2 = thismodule.JetDefragment2W; pub const JetDefragment3 = thismodule.JetDefragment3W; pub const JetSetDatabaseSize = thismodule.JetSetDatabaseSizeW; pub const JetBackup = thismodule.JetBackupW; pub const JetBackupInstance = thismodule.JetBackupInstanceW; pub const JetRestore = thismodule.JetRestoreW; pub const JetRestore2 = thismodule.JetRestore2W; pub const JetRestoreInstance = thismodule.JetRestoreInstanceW; pub const JetGetAttachInfo = thismodule.JetGetAttachInfoW; pub const JetGetAttachInfoInstance = thismodule.JetGetAttachInfoInstanceW; pub const JetOpenFile = thismodule.JetOpenFileW; pub const JetOpenFileInstance = thismodule.JetOpenFileInstanceW; pub const JetGetLogInfo = thismodule.JetGetLogInfoW; pub const JetGetLogInfoInstance = thismodule.JetGetLogInfoInstanceW; pub const JetGetLogInfoInstance2 = thismodule.JetGetLogInfoInstance2W; pub const JetGetTruncateLogInfoInstance = thismodule.JetGetTruncateLogInfoInstanceW; pub const JetExternalRestore = thismodule.JetExternalRestoreW; pub const JetExternalRestore2 = thismodule.JetExternalRestore2W; pub const JetGetInstanceInfo = thismodule.JetGetInstanceInfoW; pub const JetOSSnapshotFreeze = thismodule.JetOSSnapshotFreezeW; pub const JetOSSnapshotGetFreezeInfo = thismodule.JetOSSnapshotGetFreezeInfoW; }, .unspecified => if (@import("builtin").is_test) struct { pub const JET_RSTMAP_ = *opaque{}; pub const CONVERT_ = *opaque{}; pub const JET_COLUMNBASE_ = *opaque{}; pub const JET_COLUMNCREATE_ = *opaque{}; pub const JET_USERDEFINEDDEFAULT_ = *opaque{}; pub const JET_CONDITIONALCOLUMN_ = *opaque{}; pub const JET_INDEXCREATE_ = *opaque{}; pub const JET_INDEXCREATE2_ = *opaque{}; pub const JET_INDEXCREATE3_ = *opaque{}; pub const JET_TABLECREATE_ = *opaque{}; pub const JET_TABLECREATE2_ = *opaque{}; pub const JET_TABLECREATE3_ = *opaque{}; pub const JET_TABLECREATE4_ = *opaque{}; pub const JET_RSTINFO_ = *opaque{}; pub const JET_SETSYSPARAM_ = *opaque{}; pub const JET_LOGINFO_ = *opaque{}; pub const JET_INSTANCE_INFO_ = *opaque{}; pub const JetInit3 = *opaque{}; pub const JetCreateInstance = *opaque{}; pub const JetCreateInstance2 = *opaque{}; pub const JetSetSystemParameter = *opaque{}; pub const JetGetSystemParameter = *opaque{}; pub const JetEnableMultiInstance = *opaque{}; pub const JetBeginSession = *opaque{}; pub const JetCreateDatabase = *opaque{}; pub const JetCreateDatabase2 = *opaque{}; pub const JetAttachDatabase = *opaque{}; pub const JetAttachDatabase2 = *opaque{}; pub const JetDetachDatabase = *opaque{}; pub const JetDetachDatabase2 = *opaque{}; pub const JetGetObjectInfo = *opaque{}; pub const JetGetTableInfo = *opaque{}; pub const JetCreateTable = *opaque{}; pub const JetCreateTableColumnIndex = *opaque{}; pub const JetCreateTableColumnIndex2 = *opaque{}; pub const JetCreateTableColumnIndex3 = *opaque{}; pub const JetCreateTableColumnIndex4 = *opaque{}; pub const JetDeleteTable = *opaque{}; pub const JetRenameTable = *opaque{}; pub const JetGetTableColumnInfo = *opaque{}; pub const JetGetColumnInfo = *opaque{}; pub const JetAddColumn = *opaque{}; pub const JetDeleteColumn = *opaque{}; pub const JetDeleteColumn2 = *opaque{}; pub const JetRenameColumn = *opaque{}; pub const JetSetColumnDefaultValue = *opaque{}; pub const JetGetTableIndexInfo = *opaque{}; pub const JetGetIndexInfo = *opaque{}; pub const JetCreateIndex = *opaque{}; pub const JetCreateIndex2 = *opaque{}; pub const JetCreateIndex3 = *opaque{}; pub const JetCreateIndex4 = *opaque{}; pub const JetDeleteIndex = *opaque{}; pub const JetGetDatabaseInfo = *opaque{}; pub const JetGetDatabaseFileInfo = *opaque{}; pub const JetOpenDatabase = *opaque{}; pub const JetOpenTable = *opaque{}; pub const JetGetCurrentIndex = *opaque{}; pub const JetSetCurrentIndex = *opaque{}; pub const JetSetCurrentIndex2 = *opaque{}; pub const JetSetCurrentIndex3 = *opaque{}; pub const JetSetCurrentIndex4 = *opaque{}; pub const JetCompact = *opaque{}; pub const JetDefragment = *opaque{}; pub const JetDefragment2 = *opaque{}; pub const JetDefragment3 = *opaque{}; pub const JetSetDatabaseSize = *opaque{}; pub const JetBackup = *opaque{}; pub const JetBackupInstance = *opaque{}; pub const JetRestore = *opaque{}; pub const JetRestore2 = *opaque{}; pub const JetRestoreInstance = *opaque{}; pub const JetGetAttachInfo = *opaque{}; pub const JetGetAttachInfoInstance = *opaque{}; pub const JetOpenFile = *opaque{}; pub const JetOpenFileInstance = *opaque{}; pub const JetGetLogInfo = *opaque{}; pub const JetGetLogInfoInstance = *opaque{}; pub const JetGetLogInfoInstance2 = *opaque{}; pub const JetGetTruncateLogInfoInstance = *opaque{}; pub const JetExternalRestore = *opaque{}; pub const JetExternalRestore2 = *opaque{}; pub const JetGetInstanceInfo = *opaque{}; pub const JetOSSnapshotFreeze = *opaque{}; pub const JetOSSnapshotGetFreezeInfo = *opaque{}; } else struct { pub const JET_RSTMAP_ = @compileError("'JET_RSTMAP_' requires that UNICODE be set to true or false in the root module"); pub const CONVERT_ = @compileError("'CONVERT_' requires that UNICODE be set to true or false in the root module"); pub const JET_COLUMNBASE_ = @compileError("'JET_COLUMNBASE_' requires that UNICODE be set to true or false in the root module"); pub const JET_COLUMNCREATE_ = @compileError("'JET_COLUMNCREATE_' requires that UNICODE be set to true or false in the root module"); pub const JET_USERDEFINEDDEFAULT_ = @compileError("'JET_USERDEFINEDDEFAULT_' requires that UNICODE be set to true or false in the root module"); pub const JET_CONDITIONALCOLUMN_ = @compileError("'JET_CONDITIONALCOLUMN_' requires that UNICODE be set to true or false in the root module"); pub const JET_INDEXCREATE_ = @compileError("'JET_INDEXCREATE_' requires that UNICODE be set to true or false in the root module"); pub const JET_INDEXCREATE2_ = @compileError("'JET_INDEXCREATE2_' requires that UNICODE be set to true or false in the root module"); pub const JET_INDEXCREATE3_ = @compileError("'JET_INDEXCREATE3_' requires that UNICODE be set to true or false in the root module"); pub const JET_TABLECREATE_ = @compileError("'JET_TABLECREATE_' requires that UNICODE be set to true or false in the root module"); pub const JET_TABLECREATE2_ = @compileError("'JET_TABLECREATE2_' requires that UNICODE be set to true or false in the root module"); pub const JET_TABLECREATE3_ = @compileError("'JET_TABLECREATE3_' requires that UNICODE be set to true or false in the root module"); pub const JET_TABLECREATE4_ = @compileError("'JET_TABLECREATE4_' requires that UNICODE be set to true or false in the root module"); pub const JET_RSTINFO_ = @compileError("'JET_RSTINFO_' requires that UNICODE be set to true or false in the root module"); pub const JET_SETSYSPARAM_ = @compileError("'JET_SETSYSPARAM_' requires that UNICODE be set to true or false in the root module"); pub const JET_LOGINFO_ = @compileError("'JET_LOGINFO_' requires that UNICODE be set to true or false in the root module"); pub const JET_INSTANCE_INFO_ = @compileError("'JET_INSTANCE_INFO_' requires that UNICODE be set to true or false in the root module"); pub const JetInit3 = @compileError("'JetInit3' requires that UNICODE be set to true or false in the root module"); pub const JetCreateInstance = @compileError("'JetCreateInstance' requires that UNICODE be set to true or false in the root module"); pub const JetCreateInstance2 = @compileError("'JetCreateInstance2' requires that UNICODE be set to true or false in the root module"); pub const JetSetSystemParameter = @compileError("'JetSetSystemParameter' requires that UNICODE be set to true or false in the root module"); pub const JetGetSystemParameter = @compileError("'JetGetSystemParameter' requires that UNICODE be set to true or false in the root module"); pub const JetEnableMultiInstance = @compileError("'JetEnableMultiInstance' requires that UNICODE be set to true or false in the root module"); pub const JetBeginSession = @compileError("'JetBeginSession' requires that UNICODE be set to true or false in the root module"); pub const JetCreateDatabase = @compileError("'JetCreateDatabase' requires that UNICODE be set to true or false in the root module"); pub const JetCreateDatabase2 = @compileError("'JetCreateDatabase2' requires that UNICODE be set to true or false in the root module"); pub const JetAttachDatabase = @compileError("'JetAttachDatabase' requires that UNICODE be set to true or false in the root module"); pub const JetAttachDatabase2 = @compileError("'JetAttachDatabase2' requires that UNICODE be set to true or false in the root module"); pub const JetDetachDatabase = @compileError("'JetDetachDatabase' requires that UNICODE be set to true or false in the root module"); pub const JetDetachDatabase2 = @compileError("'JetDetachDatabase2' requires that UNICODE be set to true or false in the root module"); pub const JetGetObjectInfo = @compileError("'JetGetObjectInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetTableInfo = @compileError("'JetGetTableInfo' requires that UNICODE be set to true or false in the root module"); pub const JetCreateTable = @compileError("'JetCreateTable' requires that UNICODE be set to true or false in the root module"); pub const JetCreateTableColumnIndex = @compileError("'JetCreateTableColumnIndex' requires that UNICODE be set to true or false in the root module"); pub const JetCreateTableColumnIndex2 = @compileError("'JetCreateTableColumnIndex2' requires that UNICODE be set to true or false in the root module"); pub const JetCreateTableColumnIndex3 = @compileError("'JetCreateTableColumnIndex3' requires that UNICODE be set to true or false in the root module"); pub const JetCreateTableColumnIndex4 = @compileError("'JetCreateTableColumnIndex4' requires that UNICODE be set to true or false in the root module"); pub const JetDeleteTable = @compileError("'JetDeleteTable' requires that UNICODE be set to true or false in the root module"); pub const JetRenameTable = @compileError("'JetRenameTable' requires that UNICODE be set to true or false in the root module"); pub const JetGetTableColumnInfo = @compileError("'JetGetTableColumnInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetColumnInfo = @compileError("'JetGetColumnInfo' requires that UNICODE be set to true or false in the root module"); pub const JetAddColumn = @compileError("'JetAddColumn' requires that UNICODE be set to true or false in the root module"); pub const JetDeleteColumn = @compileError("'JetDeleteColumn' requires that UNICODE be set to true or false in the root module"); pub const JetDeleteColumn2 = @compileError("'JetDeleteColumn2' requires that UNICODE be set to true or false in the root module"); pub const JetRenameColumn = @compileError("'JetRenameColumn' requires that UNICODE be set to true or false in the root module"); pub const JetSetColumnDefaultValue = @compileError("'JetSetColumnDefaultValue' requires that UNICODE be set to true or false in the root module"); pub const JetGetTableIndexInfo = @compileError("'JetGetTableIndexInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetIndexInfo = @compileError("'JetGetIndexInfo' requires that UNICODE be set to true or false in the root module"); pub const JetCreateIndex = @compileError("'JetCreateIndex' requires that UNICODE be set to true or false in the root module"); pub const JetCreateIndex2 = @compileError("'JetCreateIndex2' requires that UNICODE be set to true or false in the root module"); pub const JetCreateIndex3 = @compileError("'JetCreateIndex3' requires that UNICODE be set to true or false in the root module"); pub const JetCreateIndex4 = @compileError("'JetCreateIndex4' requires that UNICODE be set to true or false in the root module"); pub const JetDeleteIndex = @compileError("'JetDeleteIndex' requires that UNICODE be set to true or false in the root module"); pub const JetGetDatabaseInfo = @compileError("'JetGetDatabaseInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetDatabaseFileInfo = @compileError("'JetGetDatabaseFileInfo' requires that UNICODE be set to true or false in the root module"); pub const JetOpenDatabase = @compileError("'JetOpenDatabase' requires that UNICODE be set to true or false in the root module"); pub const JetOpenTable = @compileError("'JetOpenTable' requires that UNICODE be set to true or false in the root module"); pub const JetGetCurrentIndex = @compileError("'JetGetCurrentIndex' requires that UNICODE be set to true or false in the root module"); pub const JetSetCurrentIndex = @compileError("'JetSetCurrentIndex' requires that UNICODE be set to true or false in the root module"); pub const JetSetCurrentIndex2 = @compileError("'JetSetCurrentIndex2' requires that UNICODE be set to true or false in the root module"); pub const JetSetCurrentIndex3 = @compileError("'JetSetCurrentIndex3' requires that UNICODE be set to true or false in the root module"); pub const JetSetCurrentIndex4 = @compileError("'JetSetCurrentIndex4' requires that UNICODE be set to true or false in the root module"); pub const JetCompact = @compileError("'JetCompact' requires that UNICODE be set to true or false in the root module"); pub const JetDefragment = @compileError("'JetDefragment' requires that UNICODE be set to true or false in the root module"); pub const JetDefragment2 = @compileError("'JetDefragment2' requires that UNICODE be set to true or false in the root module"); pub const JetDefragment3 = @compileError("'JetDefragment3' requires that UNICODE be set to true or false in the root module"); pub const JetSetDatabaseSize = @compileError("'JetSetDatabaseSize' requires that UNICODE be set to true or false in the root module"); pub const JetBackup = @compileError("'JetBackup' requires that UNICODE be set to true or false in the root module"); pub const JetBackupInstance = @compileError("'JetBackupInstance' requires that UNICODE be set to true or false in the root module"); pub const JetRestore = @compileError("'JetRestore' requires that UNICODE be set to true or false in the root module"); pub const JetRestore2 = @compileError("'JetRestore2' requires that UNICODE be set to true or false in the root module"); pub const JetRestoreInstance = @compileError("'JetRestoreInstance' requires that UNICODE be set to true or false in the root module"); pub const JetGetAttachInfo = @compileError("'JetGetAttachInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetAttachInfoInstance = @compileError("'JetGetAttachInfoInstance' requires that UNICODE be set to true or false in the root module"); pub const JetOpenFile = @compileError("'JetOpenFile' requires that UNICODE be set to true or false in the root module"); pub const JetOpenFileInstance = @compileError("'JetOpenFileInstance' requires that UNICODE be set to true or false in the root module"); pub const JetGetLogInfo = @compileError("'JetGetLogInfo' requires that UNICODE be set to true or false in the root module"); pub const JetGetLogInfoInstance = @compileError("'JetGetLogInfoInstance' requires that UNICODE be set to true or false in the root module"); pub const JetGetLogInfoInstance2 = @compileError("'JetGetLogInfoInstance2' requires that UNICODE be set to true or false in the root module"); pub const JetGetTruncateLogInfoInstance = @compileError("'JetGetTruncateLogInfoInstance' requires that UNICODE be set to true or false in the root module"); pub const JetExternalRestore = @compileError("'JetExternalRestore' requires that UNICODE be set to true or false in the root module"); pub const JetExternalRestore2 = @compileError("'JetExternalRestore2' requires that UNICODE be set to true or false in the root module"); pub const JetGetInstanceInfo = @compileError("'JetGetInstanceInfo' requires that UNICODE be set to true or false in the root module"); pub const JetOSSnapshotFreeze = @compileError("'JetOSSnapshotFreeze' requires that UNICODE be set to true or false in the root module"); pub const JetOSSnapshotGetFreezeInfo = @compileError("'JetOSSnapshotGetFreezeInfo' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (8) //-------------------------------------------------------------------------------- const CHAR = @import("../foundation.zig").CHAR; const JET_API_PTR = @import("../storage/structured_storage.zig").JET_API_PTR; const JET_HANDLE = @import("../storage/structured_storage.zig").JET_HANDLE; const JET_INSTANCE = @import("../storage/structured_storage.zig").JET_INSTANCE; const JET_SESID = @import("../storage/structured_storage.zig").JET_SESID; const JET_TABLEID = @import("../storage/structured_storage.zig").JET_TABLEID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "JET_PFNSTATUS")) { _ = JET_PFNSTATUS; } if (@hasDecl(@This(), "JET_CALLBACK")) { _ = JET_CALLBACK; } if (@hasDecl(@This(), "JET_PFNDURABLECOMMITCALLBACK")) { _ = JET_PFNDURABLECOMMITCALLBACK; } if (@hasDecl(@This(), "JET_PFNREALLOC")) { _ = JET_PFNREALLOC; } @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/storage/jet.zig
const std = @import("std"); const Allocator = std.mem.Allocator; //-------------------------------------------------------------------------------------------------- const Entry = struct { idx: u32, total_risk: u16, risk: u16, }; //-------------------------------------------------------------------------------------------------- fn lessThan(context: void, a: Entry, b: Entry) std.math.Order { _ = context; return std.math.order(a.total_risk, b.total_risk); } const ToVisitQueue = std.PriorityQueue(Entry, void, lessThan); //-------------------------------------------------------------------------------------------------- const Cavern = struct { width: u32, height: u32, entries: std.ArrayList(Entry), const Self = @This(); pub fn initCapacity(allocator: Allocator, num: usize) Allocator.Error!Self { return Self{ .width = 0, .height = 0, .entries = try std.ArrayList(Entry).initCapacity(allocator, num), }; } pub fn deinit(self: Self) void { self.entries.deinit(); } }; //-------------------------------------------------------------------------------------------------- pub fn main() anyerror!void { var timer = try std.time.Timer.start(); const file = std.fs.cwd().openFile("data/day15_input.txt", .{}) catch |err| label: { std.debug.print("unable to open file: {e}\n", .{err}); const stderr = std.io.getStdErr(); break :label stderr; }; defer file.close(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = arena.allocator(); var cavern = try Cavern.initCapacity(allocator, 100 * 100); defer cavern.deinit(); { var reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); var buf: [128]u8 = undefined; // Read lines var idx: u32 = 0; while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| { if (line.len == 0) { continue; } cavern.width = @intCast(u32, line.len); // Convert line into array of ints for (line) |char| { const risk = std.fmt.charToDigit(char, 10) catch 0; const entry = Entry{ .idx = idx, .risk = risk, .total_risk = std.math.maxInt(u16), }; cavern.entries.append(entry) catch unreachable; idx += 1; } cavern.height += 1; } } var cavern2 = try Cavern.initCapacity(allocator, 500 * 500); defer cavern2.deinit(); { cavern2.width = cavern.width * 5; cavern2.height = cavern.height * 5; const dest_size: u32 = cavern2.width * cavern2.height; // Copy the first cavern but with repetitions var dest_idx: u32 = 0; while (dest_idx < dest_size) : (dest_idx += 1) { const dest_x = dest_idx % cavern2.width; const dest_y = dest_idx / cavern2.width; const source_x = dest_idx % cavern.width; const source_y = dest_y % cavern.height; const x_repeat = dest_x / cavern.width; const y_repeat = dest_y / cavern.height; const source_idx = (source_y * cavern.width) + source_x; const source_risk = cavern.entries.items[source_idx].risk; const risk_inc: u16 = @intCast(u16, x_repeat + y_repeat); const new_risk = ((source_risk + risk_inc - 1) % 9) + 1; // wrap around const entry = Entry{ .idx = dest_idx, .risk = new_risk, .total_risk = std.math.maxInt(u16), }; cavern2.entries.append(entry) catch unreachable; } } const part1_risk = search(&cavern, allocator) catch 0; std.log.info("Part 1 Found exit: Total risk {d}\n", .{part1_risk}); const part2_risk = search(&cavern2, allocator) catch 0; std.log.info("Part 2 Found exit: Total risk {d}\n", .{part2_risk}); std.log.info("Completed in {d:.2}ms\n", .{@intToFloat(f32, timer.lap()) / 1.0e+6}); } //-------------------------------------------------------------------------------------------------- fn search(cavern: *Cavern, allocator: Allocator) anyerror!u32 { //std.log.info("cavern.width: {d}", .{cavern.width}); //std.log.info("cavern.height: {d}", .{cavern.height}); //std.log.info("cavern.len: {d}", .{cavern.entries.items.len}); const start_idx = 0; const exit_idx = cavern.entries.items.len - 1; var to_visit = ToVisitQueue.init(allocator, {}); defer to_visit.deinit(); cavern.entries.items[start_idx].total_risk = 0; try to_visit.add(cavern.entries.items[start_idx]); while (to_visit.len != 0) { var visit_ptr = to_visit.remove(); const visit_idx = visit_ptr.idx; const x = visit_ptr.idx % cavern.width; const y = visit_ptr.idx / cavern.width; const current_risk = visit_ptr.total_risk; //std.log.info("Visiting: idx:{d} - {}x{}\n", .{ visit_idx, x, y }); if (visit_idx == exit_idx) { return current_risk; } // for each neighbour, check if we `can` move there const north_idx: ?u32 = if (y > 0) visit_idx - cavern.width else null; const south_idx: ?u32 = if (y < cavern.height - 1) visit_idx + cavern.width else null; const west_idx: ?u32 = if (x > 0) visit_idx - 1 else null; const east_idx: ?u32 = if (x < cavern.width - 1) visit_idx + 1 else null; // then move there only if it's currently the cheapest route to there if (north_idx) |idx| { try move_if_cheaper(idx, cavern, &to_visit, current_risk); } if (south_idx) |idx| { try move_if_cheaper(idx, cavern, &to_visit, current_risk); } if (west_idx) |idx| { try move_if_cheaper(idx, cavern, &to_visit, current_risk); } if (east_idx) |idx| { try move_if_cheaper(idx, cavern, &to_visit, current_risk); } } return 0; //std.log.info("Part 2: {d}", .{calc_min_max_diff(map, template_slice.?)}); } //-------------------------------------------------------------------------------------------------- fn move_if_cheaper(to_idx: u32, cavern: *Cavern, to_visit: *ToVisitQueue, current_risk: u16) anyerror!void { const risk = cavern.entries.items[to_idx].risk; const new_total = current_risk + risk; if (new_total < cavern.entries.items[to_idx].total_risk) { cavern.entries.items[to_idx].total_risk = new_total; // TODO: what happens if we already marked this place to visit try to_visit.add(cavern.entries.items[to_idx]); } } //--------------------------------------------------------------------------------------------------
src/day15.zig
const std = @import("std"); pub usingnamespace @cImport({ @cInclude("SDL.h"); }); pub fn init(flags: c_uint) !void { var errCode = SDL_Init(flags); if (errCode != 0) { std.debug.warn("SDL: Failed to init: {s}\n", .{SDL_GetError()}); SDL_ClearError(); return error.InitError; } } pub fn deinit() void { SDL_Quit(); } pub const Color = packed struct { r: u8, g: u8, b: u8, a: u8 = 255, pub const black = Color{ .r = 0, .g = 0, .b = 0 }; pub const white = Color{ .r = 255, .g = 255, .b = 255 }; }; pub const Window = struct { window: *SDL_Window, pub fn init(title: [*:0]const u8, x: c_int, y: c_int, w: c_int, h: c_int, flags: c_uint) anyerror!Window { var raw_window = SDL_CreateWindow(title, x, y, w, h, flags); if (raw_window) |window| { return Window{ .window = window }; } std.debug.warn("SDL: Failed to create window: {s}\n", .{SDL_GetError()}); return error.CreateWindow; } pub fn deinit(self: Window) void { SDL_DestroyWindow(self.window); } pub fn getSurface(self: Window) !*SDL_Surface { if (SDL_GetWindowSurface(self.window)) |surface| { return surface; } std.debug.warn("SDL: Failed to get window surface: {s}\n", .{SDL_GetError()}); return error.GetWindowSurface; } }; pub const Renderer = struct { renderer: *SDL_Renderer, pub const Texture = struct { texture: *SDL_Texture, pub fn deinit(self: *Texture) void { SDL_DestroyTexture(self.texture); } }; pub fn init(window: *Window, ind: i32, flags: u32) !Renderer { if (SDL_CreateRenderer(window.window, ind, flags)) |renderer| { return Renderer{ .renderer = renderer }; } std.debug.warn("SDL: Failed to create renderer: {s}\n", .{SDL_GetError()}); return error.InitRenderer; } pub fn deinit(self: Renderer) void { SDL_DestroyRenderer(self.renderer); } pub fn info(self: Renderer) !SDL_RendererInfo { var raw_info: SDL_RendererInfo = undefined; if (SDL_GetRendererInfo(self.renderer, &raw_info) != 0) { std.debug.warn("SDL: Failed to get renderer info: {s}\n", .{SDL_GetError()}); return error.GetRendererInfo; } return raw_info; } pub fn clear(self: Renderer) !void { if (SDL_RenderClear(self.renderer) != 0) { std.debug.warn("SDL: Failed to render clear: {s}\n", .{SDL_GetError()}); return error.RenderClear; } } pub fn setDrawColor(self: Renderer, c: Color) !void { if (SDL_SetRenderDrawColor(self.renderer, c.r, c.g, c.b, c.a) != 0) { std.debug.warn("SDL: Failed to set draw color: {s}\n", .{SDL_GetError()}); return error.SetDrawColor; } } pub fn fillRect(self: Renderer, rect: ?*const SDL_Rect) !void { if (SDL_RenderFillRect(self.renderer, rect) != 0) { std.debug.warn("SDL: Failed to fill rect: {s}\n", .{SDL_GetError()}); return error.FillRect; } } pub fn createTextureFromSurface(self: *Renderer, surface: *Surface) !Texture { var maybe_texture = SDL_CreateTextureFromSurface(self.renderer, surface.surface); if (maybe_texture) |texture| { return Texture{ .texture = texture }; } std.debug.warn("SDL: Failed to create texture from surface: {s}\n", .{SDL_GetError()}); return error.CreateTextureFromSurface; } pub fn present(self: Renderer) void { SDL_RenderPresent(self.renderer); } }; pub const AudioDevice = struct { deviceId: SDL_AudioDeviceID, spec: SDL_AudioSpec, pub fn init(device: ?[*:0]const u8, isCapture: bool, desired: SDL_AudioSpec, allowedChanges: i32) !AudioDevice { var obtained: SDL_AudioSpec = undefined; var deviceId = SDL_OpenAudioDevice(device, @boolToInt(isCapture), &desired, &obtained, allowedChanges); if (deviceId > 0) { return AudioDevice{ .deviceId = deviceId, .spec = obtained }; } else { std.debug.warn("SDL: Failed to open audio device: {s}\n", .{SDL_GetError()}); return error.OpenAudioDevice; } } pub fn deinit(self: AudioDevice) void { SDL_CloseAudioDevice(self.deviceId); } pub fn play(self: AudioDevice) void { SDL_PauseAudioDevice(self.deviceId, 0); } pub fn pause(self: AudioDevice) void { SDL_PauseAudioDevice(self.deviceId, 1); } }; pub fn mixAudio(comptime T: type, dst: []T, src: []const T, format: SDL_AudioFormat, volume: u7) void { std.debug.assert(src.len <= dst.len); std.debug.assert(src.len <= std.math.maxInt(u32)); SDL_MixAudioFormat( @ptrCast([*c]u8, dst.ptr), @ptrCast([*c]const u8, src.ptr), format, @intCast(u32, src.len), @intCast(c_int, volume), ); } /// /// Returns the number of ms since start of the game /// pub fn ticks() u32 { return SDL_GetTicks(); } pub fn getPerformanceCounter() u64 { return SDL_GetPerformanceCounter(); } pub fn getPerformanceFrequency() u64 { return SDL_GetPerformanceFrequency(); } pub const RWops = struct { rwops: *SDL_RWops, pub fn fromConstMem(mem: [*:0]const u8, len: usize) !RWops { if (SDL_RWFromConstMem(@ptrCast(*const c_void, mem), @intCast(c_int, len))) |rwops| { return RWops{ .rwops = rwops }; } std.debug.warn("SDL: Failed to create RWops from const mem: {s}\n", .{SDL_GetError()}); return error.RWopsCreateFail; } pub fn close(self: *RWops) !void { if (SDL_RWclose(self.rwops) != 0) { std.debug.warn("SDL: Failed to close RWops: {s}\n", .{SDL_GetError()}); return error.RWopsCloseFail; } } }; pub const Surface = struct { surface: *SDL_Surface, pub fn createRGBFrom( pixels: ?*c_void, width: c_int, height: c_int, depth: c_int, pitch: c_int, rMask: u32, gMask: u32, bMask: u32, aMask: u32, ) !Surface { var maybe_surface = SDL_CreateRGBSurfaceFrom(pixels, width, height, depth, pitch, rMask, gMask, bMask, aMask); if (maybe_surface) |surface| { return Surface{ .surface = surface }; } std.debug.warn("SDL: Failed to create surface from pixels: {s}\n", .{SDL_GetError()}); return error.CreateSurfaceFrom; } pub fn deinit(self: *Surface) void { SDL_FreeSurface(self.surface); } };
src/sdl.zig
/// The function fiatPoly1305AddcarryxU26 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 fiatPoly1305AddcarryxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u32 = ((@intCast(u32, arg1) + arg2) + arg3); const x2: u32 = (x1 & 0x3ffffff); const x3: u1 = @intCast(u1, (x1 >> 26)); out1.* = x2; out2.* = x3; } /// The function fiatPoly1305SubborrowxU26 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 fiatPoly1305SubborrowxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: i32 = @intCast(i32, (@intCast(i64, @intCast(i32, (@intCast(i64, arg2) - @intCast(i64, arg1)))) - @intCast(i64, arg3))); const x2: i1 = @intCast(i1, (x1 >> 26)); const x3: u32 = @intCast(u32, (@intCast(i64, x1) & @intCast(i64, 0x3ffffff))); out1.* = x3; out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2))); } /// The function fiatPoly1305CmovznzU32 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 fiatPoly1305CmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u1 = (~(~arg1)); const x2: u32 = @intCast(u32, (@intCast(i64, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i64, 0xffffffff))); const x3: u32 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function fiatPoly1305CarryMul 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 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] /// arg2: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] pub fn fiatPoly1305CarryMul(out1: *[5]u32, arg1: [5]u32, arg2: [5]u32) void { const x1: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, ((arg2[4]) * 0x5))); const x2: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, ((arg2[3]) * 0x5))); const x3: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, ((arg2[2]) * 0x5))); const x4: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, ((arg2[1]) * 0x5))); const x5: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, ((arg2[4]) * 0x5))); const x6: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, ((arg2[3]) * 0x5))); const x7: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, ((arg2[2]) * 0x5))); const x8: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, ((arg2[4]) * 0x5))); const x9: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, ((arg2[3]) * 0x5))); const x10: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, ((arg2[4]) * 0x5))); const x11: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[0]))); const x12: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[1]))); const x13: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[0]))); const x14: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[2]))); const x15: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[1]))); const x16: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[0]))); const x17: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[3]))); const x18: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[2]))); const x19: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[1]))); const x20: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[0]))); const x21: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[4]))); const x22: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[3]))); const x23: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[2]))); const x24: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[1]))); const x25: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[0]))); const x26: u64 = (x25 + (x10 + (x9 + (x7 + x4)))); const x27: u64 = (x26 >> 26); const x28: u32 = @intCast(u32, (x26 & @intCast(u64, 0x3ffffff))); const x29: u64 = (x21 + (x17 + (x14 + (x12 + x11)))); const x30: u64 = (x22 + (x18 + (x15 + (x13 + x1)))); const x31: u64 = (x23 + (x19 + (x16 + (x5 + x2)))); const x32: u64 = (x24 + (x20 + (x8 + (x6 + x3)))); const x33: u64 = (x27 + x32); const x34: u64 = (x33 >> 26); const x35: u32 = @intCast(u32, (x33 & @intCast(u64, 0x3ffffff))); const x36: u64 = (x34 + x31); const x37: u64 = (x36 >> 26); const x38: u32 = @intCast(u32, (x36 & @intCast(u64, 0x3ffffff))); const x39: u64 = (x37 + x30); const x40: u64 = (x39 >> 26); const x41: u32 = @intCast(u32, (x39 & @intCast(u64, 0x3ffffff))); const x42: u64 = (x40 + x29); const x43: u32 = @intCast(u32, (x42 >> 26)); const x44: u32 = @intCast(u32, (x42 & @intCast(u64, 0x3ffffff))); const x45: u64 = (@intCast(u64, x43) * @intCast(u64, 0x5)); const x46: u64 = (@intCast(u64, x28) + x45); const x47: u32 = @intCast(u32, (x46 >> 26)); const x48: u32 = @intCast(u32, (x46 & @intCast(u64, 0x3ffffff))); const x49: u32 = (x47 + x35); const x50: u1 = @intCast(u1, (x49 >> 26)); const x51: u32 = (x49 & 0x3ffffff); const x52: u32 = (@intCast(u32, x50) + x38); out1[0] = x48; out1[1] = x51; out1[2] = x52; out1[3] = x41; out1[4] = x44; } /// The function fiatPoly1305CarrySquare 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 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] pub fn fiatPoly1305CarrySquare(out1: *[5]u32, arg1: [5]u32) void { const x1: u32 = ((arg1[4]) * 0x5); const x2: u32 = (x1 * 0x2); const x3: u32 = ((arg1[4]) * 0x2); const x4: u32 = ((arg1[3]) * 0x5); const x5: u32 = (x4 * 0x2); const x6: u32 = ((arg1[3]) * 0x2); const x7: u32 = ((arg1[2]) * 0x2); const x8: u32 = ((arg1[1]) * 0x2); const x9: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x1)); const x10: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x2)); const x11: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x4)); const x12: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x2)); const x13: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x5)); const x14: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg1[2]))); const x15: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x2)); const x16: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x6)); const x17: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x7)); const x18: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg1[1]))); const x19: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x3)); const x20: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x6)); const x21: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x7)); const x22: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x8)); const x23: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg1[0]))); const x24: u64 = (x23 + (x15 + x13)); const x25: u64 = (x24 >> 26); const x26: u32 = @intCast(u32, (x24 & @intCast(u64, 0x3ffffff))); const x27: u64 = (x19 + (x16 + x14)); const x28: u64 = (x20 + (x17 + x9)); const x29: u64 = (x21 + (x18 + x10)); const x30: u64 = (x22 + (x12 + x11)); const x31: u64 = (x25 + x30); const x32: u64 = (x31 >> 26); const x33: u32 = @intCast(u32, (x31 & @intCast(u64, 0x3ffffff))); const x34: u64 = (x32 + x29); const x35: u64 = (x34 >> 26); const x36: u32 = @intCast(u32, (x34 & @intCast(u64, 0x3ffffff))); const x37: u64 = (x35 + x28); const x38: u64 = (x37 >> 26); const x39: u32 = @intCast(u32, (x37 & @intCast(u64, 0x3ffffff))); const x40: u64 = (x38 + x27); const x41: u32 = @intCast(u32, (x40 >> 26)); const x42: u32 = @intCast(u32, (x40 & @intCast(u64, 0x3ffffff))); const x43: u64 = (@intCast(u64, x41) * @intCast(u64, 0x5)); const x44: u64 = (@intCast(u64, x26) + x43); const x45: u32 = @intCast(u32, (x44 >> 26)); const x46: u32 = @intCast(u32, (x44 & @intCast(u64, 0x3ffffff))); const x47: u32 = (x45 + x33); const x48: u1 = @intCast(u1, (x47 >> 26)); const x49: u32 = (x47 & 0x3ffffff); const x50: u32 = (@intCast(u32, x48) + x36); out1[0] = x46; out1[1] = x49; out1[2] = x50; out1[3] = x39; out1[4] = x42; } /// The function fiatPoly1305Carry reduces a field element. /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] pub fn fiatPoly1305Carry(out1: *[5]u32, arg1: [5]u32) void { const x1: u32 = (arg1[0]); const x2: u32 = ((x1 >> 26) + (arg1[1])); const x3: u32 = ((x2 >> 26) + (arg1[2])); const x4: u32 = ((x3 >> 26) + (arg1[3])); const x5: u32 = ((x4 >> 26) + (arg1[4])); const x6: u32 = ((x1 & 0x3ffffff) + ((x5 >> 26) * 0x5)); const x7: u32 = (@intCast(u32, @intCast(u1, (x6 >> 26))) + (x2 & 0x3ffffff)); const x8: u32 = (x6 & 0x3ffffff); const x9: u32 = (x7 & 0x3ffffff); const x10: u32 = (@intCast(u32, @intCast(u1, (x7 >> 26))) + (x3 & 0x3ffffff)); const x11: u32 = (x4 & 0x3ffffff); const x12: u32 = (x5 & 0x3ffffff); out1[0] = x8; out1[1] = x9; out1[2] = x10; out1[3] = x11; out1[4] = x12; } /// The function fiatPoly1305Add adds two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// arg2: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] pub fn fiatPoly1305Add(out1: *[5]u32, arg1: [5]u32, arg2: [5]u32) void { const x1: u32 = ((arg1[0]) + (arg2[0])); const x2: u32 = ((arg1[1]) + (arg2[1])); const x3: u32 = ((arg1[2]) + (arg2[2])); const x4: u32 = ((arg1[3]) + (arg2[3])); const x5: u32 = ((arg1[4]) + (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function fiatPoly1305Sub subtracts two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// arg2: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] pub fn fiatPoly1305Sub(out1: *[5]u32, arg1: [5]u32, arg2: [5]u32) void { const x1: u32 = ((0x7fffff6 + (arg1[0])) - (arg2[0])); const x2: u32 = ((0x7fffffe + (arg1[1])) - (arg2[1])); const x3: u32 = ((0x7fffffe + (arg1[2])) - (arg2[2])); const x4: u32 = ((0x7fffffe + (arg1[3])) - (arg2[3])); const x5: u32 = ((0x7fffffe + (arg1[4])) - (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function fiatPoly1305Opp negates a field element. /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] pub fn fiatPoly1305Opp(out1: *[5]u32, arg1: [5]u32) void { const x1: u32 = (0x7fffff6 - (arg1[0])); const x2: u32 = (0x7fffffe - (arg1[1])); const x3: u32 = (0x7fffffe - (arg1[2])); const x4: u32 = (0x7fffffe - (arg1[3])); const x5: u32 = (0x7fffffe - (arg1[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function fiatPoly1305Selectznz 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]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatPoly1305Selectznz(out1: *[5]u32, arg1: u1, arg2: [5]u32, arg3: [5]u32) void { var x1: u32 = undefined; fiatPoly1305CmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; fiatPoly1305CmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; fiatPoly1305CmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; fiatPoly1305CmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; fiatPoly1305CmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function fiatPoly1305ToBytes 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..16] /// /// Input Bounds: /// arg1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] /// 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 ~> 0x3]] pub fn fiatPoly1305ToBytes(out1: *[17]u8, arg1: [5]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatPoly1305SubborrowxU26(&x1, &x2, 0x0, (arg1[0]), 0x3fffffb); var x3: u32 = undefined; var x4: u1 = undefined; fiatPoly1305SubborrowxU26(&x3, &x4, x2, (arg1[1]), 0x3ffffff); var x5: u32 = undefined; var x6: u1 = undefined; fiatPoly1305SubborrowxU26(&x5, &x6, x4, (arg1[2]), 0x3ffffff); var x7: u32 = undefined; var x8: u1 = undefined; fiatPoly1305SubborrowxU26(&x7, &x8, x6, (arg1[3]), 0x3ffffff); var x9: u32 = undefined; var x10: u1 = undefined; fiatPoly1305SubborrowxU26(&x9, &x10, x8, (arg1[4]), 0x3ffffff); var x11: u32 = undefined; fiatPoly1305CmovznzU32(&x11, x10, @intCast(u32, 0x0), 0xffffffff); var x12: u32 = undefined; var x13: u1 = undefined; fiatPoly1305AddcarryxU26(&x12, &x13, 0x0, x1, (x11 & 0x3fffffb)); var x14: u32 = undefined; var x15: u1 = undefined; fiatPoly1305AddcarryxU26(&x14, &x15, x13, x3, (x11 & 0x3ffffff)); var x16: u32 = undefined; var x17: u1 = undefined; fiatPoly1305AddcarryxU26(&x16, &x17, x15, x5, (x11 & 0x3ffffff)); var x18: u32 = undefined; var x19: u1 = undefined; fiatPoly1305AddcarryxU26(&x18, &x19, x17, x7, (x11 & 0x3ffffff)); var x20: u32 = undefined; var x21: u1 = undefined; fiatPoly1305AddcarryxU26(&x20, &x21, x19, x9, (x11 & 0x3ffffff)); const x22: u32 = (x18 << 6); const x23: u32 = (x16 << 4); const x24: u32 = (x14 << 2); const x25: u8 = @intCast(u8, (x12 & @intCast(u32, 0xff))); const x26: u32 = (x12 >> 8); const x27: u8 = @intCast(u8, (x26 & @intCast(u32, 0xff))); const x28: u32 = (x26 >> 8); const x29: u8 = @intCast(u8, (x28 & @intCast(u32, 0xff))); const x30: u8 = @intCast(u8, (x28 >> 8)); const x31: u32 = (x24 + @intCast(u32, x30)); const x32: u8 = @intCast(u8, (x31 & @intCast(u32, 0xff))); const x33: u32 = (x31 >> 8); const x34: u8 = @intCast(u8, (x33 & @intCast(u32, 0xff))); const x35: u32 = (x33 >> 8); const x36: u8 = @intCast(u8, (x35 & @intCast(u32, 0xff))); const x37: u8 = @intCast(u8, (x35 >> 8)); const x38: u32 = (x23 + @intCast(u32, x37)); const x39: u8 = @intCast(u8, (x38 & @intCast(u32, 0xff))); const x40: u32 = (x38 >> 8); const x41: u8 = @intCast(u8, (x40 & @intCast(u32, 0xff))); const x42: u32 = (x40 >> 8); const x43: u8 = @intCast(u8, (x42 & @intCast(u32, 0xff))); const x44: u8 = @intCast(u8, (x42 >> 8)); const x45: u32 = (x22 + @intCast(u32, x44)); const x46: u8 = @intCast(u8, (x45 & @intCast(u32, 0xff))); const x47: u32 = (x45 >> 8); const x48: u8 = @intCast(u8, (x47 & @intCast(u32, 0xff))); const x49: u32 = (x47 >> 8); const x50: u8 = @intCast(u8, (x49 & @intCast(u32, 0xff))); const x51: u8 = @intCast(u8, (x49 >> 8)); const x52: u8 = @intCast(u8, (x20 & @intCast(u32, 0xff))); const x53: u32 = (x20 >> 8); const x54: u8 = @intCast(u8, (x53 & @intCast(u32, 0xff))); const x55: u32 = (x53 >> 8); const x56: u8 = @intCast(u8, (x55 & @intCast(u32, 0xff))); const x57: u8 = @intCast(u8, (x55 >> 8)); out1[0] = x25; out1[1] = x27; out1[2] = x29; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x39; out1[7] = x41; out1[8] = x43; out1[9] = x46; out1[10] = x48; out1[11] = x50; out1[12] = x51; out1[13] = x52; out1[14] = x54; out1[15] = x56; out1[16] = x57; } /// The function fiatPoly1305FromBytes 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 ~> 0x3]] /// Output Bounds: /// out1: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] pub fn fiatPoly1305FromBytes(out1: *[5]u32, arg1: [17]u8) void { const x1: u32 = (@intCast(u32, (arg1[16])) << 24); const x2: u32 = (@intCast(u32, (arg1[15])) << 16); const x3: u32 = (@intCast(u32, (arg1[14])) << 8); const x4: u8 = (arg1[13]); const x5: u32 = (@intCast(u32, (arg1[12])) << 18); const x6: u32 = (@intCast(u32, (arg1[11])) << 10); const x7: u32 = (@intCast(u32, (arg1[10])) << 2); const x8: u32 = (@intCast(u32, (arg1[9])) << 20); const x9: u32 = (@intCast(u32, (arg1[8])) << 12); const x10: u32 = (@intCast(u32, (arg1[7])) << 4); const x11: u32 = (@intCast(u32, (arg1[6])) << 22); const x12: u32 = (@intCast(u32, (arg1[5])) << 14); const x13: u32 = (@intCast(u32, (arg1[4])) << 6); const x14: u32 = (@intCast(u32, (arg1[3])) << 24); const x15: u32 = (@intCast(u32, (arg1[2])) << 16); const x16: u32 = (@intCast(u32, (arg1[1])) << 8); const x17: u8 = (arg1[0]); const x18: u32 = (x16 + @intCast(u32, x17)); const x19: u32 = (x15 + x18); const x20: u32 = (x14 + x19); const x21: u32 = (x20 & 0x3ffffff); const x22: u8 = @intCast(u8, (x20 >> 26)); const x23: u32 = (x13 + @intCast(u32, x22)); const x24: u32 = (x12 + x23); const x25: u32 = (x11 + x24); const x26: u32 = (x25 & 0x3ffffff); const x27: u8 = @intCast(u8, (x25 >> 26)); const x28: u32 = (x10 + @intCast(u32, x27)); const x29: u32 = (x9 + x28); const x30: u32 = (x8 + x29); const x31: u32 = (x30 & 0x3ffffff); const x32: u8 = @intCast(u8, (x30 >> 26)); const x33: u32 = (x7 + @intCast(u32, x32)); const x34: u32 = (x6 + x33); const x35: u32 = (x5 + x34); const x36: u32 = (x3 + @intCast(u32, x4)); const x37: u32 = (x2 + x36); const x38: u32 = (x1 + x37); out1[0] = x21; out1[1] = x26; out1[2] = x31; out1[3] = x35; out1[4] = x38; }
fiat-zig/src/poly1305_32.zig
pub const max_touchpoints = 8; pub const max_mousebuttons = 3; pub const max_keycodes = 512; pub const EventType = extern enum(i32) { INVALID, KEY_DOWN, KEY_UP, CHAR, MOUSE_DOWN, MOUSE_UP, MOUSE_SCROLL, MOUSE_MOVE, MOUSE_ENTER, MOUSE_LEAVE, TOUCHES_BEGAN, TOUCHES_MOVED, TOUCHES_ENDED, TOUCHES_CANCELLED, RESIZED, ICONIFIED, RESTORED, SUSPENDED, RESUMED, UPDATE_CURSOR, QUIT_REQUESTED, CLIPBOARD_PASTED, FILES_DROPPED, NUM, }; pub const Keycode = extern enum(i32) { INVALID = 0, SPACE = 32, APOSTROPHE = 39, COMMA = 44, MINUS = 45, PERIOD = 46, SLASH = 47, _0 = 48, _1 = 49, _2 = 50, _3 = 51, _4 = 52, _5 = 53, _6 = 54, _7 = 55, _8 = 56, _9 = 57, SEMICOLON = 59, EQUAL = 61, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LEFT_BRACKET = 91, BACKSLASH = 92, RIGHT_BRACKET = 93, GRAVE_ACCENT = 96, WORLD_1 = 161, WORLD_2 = 162, ESCAPE = 256, ENTER = 257, TAB = 258, BACKSPACE = 259, INSERT = 260, DELETE = 261, RIGHT = 262, LEFT = 263, DOWN = 264, UP = 265, PAGE_UP = 266, PAGE_DOWN = 267, HOME = 268, END = 269, CAPS_LOCK = 280, SCROLL_LOCK = 281, NUM_LOCK = 282, PRINT_SCREEN = 283, PAUSE = 284, F1 = 290, F2 = 291, F3 = 292, F4 = 293, F5 = 294, F6 = 295, F7 = 296, F8 = 297, F9 = 298, F10 = 299, F11 = 300, F12 = 301, F13 = 302, F14 = 303, F15 = 304, F16 = 305, F17 = 306, F18 = 307, F19 = 308, F20 = 309, F21 = 310, F22 = 311, F23 = 312, F24 = 313, F25 = 314, KP_0 = 320, KP_1 = 321, KP_2 = 322, KP_3 = 323, KP_4 = 324, KP_5 = 325, KP_6 = 326, KP_7 = 327, KP_8 = 328, KP_9 = 329, KP_DECIMAL = 330, KP_DIVIDE = 331, KP_MULTIPLY = 332, KP_SUBTRACT = 333, KP_ADD = 334, KP_ENTER = 335, KP_EQUAL = 336, LEFT_SHIFT = 340, LEFT_CONTROL = 341, LEFT_ALT = 342, LEFT_SUPER = 343, RIGHT_SHIFT = 344, RIGHT_CONTROL = 345, RIGHT_ALT = 346, RIGHT_SUPER = 347, MENU = 348, }; pub const Touchpoint = extern struct { identifier: usize = 0, pos_x: f32 = 0.0, pos_y: f32 = 0.0, changed: bool = false, }; pub const Mousebutton = extern enum(i32) { LEFT = 0, RIGHT = 1, MIDDLE = 2, INVALID = 256, }; pub const modifier_shift = 1; pub const modifier_ctrl = 2; pub const modifier_alt = 4; pub const modifier_super = 8; pub const Event = extern struct { frame_count: u64 = 0, type: EventType = .INVALID, key_code: Keycode = .INVALID, char_code: u32 = 0, key_repeat: bool = false, modifiers: u32 = 0, mouse_button: Mousebutton = .LEFT, mouse_x: f32 = 0.0, mouse_y: f32 = 0.0, mouse_dx: f32 = 0.0, mouse_dy: f32 = 0.0, scroll_x: f32 = 0.0, scroll_y: f32 = 0.0, num_touches: i32 = 0, touches: [8]Touchpoint = [_]Touchpoint{.{}} ** 8, window_width: i32 = 0, window_height: i32 = 0, framebuffer_width: i32 = 0, framebuffer_height: i32 = 0, }; pub const Desc = extern struct { init_cb: ?fn() callconv(.C) void = null, frame_cb: ?fn() callconv(.C) void = null, cleanup_cb: ?fn() callconv(.C) void = null, event_cb: ?fn([*c]const Event) callconv(.C) void = null, fail_cb: ?fn([*c]const u8) callconv(.C) void = null, user_data: ?*c_void = null, init_userdata_cb: ?fn(?*c_void) callconv(.C) void = null, frame_userdata_cb: ?fn(?*c_void) callconv(.C) void = null, cleanup_userdata_cb: ?fn(?*c_void) callconv(.C) void = null, event_userdata_cb: ?fn([*c]const Event, ?*c_void) callconv(.C) void = null, fail_userdata_cb: ?fn([*c]const u8, ?*c_void) callconv(.C) void = null, width: i32 = 0, height: i32 = 0, sample_count: i32 = 0, swap_interval: i32 = 0, high_dpi: bool = false, fullscreen: bool = false, alpha: bool = false, window_title: [*c]const u8 = null, user_cursor: bool = false, enable_clipboard: bool = false, clipboard_size: i32 = 0, enable_dragndrop: bool = false, max_dropped_files: i32 = 0, max_dropped_file_path_length: i32 = 0, html5_canvas_name: [*c]const u8 = null, html5_canvas_resize: bool = false, html5_preserve_drawing_buffer: bool = false, html5_premultiplied_alpha: bool = false, html5_ask_leave_site: bool = false, ios_keyboard_resizes_canvas: bool = false, gl_force_gles2: bool = false, }; pub const Html5FetchError = extern enum(i32) { FETCH_ERROR_NO_ERROR, FETCH_ERROR_BUFFER_TOO_SMALL, FETCH_ERROR_OTHER, }; pub const Html5FetchResponse = extern struct { succeeded: bool = false, error_code: Html5FetchError = .FETCH_ERROR_NO_ERROR, file_index: i32 = 0, fetched_size: u32 = 0, buffer_ptr: ?*c_void = null, buffer_size: u32 = 0, user_data: ?*c_void = null, }; pub const Html5FetchRequest = extern struct { dropped_file_index: i32 = 0, callback: ?fn([*c]const Html5FetchResponse) callconv(.C) void = null, buffer_ptr: ?*c_void = null, buffer_size: u32 = 0, user_data: ?*c_void = null, }; pub extern fn sapp_isvalid() bool; pub inline fn isvalid() bool { return sapp_isvalid(); } pub extern fn sapp_width() i32; pub inline fn width() i32 { return sapp_width(); } pub extern fn sapp_widthf() f32; pub inline fn widthf() f32 { return sapp_widthf(); } pub extern fn sapp_height() i32; pub inline fn height() i32 { return sapp_height(); } pub extern fn sapp_heightf() f32; pub inline fn heightf() f32 { return sapp_heightf(); } pub extern fn sapp_color_format() i32; pub inline fn colorFormat() i32 { return sapp_color_format(); } pub extern fn sapp_depth_format() i32; pub inline fn depthFormat() i32 { return sapp_depth_format(); } pub extern fn sapp_sample_count() i32; pub inline fn sampleCount() i32 { return sapp_sample_count(); } pub extern fn sapp_high_dpi() bool; pub inline fn highDpi() bool { return sapp_high_dpi(); } pub extern fn sapp_dpi_scale() f32; pub inline fn dpiScale() f32 { return sapp_dpi_scale(); } pub extern fn sapp_show_keyboard(bool) void; pub inline fn showKeyboard(show: bool) void { sapp_show_keyboard(show); } pub extern fn sapp_keyboard_shown() bool; pub inline fn keyboardShown() bool { return sapp_keyboard_shown(); } pub extern fn sapp_is_fullscreen() bool; pub inline fn isFullscreen() bool { return sapp_is_fullscreen(); } pub extern fn sapp_toggle_fullscreen() void; pub inline fn toggleFullscreen() void { sapp_toggle_fullscreen(); } pub extern fn sapp_show_mouse(bool) void; pub inline fn showMouse(show: bool) void { sapp_show_mouse(show); } pub extern fn sapp_mouse_shown() bool; pub inline fn mouseShown() bool { return sapp_mouse_shown(); } pub extern fn sapp_lock_mouse(bool) void; pub inline fn lockMouse(lock: bool) void { sapp_lock_mouse(lock); } pub extern fn sapp_mouse_locked() bool; pub inline fn mouseLocked() bool { return sapp_mouse_locked(); } pub extern fn sapp_userdata() ?*c_void; pub inline fn userdata() ?*c_void { return sapp_userdata(); } pub extern fn sapp_query_desc() Desc; pub inline fn queryDesc() Desc { return sapp_query_desc(); } pub extern fn sapp_request_quit() void; pub inline fn requestQuit() void { sapp_request_quit(); } pub extern fn sapp_cancel_quit() void; pub inline fn cancelQuit() void { sapp_cancel_quit(); } pub extern fn sapp_quit() void; pub inline fn quit() void { sapp_quit(); } pub extern fn sapp_consume_event() void; pub inline fn consumeEvent() void { sapp_consume_event(); } pub extern fn sapp_frame_count() u64; pub inline fn frameCount() u64 { return sapp_frame_count(); } pub extern fn sapp_set_clipboard_string([*c]const u8) void; pub inline fn setClipboardString(str: [:0]const u8) void { sapp_set_clipboard_string(@ptrCast([*c]const u8,str)); } pub extern fn sapp_get_clipboard_string() [*c]const u8; pub inline fn getClipboardString() [:0]const u8 { return sapp_get_clipboard_string(); } pub extern fn sapp_set_window_title([*c]const u8) void; pub inline fn setWindowTitle(str: [:0]const u8) void { sapp_set_window_title(@ptrCast([*c]const u8,str)); } pub extern fn sapp_get_num_dropped_files() i32; pub inline fn getNumDroppedFiles() i32 { return sapp_get_num_dropped_files(); } pub extern fn sapp_get_dropped_file_path(i32) [*c]const u8; pub inline fn getDroppedFilePath(index: i32) [:0]const u8 { return sapp_get_dropped_file_path(index); } pub extern fn sapp_run([*c]const Desc) void; pub inline fn run(desc: Desc) void { sapp_run(&desc); } pub extern fn sapp_gles2() bool; pub inline fn gles2() bool { return sapp_gles2(); } pub extern fn sapp_html5_ask_leave_site(bool) void; pub inline fn html5AskLeaveSite(ask: bool) void { sapp_html5_ask_leave_site(ask); } pub extern fn sapp_html5_get_dropped_file_size(i32) u32; pub inline fn html5GetDroppedFileSize(index: i32) u32 { return sapp_html5_get_dropped_file_size(index); } pub extern fn sapp_html5_fetch_dropped_file([*c]const Html5FetchRequest) void; pub inline fn html5FetchDroppedFile(request: Html5FetchRequest) void { sapp_html5_fetch_dropped_file(&request); } pub extern fn sapp_metal_get_device() ?*const c_void; pub inline fn metalGetDevice() ?*const c_void { return sapp_metal_get_device(); } pub extern fn sapp_metal_get_renderpass_descriptor() ?*const c_void; pub inline fn metalGetRenderpassDescriptor() ?*const c_void { return sapp_metal_get_renderpass_descriptor(); } pub extern fn sapp_metal_get_drawable() ?*const c_void; pub inline fn metalGetDrawable() ?*const c_void { return sapp_metal_get_drawable(); } pub extern fn sapp_macos_get_window() ?*const c_void; pub inline fn macosGetWindow() ?*const c_void { return sapp_macos_get_window(); } pub extern fn sapp_ios_get_window() ?*const c_void; pub inline fn iosGetWindow() ?*const c_void { return sapp_ios_get_window(); } pub extern fn sapp_d3d11_get_device() ?*const c_void; pub inline fn d3d11GetDevice() ?*const c_void { return sapp_d3d11_get_device(); } pub extern fn sapp_d3d11_get_device_context() ?*const c_void; pub inline fn d3d11GetDeviceContext() ?*const c_void { return sapp_d3d11_get_device_context(); } pub extern fn sapp_d3d11_get_render_target_view() ?*const c_void; pub inline fn d3d11GetRenderTargetView() ?*const c_void { return sapp_d3d11_get_render_target_view(); } pub extern fn sapp_d3d11_get_depth_stencil_view() ?*const c_void; pub inline fn d3d11GetDepthStencilView() ?*const c_void { return sapp_d3d11_get_depth_stencil_view(); } pub extern fn sapp_win32_get_hwnd() ?*const c_void; pub inline fn win32GetHwnd() ?*const c_void { return sapp_win32_get_hwnd(); } pub extern fn sapp_wgpu_get_device() ?*const c_void; pub inline fn wgpuGetDevice() ?*const c_void { return sapp_wgpu_get_device(); } pub extern fn sapp_wgpu_get_render_view() ?*const c_void; pub inline fn wgpuGetRenderView() ?*const c_void { return sapp_wgpu_get_render_view(); } pub extern fn sapp_wgpu_get_resolve_view() ?*const c_void; pub inline fn wgpuGetResolveView() ?*const c_void { return sapp_wgpu_get_resolve_view(); } pub extern fn sapp_wgpu_get_depth_stencil_view() ?*const c_void; pub inline fn wgpuGetDepthStencilView() ?*const c_void { return sapp_wgpu_get_depth_stencil_view(); } pub extern fn sapp_android_get_native_activity() ?*const c_void; pub inline fn androidGetNativeActivity() ?*const c_void { return sapp_android_get_native_activity(); }
src/sokol/app.zig
const std = @import("std"); const expectEqual = std.testing.expectEqual; const math = std.math; pub usingnamespace @import("generic_vector.zig"); pub usingnamespace @import("mat4.zig"); pub usingnamespace @import("quaternion.zig"); /// Convert degrees to radians. pub fn toRadians(degrees: anytype) @TypeOf(degrees) { const T = @TypeOf(degrees); if (@typeInfo(T) != .Float) { @compileError("Radians not implemented for " ++ @typeName(T)); } return degrees * (math.pi / 180.0); } /// Convert radians to degrees. pub fn toDegrees(radians: anytype) @TypeOf(radians) { const T = @TypeOf(radians); if (@typeInfo(T) != .Float) { @compileError("Radians not implemented for " ++ @typeName(T)); } return radians * (180.0 / math.pi); } /// Linear interpolation between two floats. /// `t` is used to interpolate between `from` and `to`. pub fn lerp(comptime T: type, from: T, to: T, t: T) T { if (@typeInfo(T) != .Float) { @compileError("Lerp not implemented for " ++ @typeName(T)); } return (1 - t) * from + t * to; } test "zalgebra.toRadians" { try expectEqual(toRadians(@as(f32, 0)), 0); try expectEqual(toRadians(@as(f32, 30)), 0.523598790); try expectEqual(toRadians(@as(f32, 45)), 0.78539818); try expectEqual(toRadians(@as(f32, 60)), 1.04719758); try expectEqual(toRadians(@as(f32, 90)), 1.57079637); //math.pi / 2 try expectEqual(toRadians(@as(f32, 180)), 3.14159274); //math.pi try expectEqual(toRadians(@as(f32, 270)), 4.71238899); try expectEqual(toRadians(@as(f32, 360)), 6.28318548); //math.pi * 2 } test "zalgebra.toDegrees" { try expectEqual(toDegrees(@as(f32, 0)), 0); try expectEqual(toDegrees(@as(f32, 0.5)), 28.6478900); try expectEqual(toDegrees(@as(f32, 1)), 57.2957801); try expectEqual(toDegrees(@as(f32, 1.57079637)), 90); //math.pi / 2 try expectEqual(toDegrees(@as(f32, 3.14159274)), 180); //math.pi try expectEqual(toDegrees(@as(f32, 4.71238899)), 270); try expectEqual(toDegrees(@as(f32, 6.28318548)), 360); //math.pi * 2 } test "zalgebra.lerp" { const from: f32 = 0; const to: f32 = 10; try expectEqual(lerp(f32, from, to, 0), 0); try expectEqual(lerp(f32, from, to, 0.5), 5); try expectEqual(lerp(f32, from, to, 1), 10); }
src/main.zig
const std = @import("std"); // Import/expose everything from std.math so that this package can take its place. pub const e = std.math.e; pub const pi = std.math.pi; pub const phi = std.math.phi; pub const tau = std.math.tau; pub const log2e = std.math.log2e; pub const log10e = std.math.log10e; pub const ln2 = std.math.ln2; pub const ln10 = std.math.ln10; pub const two_sqrtpi = std.math.two_sqrtpi; pub const sqrt2 = std.math.sqrt2; pub const sqrt1_2 = std.math.sqrt1_2; pub const f128_true_min = std.math.f128_true_min; pub const f128_min = std.math.f128_min; pub const f128_max = std.math.f128_max; pub const f128_epsilon = std.math.f128_epsilon; pub const f128_toint = std.math.f128_toint; pub const f64_true_min = std.math.f64_true_min; pub const f64_min = std.math.f64_min; pub const f64_max = std.math.f64_max; pub const f64_epsilon = std.math.f64_epsilon; pub const f64_toint = std.math.f64_toint; pub const f32_true_min = std.math.f32_true_min; pub const f32_min = std.math.f32_min; pub const f32_max = std.math.f32_max; pub const f32_epsilon = std.math.f32_epsilon; pub const f32_toint = std.math.f32_toint; pub const f16_true_min = std.math.f16_true_min; pub const f16_min = std.math.f16_min; pub const f16_max = std.math.f16_max; pub const f16_epsilon = std.math.f16_epsilon; pub const f16_toint = std.math.f16_toint; pub const epsilon = std.math.epsilon; // pub const nan_u16 = std.math.nan_u16; // pub const nan_f16 = std.math.nan_f16; // pub const qnan_u16 = std.math.qnan_u16; // pub const qnan_f16 = std.math.qnan_f16; pub const inf_u16 = std.math.inf_u16; pub const inf_f16 = std.math.inf_f16; // pub const nan_u32 = std.math.nan_u32; // pub const nan_f32 = std.math.nan_f32; // pub const qnan_u32 = std.math.qnan_u32; // pub const qnan_f32 = std.math.qnan_f32; pub const inf_u32 = std.math.inf_u32; pub const inf_f32 = std.math.inf_f32; // pub const nan_u64 = std.math.nan_u64; // pub const nan_f64 = std.math.nan_f64; // pub const qnan_u64 = std.math.qnan_u64; // pub const qnan_f64 = std.math.qnan_f64; pub const inf_u64 = std.math.inf_u64; pub const inf_f64 = std.math.inf_f64; // pub const nan_u128 = std.math.nan_u128; // pub const nan_f128 = std.math.nan_f128; // pub const qnan_u128 = std.math.qnan_u128; // pub const qnan_f128 = std.math.qnan_f128; pub const inf_u128 = std.math.inf_u128; pub const inf_f128 = std.math.inf_f128; // pub const nan = std.math.nan; // pub const snan = std.math.snan; pub const inf = std.math.inf; pub const isNan = std.math.isNan; pub const isSignalNan = std.math.isSignalNan; pub const fabs = std.math.fabs; pub const ceil = std.math.ceil; pub const floor = std.math.floor; pub const trunc = std.math.trunc; pub const round = std.math.round; pub const frexp = std.math.frexp; pub const Frexp = std.math.Frexp; pub const modf = std.math.modf; pub const modf32_result = std.math.modf32_result; pub const modf64_result = std.math.modf64_result; pub const copysign = std.math.copysign; pub const isFinite = std.math.isFinite; pub const isInf = std.math.isInf; pub const isPositiveInf = std.math.isPositiveInf; pub const isNegativeInf = std.math.isNegativeInf; pub const isNormal = std.math.isNormal; pub const signbit = std.math.signbit; pub const scalbn = std.math.scalbn; pub const pow = std.math.pow; pub const powi = std.math.powi; pub const sqrt = std.math.sqrt; pub const cbrt = std.math.cbrt; pub const acos = std.math.acos; pub const asin = std.math.asin; pub const atan = std.math.atan; pub const atan2 = std.math.atan2; pub const hypot = std.math.hypot; // pub const exp = std.math.exp; // pub const exp2 = std.math.exp2; pub const expm1 = std.math.expm1; pub const ilogb = std.math.ilogb; pub const ln = std.math.ln; pub const log = std.math.log; // pub const log2 = std.math.log2; pub const log10 = std.math.log10; pub const log1p = std.math.log1p; pub const fma = std.math.fma; pub const asinh = std.math.asinh; pub const acosh = std.math.acosh; pub const atanh = std.math.atanh; pub const sinh = std.math.sinh; pub const cosh = std.math.cosh; pub const tanh = std.math.tanh; pub const cos = std.math.cos; pub const sin = std.math.sin; pub const tan = std.math.tan; pub const complex = std.math.complex; pub const Complex = complex.Complex; pub const big = std.math.big; pub const approxEqAbs = std.math.approxEqAbs; pub const approxEqRel = std.math.approxEqRel; pub const doNotOptimizeAway = std.math.doNotOptimizeAway; pub const raiseInvalid = std.math.raiseInvalid; pub const raiseUnderflow = std.math.raiseUnderflow; pub const raiseOverflow = std.math.raiseOverflow; pub const raiseInexact = std.math.raiseInexact; pub const raiseDivByZero = std.math.raiseDivByZero; pub const floatMantissaBits = std.math.floatMantissaBits; pub const floatExponentBits = std.math.floatExponentBits; pub const Min = std.math.Min; pub const min = std.math.min; pub const min3 = std.math.min3; pub const max = std.math.max; pub const max3 = std.math.max3; pub const clamp = std.math.clamp; pub const mul = std.math.mul; pub const add = std.math.add; pub const sub = std.math.sub; pub const negate = std.math.negate; pub const shlExact = std.math.shlExact; pub const shl = std.math.shl; pub const shr = std.math.shr; pub const rotr = std.math.rotr; pub const rotl = std.math.rotl; pub const Log2Int = std.math.Log2Int; pub const Log2IntCeil = std.math.Log2IntCeil; pub const IntFittingRange = std.math.IntFittingRange; pub const absInt = std.math.absInt; pub const divTrunc = std.math.divTrunc; pub const divFloor = std.math.divFloor; pub const divCeil = std.math.divCeil; pub const divExact = std.math.divExact; pub const mod = std.math.mod; pub const rem = std.math.rem; pub const absCast = std.math.absCast; pub const negateCast = std.math.negateCast; pub const cast = std.math.cast; pub const alignCast = std.math.alignCast; pub const isPowerOfTwo = std.math.isPowerOfTwo; pub const floorPowerOfTwo = std.math.floorPowerOfTwo; pub const ceilPowerOfTwoPromote = std.math.ceilPowerOfTwoPromote; pub const ceilPowerOfTwo = std.math.ceilPowerOfTwo; pub const ceilPowerOfTwoAssert = std.math.ceilPowerOfTwoAssert; pub const log2_int = std.math.log2_int; pub const log2_int_ceil = std.math.log2_int_ceil; pub const lossyCast = std.math.lossyCast; pub const maxInt = std.math.maxInt; pub const minInt = std.math.minInt; pub const mulWide = std.math.mulWide; pub const order = std.math.order; pub const compare = std.math.compare; pub const comptimeMod = std.math.comptimeMod; // Stuff that's been rewritten/modified within the package. pub const exp = @import("exp.zig").exp; pub const exp2 = @import("exp2.zig").exp2; pub const log2 = @import("log2.zig").log2; pub const nan = @import("nan.zig").nan; pub const snan = @import("nan.zig").snan; pub const snan_u16 = @import("nan.zig").snan_u16; pub const snan_f16 = @import("nan.zig").snan_f16; pub const qnan_u16 = @import("nan.zig").qnan_u16; pub const qnan_f16 = @import("nan.zig").qnan_f16; pub const snan_u32 = @import("nan.zig").snan_u32; pub const snan_f32 = @import("nan.zig").snan_f32; pub const qnan_u32 = @import("nan.zig").qnan_u32; pub const qnan_f32 = @import("nan.zig").qnan_f32; pub const snan_u64 = @import("nan.zig").snan_u64; pub const snan_f64 = @import("nan.zig").snan_f64; pub const qnan_u64 = @import("nan.zig").qnan_u64; pub const qnan_f64 = @import("nan.zig").qnan_f64; pub const snan_u128 = @import("nan.zig").snan_u128; pub const snan_f128 = @import("nan.zig").snan_f128; pub const qnan_u128 = @import("nan.zig").qnan_u128; pub const qnan_f128 = @import("nan.zig").qnan_f128;
src/lib.zig
const std = @import("std"); const msgpack = @import("msgpack"); const expect = std.testing.expect; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // build a map which is going to hold our values var values = std.StringHashMap(msgpack.Value).init(&gpa.allocator); try values.put("s", msgpack.Value{ .string = "string" }); try values.put("u", msgpack.Value{ .uint = 123456 }); try values.put("b", msgpack.Value{ .bool = true }); try values.put("i", msgpack.Value{ .int = -12343 }); var array = try std.ArrayList(msgpack.Value).initCapacity(&gpa.allocator, 2); try array.append(.{ .uint = 1 }); try array.append(.{ .string = "hello" }); try values.put("a", msgpack.Value{ .array = array }); var m = std.StringHashMap(msgpack.Value).init(&gpa.allocator); try m.put("s", msgpack.Value{ .string = "hello world" }); try values.put("m", msgpack.Value{ .map = m }); try values.put("n", .nil); var orig = msgpack.Value{ .map = values }; defer orig.free(); // msgpack encode the value var encoded = try msgpack.encodeValue(&gpa.allocator, orig); defer gpa.allocator.free(encoded); // then let's decode it again var decoded = try msgpack.decodeValue(&gpa.allocator, encoded); defer decoded.free(); // now let's compare the orginal value and the decoded one expect(std.mem.eql(u8, values.get("s").?.string, decoded.map.get("s").?.string)); expect(values.get("u").?.uint == decoded.map.get("u").?.uint); expect(values.get("b").?.bool == decoded.map.get("b").?.bool); expect(values.get("i").?.int == decoded.map.get("i").?.int); expect(values.get("a").?.array.items[0].uint == decoded.map.get("a").?.array.items[0].uint); expect(std.mem.eql(u8, values.get("a").?.array.items[1].string, decoded.map.get("a").?.array.items[1].string)); expect(std.mem.eql(u8, values.get("m").?.map.get("s").?.string, decoded.map.get("m").?.map.get("s").?.string)); expect(values.get("n").?.nil == decoded.map.get("n").?.nil); // we can use the value.equal method as well. expect(orig.equal(decoded)); decoded.dump(); }
examples/value.zig
const std = @import("std"); const windows = @import("../windows.zig").windows; usingnamespace @import("bits.zig"); pub const HBITMAP = *opaque { pub fn toGdiObject(self: HBITMAP) HGDIOBJ { return @ptrCast(HGDIOBJ, self); } }; pub const HGDIOBJ = *opaque {}; pub const Compression = extern enum { BI_RGB = 0x0000, BI_RLE8 = 0x0001, BI_RLE4 = 0x0002, BI_BITFIELDS = 0x0003, BI_JPEG = 0x0004, BI_PNG = 0x0005, BI_CMYK = 0x000B, BI_CMYKRLE8 = 0x000C, BI_CMYKRLE4 = 0x000D, }; pub const DIBColors = extern enum { DIB_RGB_COLORS = 0x00, DIB_PAL_COLORS = 0x01, DIB_PAL_INDICES = 0x02, }; pub const BITMAPINFOHEADER = extern struct { biSize: DWORD = @sizeOf(@This()), biWidth: LONG, biHeight: LONG, biPlanes: WORD, biBitCount: WORD, biCompression: DWORD, biSizeImage: DWORD, biXPelsPerMeter: LONG, biYPelsPerMeter: LONG, biClrUsed: DWORD, biClrImportant: DWORD, }; pub const RGBQUAD = extern struct { rgbBlue: BYTE, rgbGreen: BYTE, rgbRed: BYTE, rgbReserved: BYTE, }; pub const BITMAPINFO = extern struct { bmiHeader: BITMAPINFOHEADER, bmiColors: [1]RGBQUAD, // dynamic size... }; pub const TernaryRasterOperation = extern enum { SRCCOPY = 0x00CC0020, // dest = source SRCPAINT = 0x00EE0086, // dest = source OR dest SRCAND = 0x008800C6, // dest = source AND dest SRCINVERT = 0x00660046, // dest = source XOR dest SRCERASE = 0x00440328, // dest = source AND (NOT dest ) NOTSRCCOPY = 0x00330008, // dest = (NOT source) NOTSRCERASE = 0x001100A6, // dest = (NOT src) AND (NOT dest) MERGECOPY = 0x00C000CA, // dest = (source AND pattern) MERGEPAINT = 0x00BB0226, // dest = (NOT source) OR dest PATCOPY = 0x00F00021, // dest = pattern PATPAINT = 0x00FB0A09, // dest = DPSnoo PATINVERT = 0x005A0049, // dest = pattern XOR dest DSTINVERT = 0x00550009, // dest = (NOT dest) BLACKNESS = 0x00000042, // dest = BLACK WHITENESS = 0x00FF0062, // dest = WHITE }; pub const PIXELFORMATDESCRIPTOR = extern struct { nSize: WORD = @sizeOf(@This()), nVersion: WORD, dwFlags: DWORD, iPixelType: BYTE, cColorBits: BYTE, cRedBits: BYTE, cRedShift: BYTE, cGreenBits: BYTE, cGreenShift: BYTE, cBlueBits: BYTE, cBlueShift: BYTE, cAlphaBits: BYTE, cAlphaShift: BYTE, cAccumBits: BYTE, cAccumRedBits: BYTE, cAccumGreenBits: BYTE, cAccumBlueBits: BYTE, cAccumAlphaBits: BYTE, cDepthBits: BYTE, cStencilBits: BYTE, cAuxBuffers: BYTE, iLayerType: BYTE, bReserved: BYTE, dwLayerMask: DWORD, dwVisibleMask: DWORD, dwDamageMask: DWORD, }; pub const PFD_TYPE_RGBA = 0; pub const PFD_TYPE_COLORINDEX = 1; pub const PFD_MAIN_PLANE = 0; pub const PFD_OVERLAY_PLANE = 1; pub const PFD_UNDERLAY_PLANE = -1; pub const PFD_DOUBLEBUFFER = 0x00000001; pub const PFD_STEREO = 0x00000002; pub const PFD_DRAW_TO_WINDOW = 0x00000004; pub const PFD_DRAW_TO_BITMAP = 0x00000008; pub const PFD_SUPPORT_GDI = 0x00000010; pub const PFD_SUPPORT_OPENGL = 0x00000020; pub const PFD_GENERIC_FORMAT = 0x00000040; pub const PFD_NEED_PALETTE = 0x00000080; pub const PFD_NEED_SYSTEM_PALETTE = 0x00000100; pub const PFD_SWAP_EXCHANGE = 0x00000200; pub const PFD_SWAP_COPY = 0x00000400; pub const PFD_SWAP_LAYER_BUFFERS = 0x00000800; pub const PFD_GENERIC_ACCELERATED = 0x00001000; pub const PFD_SUPPORT_DIRECTDRAW = 0x00002000; pub const PFD_DIRECT3D_ACCELERATED = 0x00004000; pub const PFD_SUPPORT_COMPOSITION = 0x00008000; pub extern "gdi32" fn CreateDIBSection( hdc: HDC, pbmi: *const BITMAPINFO, usage: UINT, ppvBits: **c_void, hSection: ?HANDLE, offset: DWORD, ) callconv(WINAPI) ?HBITMAP; pub extern "gdi32" fn DeleteObject( bitmap: HGDIOBJ, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn CreateCompatibleDC( hdc: ?HDC, ) callconv(WINAPI) ?HDC; pub extern "gdi32" fn SelectObject( hdc: HDC, h: HGDIOBJ, ) callconv(WINAPI) HGDIOBJ; pub extern "gdi32" fn BitBlt( hdc: HDC, x: c_int, y: c_int, cx: c_int, cy: c_int, hdcSrc: HDC, x1: c_int, y1: c_int, rop: DWORD, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn DeleteDC( hdc: HDC, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn TextOutA( hdc: HDC, x: c_int, y: c_int, lpString: [*:0]const u8, c: c_int, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn wglCreateContext(hDC: HDC) callconv(WINAPI) ?HGLRC; pub extern "gdi32" fn wglDeleteContext(context: HGLRC) callconv(WINAPI) BOOL; pub extern "gdi32" fn wglMakeCurrent( hDC: HDC, gl_context: ?HGLRC, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn SwapBuffers(hDC: HDC) callconv(WINAPI) BOOL; pub extern "gdi32" fn SetPixelFormat( hdc: HDC, format: c_int, ppfd: *const PIXELFORMATDESCRIPTOR, ) callconv(WINAPI) BOOL; pub extern "gdi32" fn ChoosePixelFormat( hdc: HDC, ppfd: *const PIXELFORMATDESCRIPTOR, ) c_int; pub extern "gdi32" fn wglGetProcAddress(entry_point: [*:0]const u8) callconv(WINAPI) ?*c_void; pub extern "gdi32" fn wglGetCurrentContext() callconv(WINAPI) ?HGLRC; pub const WGL_NUMBER_PIXEL_FORMATS_ARB = 0x2000; pub const WGL_DRAW_TO_WINDOW_ARB = 0x2001; pub const WGL_DRAW_TO_BITMAP_ARB = 0x2002; pub const WGL_ACCELERATION_ARB = 0x2003; pub const WGL_NEED_PALETTE_ARB = 0x2004; pub const WGL_NEED_SYSTEM_PALETTE_ARB = 0x2005; pub const WGL_SWAP_LAYER_BUFFERS_ARB = 0x2006; pub const WGL_SWAP_METHOD_ARB = 0x2007; pub const WGL_NUMBER_OVERLAYS_ARB = 0x2008; pub const WGL_NUMBER_UNDERLAYS_ARB = 0x2009; pub const WGL_TRANSPARENT_ARB = 0x200A; pub const WGL_TRANSPARENT_RED_VALUE_ARB = 0x2037; pub const WGL_TRANSPARENT_GREEN_VALUE_ARB = 0x2038; pub const WGL_TRANSPARENT_BLUE_VALUE_ARB = 0x2039; pub const WGL_TRANSPARENT_ALPHA_VALUE_ARB = 0x203A; pub const WGL_TRANSPARENT_INDEX_VALUE_ARB = 0x203B; pub const WGL_SHARE_DEPTH_ARB = 0x200C; pub const WGL_SHARE_STENCIL_ARB = 0x200D; pub const WGL_SHARE_ACCUM_ARB = 0x200E; pub const WGL_SUPPORT_GDI_ARB = 0x200F; pub const WGL_SUPPORT_OPENGL_ARB = 0x2010; pub const WGL_DOUBLE_BUFFER_ARB = 0x2011; pub const WGL_STEREO_ARB = 0x2012; pub const WGL_PIXEL_TYPE_ARB = 0x2013; pub const WGL_COLOR_BITS_ARB = 0x2014; pub const WGL_RED_BITS_ARB = 0x2015; pub const WGL_RED_SHIFT_ARB = 0x2016; pub const WGL_GREEN_BITS_ARB = 0x2017; pub const WGL_GREEN_SHIFT_ARB = 0x2018; pub const WGL_BLUE_BITS_ARB = 0x2019; pub const WGL_BLUE_SHIFT_ARB = 0x201A; pub const WGL_ALPHA_BITS_ARB = 0x201B; pub const WGL_ALPHA_SHIFT_ARB = 0x201C; pub const WGL_ACCUM_BITS_ARB = 0x201D; pub const WGL_ACCUM_RED_BITS_ARB = 0x201E; pub const WGL_ACCUM_GREEN_BITS_ARB = 0x201F; pub const WGL_ACCUM_BLUE_BITS_ARB = 0x2020; pub const WGL_ACCUM_ALPHA_BITS_ARB = 0x2021; pub const WGL_DEPTH_BITS_ARB = 0x2022; pub const WGL_STENCIL_BITS_ARB = 0x2023; pub const WGL_AUX_BUFFERS_ARB = 0x2024; pub const WGL_NO_ACCELERATION_ARB = 0x2025; pub const WGL_GENERIC_ACCELERATION_ARB = 0x2026; pub const WGL_FULL_ACCELERATION_ARB = 0x2027; pub const WGL_SWAP_EXCHANGE_ARB = 0x2028; pub const WGL_SWAP_COPY_ARB = 0x2029; pub const WGL_SWAP_UNDEFINED_ARB = 0x202A; pub const WGL_TYPE_RGBA_ARB = 0x202B; pub const WGL_TYPE_COLORINDEX_ARB = 0x202C; pub const WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091; pub const WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092; pub const WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093; pub const WGL_CONTEXT_FLAGS_ARB = 0x2094; pub const WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126; pub const WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001; pub const WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002; pub const WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001; pub const WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002; pub const ERROR_INVALID_VERSION_ARB = 0x2095; pub const ERROR_INVALID_PROFILE_ARB = 0x2096;
didot-zwl/zwl/src/windows/gdi32.zig
const std = @import("std"); const span = std.mem.span; const Span = std.mem.Span; const Child = std.meta.Child; const Allocator = std.mem.Allocator; pub fn iterator(value: anytype) IterOf(@TypeOf(value)) { // Maybe there is a better way of doing this ? if (comptime IterOf(@TypeOf(value)) == @TypeOf(value)) { return value; } else { return IterOf(@TypeOf(value)).init(value); } } pub fn zip(input0: anytype, input1: anytype) ZipIter(IterOf(@TypeOf(input0)), IterOf(@TypeOf(input1))) { return ZipIter(IterOf(@TypeOf(input0)), IterOf(@TypeOf(input1))).init(iterator(input0), iterator(input1)); } pub fn range(comptime _type: type, options: RangeOptions(_type)) RangeIter(_type) { return RangeIter(_type).init(options); } pub fn once(value: anytype) OnceIter(@TypeOf(value)) { return OnceIter(@TypeOf(value)).init(value); } pub fn Pair(comptime A: type, comptime B: type) type { return struct { const AType = A; const BType = B; a: AType, b: BType, }; } pub fn pair(a: anytype, b: anytype) Pair(@TypeOf(a), @TypeOf(a)) { return Pair(@TypeOf(a), @TypeOf(a)){ .a = a, .b = b }; } // What I wanted on filter: self.Output. // But seems that with usingnamespace, the self type here are // unable to capture const members inside the parent struct // Because of that, the solution was to pass the Output explicitly fn Functions(comptime Output: type) type { return struct { pub fn map(self: anytype, _fn: anytype) MapIter(@TypeOf(self), @TypeOf(_fn)) { return MapIter(@TypeOf(self), @TypeOf(_fn)).init(self, _fn); } pub fn filter(self: anytype, _fn: anytype) FilterIter(@TypeOf(self), Output, @TypeOf(_fn)) { return FilterIter(@TypeOf(self), Output, @TypeOf(_fn)).init(self, _fn); } pub fn reduce(self: anytype, _fn: anytype) OnceIter(Output) { if (self.next()) |first_value| { return OnceIter(Output).init(fold(self, first_value, _fn)); } else { return OnceIter(Output).init(null); } } // same problema that Input0.Output are not visible for some reason // solved by passing the value instead of the pointer. (input0.*) // I have no idea why it works, or if this will break something. pub fn zip(input0: anytype, input1: anytype) ZipIter(@TypeOf(input0.*), IterOf(@TypeOf(input1))) { return ZipIter(@TypeOf(input0.*), IterOf(@TypeOf(input1))).init(input0.*, iterator(input1)); } // Consumers pub fn fold(self: anytype, start_value: anytype, _fn: anytype) Output { var accum: Output = start_value; while (self.next()) |value| { accum = _fn(accum, value); } return accum; } pub fn each(self: anytype, _fn: anytype) void { while (self.next()) |value| { _fn(value); } } pub fn toArrayList(self: anytype, allocator: *Allocator) !std.ArrayList(Output) { var array_list = std.ArrayList(Output).init(allocator); while (self.next()) |value| { try array_list.append(value); } return array_list; } pub fn toAutoHashMap(self: anytype, allocator: *Allocator) !std.AutoHashMap(Output.AType, Output.BType) { var array = std.AutoHashMap(Output.AType, Output.BType).init(allocator); while (self.next()) |value| { try array.put(value.a, value.b); } return array; } }; } fn FnOutput(comptime Fn: type) type { //TODO: comptime check if is Fn type return @typeInfo(Fn).Fn.return_type.?; } fn IterOf(comptime Type: type) type { if (comptime std.meta.trait.hasFn("next")(Type)) { return Type; } const Info = @typeInfo(Type); return switch (Info) { .Pointer => |pointer| switch (pointer.size) { .One => return switch (@typeInfo(pointer.child)) { .Array => SliceIter(Span(Type)), else => @compileError("IterOf(" ++ @typeName(Type) ++ ") not implemented!"), }, else => @compileError("IterOf(" ++ @typeName(Type) ++ ") not implemented!"), }, else => @compileError("IterOf(" ++ @typeName(Type) ++ ") not implemented!"), }; } fn OnceIter(comptime Type: type) type { return struct { const Self = @This(); pub const Output = Type; value: ?Type, fn init(value: ?Type) Self { return Self{ .value = value }; } pub fn next(self: *Self) ?Output { if (self.value) |value| { defer self.value = null; return value; } else { return null; } } usingnamespace Functions(Output); }; } fn SliceIter(comptime Slice: type) type { return struct { const Self = @This(); pub const Output = Child(Slice); data: Slice, fn init(data: Slice) Self { return Self{ .data = data }; } pub fn next(self: *Self) ?Output { if (self.data.len == 0) { return null; } defer self.data = self.data[1..]; return self.data[0]; } usingnamespace Functions(Output); }; } fn RangeOptions(comptime _type: type) type { return struct { start: _type = 0, end: _type = 0, step: _type = 1 }; } fn RangeIter(comptime Type: type) type { return struct { const Self = @This(); pub const Output = Type; start: Output, end: Output, step: Output, fn init(options: RangeOptions(Output)) Self { return Self{ .start = options.start, .end = options.end, .step = options.step, }; } pub fn next(self: *Self) ?Output { if (self.start >= self.end) { return null; } defer self.start += self.step; return self.start; } usingnamespace Functions(Output); }; } fn MapIter(comptime Input: type, comptime Fn: type) type { return struct { const Self = @This(); pub const Output = FnOutput(Fn); input: Input, _fn: Fn, fn init(input: Input, _fn: Fn) Self { return Self{ .input = input, ._fn = _fn }; } pub fn next(self: *Self) ?Output { if (self.input.next()) |value| { return self._fn(value); } else { return null; } } usingnamespace Functions(Output); }; } fn FilterIter(comptime Input: type, comptime _Output: type, comptime Fn: type) type { return struct { const Self = @This(); const Output = _Output; input: Input, _fn: Fn, fn init(input: Input, _fn: Fn) Self { return Self{ .input = input, ._fn = _fn }; } pub fn next(self: *Self) ?Output { while (self.input.next()) |value| { if (self._fn(value)) { return value; } } return null; } usingnamespace Functions(Output); }; } fn ZipIter(comptime Input0: type, comptime Input1: type) type { return struct { const Self = @This(); const Output = Pair(Input0.Output, Input1.Output); input0: Input0, input1: Input1, fn init(input0: Input0, input1: Input1) Self { return Self{ .input0 = input0, .input1 = input1 }; } pub fn next(self: *Self) ?Output { if (self.input0.next()) |a| { if (self.input1.next()) |b| { return Output{ .a = a, .b = b }; } } return null; } usingnamespace Functions(Output); }; }
src/itertools.zig
const std = @import("std"); const common = @import("../common/data.zig"); const DEBUG = @import("../common/debug.zig").print; const options = @import("../common/options.zig"); const protocol = @import("../common/protocol.zig"); const rng = @import("../common/rng.zig"); const data = @import("data.zig"); const assert = std.debug.assert; const expectEqual = std.testing.expectEqual; const Choice = common.Choice; const ID = common.ID; const Player = common.Player; const Result = common.Result; const showdown = options.showdown; const Damage = protocol.Damage; const Heal = protocol.Heal; const Gen12 = rng.Gen12; const ActivePokemon = data.ActivePokemon; const Effectiveness = data.Effectiveness; const Move = data.Move; const MoveSlot = data.MoveSlot; const Pokemon = data.Pokemon; const Side = data.Side; const Species = data.Species; const Stats = data.Stats; const Status = data.Status; // zig fmt: off const BOOSTS = &[_][2]u8{ .{ 25, 100 }, // -6 .{ 28, 100 }, // -5 .{ 33, 100 }, // -4 .{ 40, 100 }, // -3 .{ 50, 100 }, // -2 .{ 66, 100 }, // -1 .{ 1, 1 }, // 0 .{ 15, 10 }, // +1 .{ 2, 1 }, // +2 .{ 25, 10 }, // +3 .{ 3, 1 }, // +4 .{ 35, 10 }, // +5 .{ 4, 1 }, // +6 }; // zig fmt: on const MAX_STAT_VALUE = 999; pub fn update(battle: anytype, c1: Choice, c2: Choice, log: anytype) !Result { assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0); if (battle.turn == 0) return start(battle, log); var f1: ?Move = null; var f2: ?Move = null; if (selectMove(battle, .P1, c1, c2, &f1)) |r| return r; if (selectMove(battle, .P2, c2, c1, &f2)) |r| return r; if (turnOrder(battle, c1, c2) == .P1) { if (try doTurn(battle, .P1, c1, f1, .P2, c2, f2, log)) |r| return r; } else { if (try doTurn(battle, .P2, c2, f2, .P1, c1, f1, log)) |r| return r; } var p1 = battle.side(.P1); if (p1.active.volatiles.attacks == 0) { p1.active.volatiles.Trapping = false; } var p2 = battle.side(.P2); if (p2.active.volatiles.attacks == 0) { p2.active.volatiles.Trapping = false; } return endTurn(battle, log); } fn start(battle: anytype, log: anytype) !Result { const p1 = battle.side(.P1); const p2 = battle.side(.P2); var p1_slot = findFirstAlive(p1); assert(!showdown or p1_slot == 1); if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose; var p2_slot = findFirstAlive(p2); assert(!showdown or p2_slot == 1); if (p2_slot == 0) return Result.Win; try switchIn(battle, .P1, p1_slot, true, log); try switchIn(battle, .P2, p2_slot, true, log); return endTurn(battle, log); } fn findFirstAlive(side: *const Side) u8 { for (side.pokemon) |pokemon, i| if (pokemon.hp > 0) return side.order[i]; return 0; } fn selectMove( battle: anytype, player: Player, choice: Choice, foe_choice: Choice, from: *?Move, ) ?Result { if (choice.type == .Pass) return null; var side = battle.side(player); var volatiles = &side.active.volatiles; const stored = side.stored(); // pre-battle menu if (volatiles.Recharging) return null; if (volatiles.Rage) { from.* = side.last_used_move; if (showdown) saveMove(battle, player, null); return null; } volatiles.Flinch = false; if (volatiles.Thrashing or volatiles.Charging) { from.* = side.last_used_move; if (showdown) saveMove(battle, player, null); return null; } // battle menu if (choice.type == .Switch) return null; // pre-move select if (Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP) or volatiles.Bide) { if (showdown) saveMove(battle, player, choice); return null; } if (volatiles.Trapping) { if (showdown) { from.* = side.last_used_move; // Pokémon Showdown overwrites Mirror Move with whatever was selected - really this // should set side.last_selected_move = last.id to reuse Mirror Move and fail in order // to satisfy the conditions of the Desync Clause Mod saveMove(battle, player, choice); } else { // GLITCH: https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch if (foe_choice.type == .Switch) { const slot = if (player == .P1) battle.last_selected_indexes.p1 else battle.last_selected_indexes.p2; const last = side.active.move(@truncate(u4, slot)); if (last.id == .Metronome) side.last_selected_move = last.id; if (last.id == .MirrorMove) return Result.Error; } } return null; } if (battle.foe(player).active.volatiles.Trapping) { if (showdown) { saveMove(battle, player, choice); } else { side.last_selected_move = .SKIP_TURN; } return null; } // move select if (choice.data == 0) { const struggle = ok: { for (side.active.moves) |move, i| { if (move.pp > 0 and volatiles.disabled.move != i + 1) break :ok false; } break :ok true; }; assert(struggle); saveMove(battle, player, choice); } else { saveMove(battle, player, choice); } return null; } fn saveMove(battle: anytype, player: Player, choice: ?Choice) void { var side = battle.side(player); if (choice) |c| { assert(c.type == .Move); if (c.data == 0) { side.last_selected_move = .Struggle; } else { assert(side.active.volatiles.disabled.move != c.data); const move = side.active.move(c.data); // You cannot *select* a move with 0 PP (except on Pokémon Showdown where that is // sometimes required...), but a 0 PP move can be used automatically assert(showdown or move.pp != 0); side.last_selected_move = move.id; if (player == .P1) { battle.last_selected_indexes.p1 = c.data; } else { battle.last_selected_indexes.p2 = c.data; } } } else { assert(showdown); // The choice's move slot isn't useful as Pokémon Showdown will always force the "locked" // choice to be slot 1. Overwriting the last_selected_move with the last_used_move in this // case ensures we actually call the correct move. side.last_selected_move = side.last_used_move; } // getRandomTarget arbitrarily advances the RNG during resolveAction if (showdown) battle.rng.advance(Move.frames(side.last_selected_move, .resolve)); } fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, log: anytype) !void { var side = battle.side(player); var foe = battle.foe(player); var active = &side.active; const incoming = side.get(slot); assert(incoming.hp != 0); assert(slot != 1 or initial); const out = side.order[0]; side.order[0] = side.order[slot - 1]; side.order[slot - 1] = out; side.last_used_move = .None; foe.last_used_move = .None; active.stats = incoming.stats; active.species = incoming.species; active.types = incoming.types; active.boosts = .{}; active.volatiles = .{}; active.moves = incoming.moves; statusModify(incoming.status, &active.stats); foe.active.volatiles.Trapping = false; try log.switched(battle.active(player), incoming); } fn turnOrder(battle: anytype, c1: Choice, c2: Choice) Player { assert(c1.type != .Pass or c2.type != .Pass); if (c1.type == .Pass) return .P2; if (c2.type == .Pass) return .P1; if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2; const m1 = battle.side(.P1).last_selected_move; const m2 = battle.side(.P2).last_selected_move; if ((m1 == .QuickAttack) != (m2 == .QuickAttack)) return if (m1 == .QuickAttack) .P1 else .P2; if ((m1 == .Counter) != (m2 == .Counter)) return if (m1 == .Counter) .P2 else .P1; // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on // > your own screen without waiting for the other player's choice (and their choice will appear // > to happen first for them too, unless they attacked in which case your switch happens first) // A cartridge-compatible implemention must not advance the RNG so we simply default to P1 if (!showdown and c1.type == .Switch and c2.type == .Switch) return .P1; const spe1 = battle.side(.P1).active.stats.spe; const spe2 = battle.side(.P2).active.stats.spe; if (spe1 == spe2) { const p1 = if (showdown) battle.rng.range(u8, 0, 2) == 0 else battle.rng.next() < Gen12.percent(50) + 1; return if (p1) .P1 else .P2; } return if (spe1 > spe2) .P1 else .P2; } fn doTurn( battle: anytype, player: Player, player_choice: Choice, player_from: ?Move, foe_player: Player, foe_choice: Choice, foe_from: ?Move, log: anytype, ) !?Result { assert(player_choice.type != .Pass); if (try executeMove(battle, player, player_choice, player_from, log)) |r| return r; if (try checkFaint(battle, foe_player, log)) |r| return r; try handleResidual(battle, player, log); if (try checkFaint(battle, player, log)) |r| return r; if (foe_choice.type == .Pass) return null; if (try executeMove(battle, foe_player, foe_choice, foe_from, log)) |r| return r; if (try checkFaint(battle, player, log)) |r| return r; try handleResidual(battle, foe_player, log); if (try checkFaint(battle, foe_player, log)) |r| return r; return null; } fn executeMove( battle: anytype, player: Player, choice: Choice, from: ?Move, log: anytype, ) !?Result { var side = battle.side(player); // Pokémon Showdown overwrites the SKIP_TURN sentinel with its botched move select const skip_turn = if (showdown) battle.foe(player).active.volatiles.Trapping else side.last_selected_move == .SKIP_TURN; if (skip_turn) return null; if (choice.type == .Switch) { try switchIn(battle, player, choice.data, false, log); return null; } // getRandomTarget arbitrarily advances the RNG during runAction if (showdown) battle.rng.advance(Move.frames(side.last_selected_move, .run)); var skip_can = false; var skip_pp = false; switch (try beforeMove(battle, player, log)) { .done => return null, .skip_can => skip_can = true, .skip_pp => skip_pp = true, .ok => {}, .err => return @as(?Result, Result.Error), } if (!skip_can and !try canMove(battle, player, choice, skip_pp, from, log)) return null; return doMove(battle, player, choice, from, log); } const BeforeMove = union(enum) { done, skip_can, skip_pp, ok, err }; fn beforeMove(battle: anytype, player: Player, log: anytype) !BeforeMove { var side = battle.side(player); const foe = battle.foe(player); var active = &side.active; var stored = side.stored(); const ident = battle.active(player); var volatiles = &active.volatiles; if (Status.is(stored.status, .SLP)) { const status = stored.status; // Even if the SLF bit is set this will still correctly modify the sleep duration stored.status -= 1; if (Status.duration(stored.status) == 0) { try log.curestatus(ident, status, .Message); stored.status = 0; // clears SLF if present } else { try log.cant(ident, .Sleep); } side.last_used_move = .None; return .done; } if (Status.is(stored.status, .FRZ)) { try log.cant(ident, .Freeze); side.last_used_move = .None; return .done; } if (foe.active.volatiles.Trapping) { try log.cant(ident, .Trapped); return .done; } if (volatiles.Flinch) { volatiles.Flinch = false; try log.cant(ident, .Flinch); return .done; } if (volatiles.Recharging) { volatiles.Recharging = false; try log.cant(ident, .Recharge); return .done; } if (volatiles.disabled.duration > 0) { volatiles.disabled.duration -= 1; if (volatiles.disabled.duration == 0) { volatiles.disabled.move = 0; try log.end(ident, .Disable); } } if (volatiles.Confusion) { assert(volatiles.confusion > 0); volatiles.confusion -= 1; if (volatiles.confusion == 0) { volatiles.Confusion = false; try log.end(ident, .Confusion); } else { try log.activate(ident, .Confusion); const confused = if (showdown) !battle.rng.chance(u8, 128, 256) else battle.rng.next() >= Gen12.percent(50) + 1; if (confused) { volatiles.Bide = false; volatiles.Thrashing = false; volatiles.MultiHit = false; volatiles.Flinch = false; volatiles.Charging = false; volatiles.Trapping = false; volatiles.Invulnerable = false; // calcDamage just needs a 40 BP physical move, its not actually Pound const move = Move.get(.Pound); if (!calcDamage(battle, player, player, move, false)) return .err; // Skipping adjustDamage / randomizeDamage / checkHit _ = try applyDamage(battle, player, player.foe(), log); return .done; } } } if (volatiles.disabled.move != 0 and active.move(volatiles.disabled.move).id == side.last_selected_move) { try log.disabled(ident, side.last_selected_move); return .done; } if (Status.is(stored.status, .PAR)) { const paralyzed = if (showdown) battle.rng.chance(u8, 63, 256) else battle.rng.next() < Gen12.percent(25); if (paralyzed) { volatiles.Bide = false; volatiles.Thrashing = false; volatiles.Charging = false; volatiles.Trapping = false; // GLITCH: Invulnerable is not cleared, resulting in permanent Fly/Dig invulnerability // (Pokémon Showdown unintentionally patches this glitch, preventing invulnerability) if (showdown) volatiles.Invulnerable = false; try log.cant(ident, .Paralysis); return .done; } } if (volatiles.Bide) { assert(!volatiles.Thrashing and !volatiles.Rage); volatiles.state +%= battle.last_damage; try log.activate(ident, .Bide); assert(volatiles.attacks > 0); volatiles.attacks -= 1; if (volatiles.attacks != 0) return .done; volatiles.Bide = false; try log.end(ident, .Bide); battle.last_damage = volatiles.state *% 2; volatiles.state = 0; if (battle.last_damage == 0) { try log.fail(ident, .None); return .done; } _ = try applyDamage(battle, player.foe(), player.foe(), log); return .done; } if (volatiles.Thrashing) { assert(volatiles.attacks > 0); volatiles.attacks -= 1; if (volatiles.attacks == 0) { volatiles.Thrashing = false; volatiles.Confusion = true; volatiles.confusion = @truncate(u3, if (showdown) battle.rng.range(u8, 2, 6) else (battle.rng.next() & 3) + 2); try log.start(ident, .ConfusionSilent); } return .skip_can; } if (volatiles.Trapping) { assert(volatiles.attacks > 0); volatiles.attacks -= 1; _ = try applyDamage(battle, player.foe(), player.foe(), log); return .done; } return if (volatiles.Rage) .skip_pp else .ok; } fn canMove( battle: anytype, player: Player, choice: Choice, skip_pp: bool, from: ?Move, log: anytype, ) !bool { var side = battle.side(player); const player_ident = battle.active(player); const move = Move.get(side.last_selected_move); if (side.active.volatiles.Charging) { side.active.volatiles.Charging = false; side.active.volatiles.Invulnerable = false; } else if (move.effect == .Charge) { try log.move(player_ident, side.last_selected_move, .{}, from); try Effects.charge(battle, player, log); // Pokémon Showdown thinks the first turn of charging counts as using a move if (showdown) side.last_used_move = side.last_selected_move; return false; } // Getting a "locked" move advances the RNG on Pokémon Showdown const special = if (from) |m| (m == .Metronome or m == .MirrorMove) else false; const locked = from != null and !special; if (showdown and locked) battle.rng.advance(1); side.last_used_move = side.last_selected_move; if (!skip_pp) decrementPP(side, choice); // Metronome / Mirror Move call getRandomTarget if the move they proc targets if (showdown and special) battle.rng.advance(@boolToInt(move.target != .Self)); const target = if (move.target == .Self) player else player.foe(); try log.move(player_ident, side.last_selected_move, battle.active(target), from); if (move.effect.onBegin()) { try moveEffect(battle, player, move, choice.data, log); return false; } if (move.effect == .Thrashing) { Effects.thrashing(battle, player); } else if (move.effect == .Trapping) { Effects.trapping(battle, player); } return true; } fn decrementPP(side: *Side, choice: Choice) void { assert(choice.type == .Move); assert(choice.data <= 4); assert(choice.data != 0 or side.last_selected_move == .Struggle); if (choice.data == 0) return; var active = &side.active; const volatiles = &active.volatiles; assert(!volatiles.Rage and !volatiles.Thrashing); if (volatiles.Bide or volatiles.MultiHit) return; // GLITCH: Struggle bypass PP underflow via Hyper Beam / Trapping-switch auto selection const underflow = side.last_selected_move == .HyperBeam or Move.get(side.last_selected_move).effect == .Trapping; assert(active.move(choice.data).pp > 0 or underflow); active.move(choice.data).pp -%= 1; if (volatiles.Transform) return; assert(side.stored().move(choice.data).pp > 0 or underflow); side.stored().move(choice.data).pp -%= 1; assert(active.move(choice.data).pp == side.stored().move(choice.data).pp); } // Pokémon Showdown does hit/multi/crit/damage instead of crit/damage/hit/multi fn doMove(battle: anytype, player: Player, choice: Choice, from: ?Move, log: anytype) !?Result { var side = battle.side(player); const foe = battle.foe(player); var move = Move.get(side.last_selected_move); const special = move.effect == .SuperFang or move.effect == .SpecialDamage; // Pokémon Showdown runs type and OHKO immunity checks before the accuracy check if (showdown) { const m = side.last_selected_move; const type1 = @enumToInt(move.type.effectiveness(foe.active.types.type1)); const type2 = @enumToInt(move.type.effectiveness(foe.active.types.type2)); // Sonic Boom incorrectly checks type immunity on Pokémon Showdown if (move.target != .Self and (type1 == 0 or type2 == 0) and !(special and m != .SonicBoom) or (m == .DreamEater and !Status.is(foe.stored().status, .SLP))) { try log.immune(battle.active(player.foe()), .None); if (move.effect == .Explode) try Effects.explode(battle, player); return null; } if (move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe) { try log.immune(battle.active(player.foe()), .OHKO); return null; } } // The cartridge handles set damage moves in applyDamage but we short circuit to simplify things if (special) return specialDamage(battle, player, move, log); var crit = false; var ohko = false; var immune = false; var mist = false; var hits: u4 = 1; var effectiveness = Effectiveness.neutral; var miss = showdown and (move.target != .Self and !(move.effect == .Sleep and foe.active.volatiles.Recharging) and !moveHit(battle, player, move, &immune, &mist)); assert(!immune); const skip = move.bp == 0 and move.effect != .OHKO; const counter = side.last_selected_move == .Counter; if (!miss and (!showdown or (!skip or counter))) blk: { if (showdown and move.effect.isMulti()) { Effects.multiHit(battle, player, move); hits = side.active.volatiles.attacks; } // Cartridge rolls for crit even for moves that can't crit (Counter/Metronome/status/OHKO) const check = if (!showdown) true else !counter and move.effect != .OHKO; // TODO: skip? crit = if (check) checkCriticalHit(battle, player, move) else crit; if (counter) return counterDamage(battle, player, move, log); // Pokémon Showdown has broken `Battle.lastDamage` handling if (!showdown) battle.last_damage = 0; // Disassembly does a check to allow 0 BP MultiHit moves but this isn't possible in practice assert(move.effect != .MultiHit or move.bp > 0); if (!skip) { if (move.effect == .OHKO) { ohko = if (!showdown) side.active.stats.spe >= foe.active.stats.spe else true; // This can overflow after adjustDamage, but will still be sufficient to OHKO battle.last_damage = if (ohko) 65535 else 0; if (showdown) break :blk; // skip adjustDamage / randomizeDamage } else if (!calcDamage(battle, player, player.foe(), move, crit)) { return @as(?Result, Result.Error); } if (battle.last_damage == 0) { immune = true; effectiveness = 0; } else { effectiveness = adjustDamage(battle, player); immune = effectiveness == 0; } randomizeDamage(battle); } } miss = if (showdown or skip) miss else (!moveHit(battle, player, move, &immune, &mist) or battle.last_damage == 0); assert(miss or battle.last_damage > 0 or skip or showdown); assert(!(ohko and immune)); assert(!immune or miss); if (!showdown or !miss) { if (move.effect == .MirrorMove) { return mirrorMove(battle, player, choice, log); } else if (move.effect == .Metronome) { return metronome(battle, player, choice, log); } } if ((!showdown or !miss) and move.effect.onEnd()) { try moveEffect(battle, player, move, choice.data, log); return null; } if (miss) { const foe_ident = battle.active(player.foe()); if (!showdown and move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe) { try log.immune(foe_ident, .OHKO); } else if (immune) { try log.immune(foe_ident, .None); } else if (mist) { try log.activate(foe_ident, .Mist); try log.fail(foe_ident, .None); } else { try log.lastmiss(); try log.miss(battle.active(player)); } if (move.effect == .JumpKick) { // Recoil is supposed to be damage/8 but damage will always be 0 here assert(battle.last_damage == 0); battle.last_damage = 1; _ = try applyDamage(battle, player, player.foe(), log); } else if (move.effect == .Explode) { try Effects.explode(battle, player); // Pokémon Showdown does not build Rage after missing Self-Destruct/Explosion if (foe.stored().hp == 0 or showdown) return null; if (foe.active.volatiles.Rage and foe.active.boosts.atk < 6) { try Effects.boost(battle, player.foe(), Move.get(.Rage), log); } } return null; } // On the cartridge MultiHit doesn't get set up until after damage has been applied for the // first time but its more convenient and efficient to set it up here (Pokémon Showdown sets // it up above before damage calculation). if (!showdown and move.effect.isMulti()) { Effects.multiHit(battle, player, move); hits = side.active.volatiles.attacks; } // FIXME: HyperBeam [from] MirrorMove _ = from; var nullified = false; var hit: u4 = 0; while (hit < hits) { if (hit == 0) { if (crit) try log.crit(battle.active(player.foe())); if (effectiveness > Effectiveness.neutral) { try log.supereffective(battle.active(player.foe())); } else if (effectiveness < Effectiveness.neutral) { try log.resisted(battle.active(player.foe())); } } if (!skip) nullified = try applyDamage(battle, player.foe(), player.foe(), log); if (foe.active.volatiles.Rage and foe.active.boosts.atk < 6) { try Effects.boost(battle, player.foe(), Move.get(.Rage), log); } if (hit == 0 and ohko) try log.ohko(); hit += 1; // If the substitute breaks during a multi-hit attack, the attack ends if (nullified or foe.stored().hp == 0) break; // Twineedle can also poison on the first hit on Pokémon Showdown (second hit below) if (showdown and hit == 0 and move.effect == .Twineedle) { try moveEffect(battle, player, Move.get(.PoisonSting), choice.data, log); } } if (side.active.volatiles.MultiHit) { side.active.volatiles.MultiHit = false; assert(nullified or side.active.volatiles.attacks - hit == 0); side.active.volatiles.attacks = 0; try log.hitcount(battle.active(player.foe()), hit); } // Substitute being broken nullifies the move's effect completely so even // if an effect was intended to "always happen" it will still get skipped. if (nullified) return null; // On the cartridge, "always happen" effect handlers are called in the applyDamage loop above, // but this is only done to setup the MultiHit looping in the first place. Moving the MultiHit // setup before the loop means we can avoid having to waste time doing no-op handler searches. if (move.effect.alwaysHappens()) try moveEffect(battle, player, move, choice.data, log); if (foe.stored().hp == 0) return null; if (!move.effect.isSpecial()) { // On the cartridge Rage is not considered to be "special" and thus gets executed for a // second time here (after being executed in the "always happens" block above) but that // doesn't matter since its idempotent (on the cartridge, but not in the implementation // below). For Twineedle we change the data to that of one with PoisonChance1 given its // MultiHit behavior is complete after the loop above. if (move.effect == .Twineedle) move = Move.get(.PoisonSting); try moveEffect(battle, player, move, choice.data, log); } return null; } fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data) bool { const side = battle.side(player); // Base speed is used for the critical hit calculation, even when Transform-ed var chance = @as(u16, Species.chance(side.stored().species)); // GLITCH: Focus Energy reduces critical hit chance instead of increasing it chance = if (side.active.volatiles.FocusEnergy) chance / 2 else @minimum(chance * 2, 255); chance = if (move.effect == .HighCritical) @minimum(chance * 4, 255) else chance / 2; if (showdown) return battle.rng.chance(u8, @truncate(u8, chance), 256); return std.math.rotl(u8, battle.rng.next(), 3) < chance; } fn calcDamage( battle: anytype, player: Player, target_player: Player, move: Move.Data, crit: bool, ) bool { assert(move.bp != 0); const side = battle.side(player); const target = battle.side(target_player); const special = move.type.special(); // zig fmt: off var atk: u32 = if (crit) if (special) side.stored().stats.spc else side.stored().stats.atk else if (special) side.active.stats.spc else side.active.stats.atk; var def: u32 = if (crit) if (special) target.stored().stats.spc else target.stored().stats.def else // GLITCH: not capped to MAX_STAT_VALUE, can be 999 * 2 = 1998 if (special) target.active.stats.spc * @as(u2, if (target.active.volatiles.LightScreen) 2 else 1) else target.active.stats.def * @as(u2, if (target.active.volatiles.Reflect) 2 else 1); // zig fmt: on if (atk > 255 or def > 255) { atk = @maximum((atk / 4) & 255, 1); // GLITCH: not adjusted to be a min of 1 on cartridge (can lead to division-by-zero freeze) def = @maximum((def / 4) & 255, if (showdown) 1 else 0); } const lvl = @as(u32, side.stored().level * @as(u2, if (crit) 2 else 1)); def = @as(u32, if (move.effect == .Explode) @maximum(def / 2, 1) else def); if (def == 0) return false; var d: u32 = (lvl * 2 / 5) + 2; d *%= @as(u32, move.bp); d *%= atk; d /= def; d /= 50; d = @minimum(997, d); // Pokémon Showdown incorrectly clamps damage here between 1 and 997 instead 0 and 997 if (showdown) d = @maximum(d, 1); d += 2; battle.last_damage = @truncate(u16, d); return true; } fn adjustDamage(battle: anytype, player: Player) u16 { const side = battle.side(player); const foe = battle.foe(player); const types = foe.active.types; const move = Move.get(side.last_selected_move); var d = battle.last_damage; if (side.active.types.includes(move.type)) d +%= d / 2; const neutral = @enumToInt(Effectiveness.Neutral); const type1: u16 = @enumToInt(move.type.effectiveness(types.type1)); const type2: u16 = @enumToInt(move.type.effectiveness(types.type2)); const total = if (types.type1 == types.type2) type1 * neutral else type1 * type2; // Pokémon Showdown considers the "total type" effectiveness instead of the individual types if (showdown and total == Effectiveness.neutral) { battle.last_damage = d; return total; } if (types.type1 == types.type2) { if (type1 != neutral) d = d *% type1 / 10; } else { if (type1 != neutral) d = d *% type1 / 10; if (type2 != neutral) d = d *% type2 / 10; } battle.last_damage = d; return total; } fn randomizeDamage(battle: anytype) void { if (battle.last_damage <= 1) return; const random = if (showdown) battle.rng.range(u8, 217, 256) else loop: { while (true) { const r = std.math.rotr(u8, battle.rng.next(), 1); if (r >= 217) break :loop r; } }; battle.last_damage = @truncate(u16, @as(u32, battle.last_damage) *% random / 255); } fn specialDamage(battle: anytype, player: Player, move: Move.Data, log: anytype) !?Result { const side = battle.side(player); if (!try checkHit(battle, player, move, log)) return null; battle.last_damage = switch (side.last_selected_move) { .SuperFang => @maximum(battle.foe(player).active.stats.hp / 2, 1), .SeismicToss, .NightShade => side.stored().level, .SonicBoom => 20, .DragonRage => 40, // GLITCH: if power = 0 then a desync occurs (or a miss on Pokémon Showdown) .Psywave => power: { const max = @truncate(u8, @as(u16, side.stored().level) * 3 / 2); if (showdown) { break :power battle.rng.range(u8, 0, max); } else { // GLITCH: Psywave infinite glitch loop if (max <= 1) return Result.Error; while (true) { const r = battle.rng.next(); if (r < max) break :power r; } } }, else => unreachable, }; if (battle.last_damage == 0) return if (showdown) null else Result.Error; _ = try applyDamage(battle, player.foe(), player.foe(), log); return null; } fn counterDamage(battle: anytype, player: Player, move: Move.Data, log: anytype) !?Result { const foe = battle.foe(player); if (battle.last_damage == 0) { try log.fail(battle.active(player), .None); return null; } // Pretend Counter was used as a stand-in when no move has been used to fail below with 0 BP const foe_last_used_move = Move.get(if (foe.last_used_move == .None) .Counter else foe.last_used_move); const foe_last_selected_move = Move.get(if (foe.last_selected_move == .None) .Counter else foe.last_selected_move); const used = foe_last_used_move.bp == 0 or foe.last_used_move == .Counter or foe_last_used_move.type != .Normal or foe_last_used_move.type != .Fighting; const selected = foe_last_selected_move.bp == 0 or foe.last_selected_move == .Counter or foe_last_selected_move.type != .Normal or foe_last_selected_move.type != .Fighting; if (!used and !selected) { try log.fail(battle.active(player), .None); return null; } if (!used or !selected) { // GLITCH: Counter desync (covered by Desync Clause Mod on Pokémon Showdown) if (!showdown) return Result.Error; try log.fail(battle.active(player), .None); return null; } battle.last_damage = if (battle.last_damage > 0x7FFF) 0xFFFF else battle.last_damage * 2; // Pokémon Showdown calls checkHit before Counter if (!showdown and !try checkHit(battle, player, move, log)) return null; _ = try applyDamage(battle, player.foe(), player.foe(), log); return null; } fn applyDamage(battle: anytype, target_player: Player, sub_player: Player, log: anytype) !bool { assert(battle.last_damage != 0 or showdown); var target = battle.side(target_player); // GLITCH: Substitute + Confusion glitch // We check if the target has a Substitute but then apply damage to the "sub player" which // isn't guaranteed to be the same (eg. crash or confusion damage) or to even have a Substitute if (target.active.volatiles.Substitute) { var subbed = battle.side(sub_player); if (!subbed.active.volatiles.Substitute) return false; if (battle.last_damage >= subbed.active.volatiles.substitute) { subbed.active.volatiles.substitute = 0; subbed.active.volatiles.Substitute = false; // battle.last_damage is not updated with the amount of HP the Substitute had try log.end(battle.active(sub_player), .Substitute); return true; } else { // Safe to truncate since less than subbed.volatiles.substitute which is a u8 subbed.active.volatiles.substitute -= @truncate(u8, battle.last_damage); try log.activate(battle.active(sub_player), .Substitute); } // Attacking a Substitute with Hyper Beam never causes a recharge on Pokémon Showdown if (showdown) battle.foe(target_player).active.volatiles.Recharging = false; } else { if (battle.last_damage > target.stored().hp) battle.last_damage = target.stored().hp; target.stored().hp -= battle.last_damage; try log.damage(battle.active(target_player), target.stored(), .None); } return false; } fn mirrorMove(battle: anytype, player: Player, choice: Choice, log: anytype) !?Result { var side = battle.side(player); const foe = battle.foe(player); if (foe.last_used_move == .None or foe.last_used_move == .MirrorMove) { try log.lastmiss(); try log.miss(battle.active(player)); return null; } side.last_selected_move = foe.last_used_move; if (!try canMove(battle, player, choice, true, .MirrorMove, log)) return null; return doMove(battle, player, choice, .MirrorMove, log); } fn metronome(battle: anytype, player: Player, choice: Choice, log: anytype) !?Result { var side = battle.side(player); side.last_selected_move = if (showdown) blk: { const r = battle.rng.range(u8, 0, @enumToInt(Move.Struggle) - 2); const mod = @as(u2, (if (r < @enumToInt(Move.Metronome) - 1) 1 else 2)); break :blk @intToEnum(Move, r + mod); } else loop: { while (true) { const r = battle.rng.next(); if (r == 0 or r == @enumToInt(Move.Metronome)) continue; if (r >= @enumToInt(Move.Struggle)) continue; break :loop @intToEnum(Move, r); } }; if (!try canMove(battle, player, choice, true, .Metronome, log)) return null; return doMove(battle, player, choice, .Metronome, log); } fn checkHit(battle: anytype, player: Player, move: Move.Data, log: anytype) !bool { var immune = false; var mist = false; if (moveHit(battle, player, move, &immune, &mist)) return true; assert(!immune); if (mist) { assert(!showdown); try log.activate(battle.active(player.foe()), .Mist); try log.fail(battle.active(player.foe()), .None); } else { try log.lastmiss(); try log.miss(battle.active(player)); } return false; } fn moveHit(battle: anytype, player: Player, move: Move.Data, immune: *bool, mist: *bool) bool { var side = battle.side(player); const foe = battle.foe(player); var miss = miss: { assert(!side.active.volatiles.Bide); if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) { immune.* = true; break :miss true; } if (move.effect == .Swift) return true; if (foe.active.volatiles.Invulnerable) break :miss true; // Hyper Beam + Sleep glitch needs to be special cased here due to control flow differences if (showdown and move.effect == .Sleep and foe.active.volatiles.Recharging) return true; // Conversion / Haze / Light Screen / Reflect qualify but do not call moveHit if (foe.active.volatiles.Mist and move.effect.isStatDown()) { mist.* = true; if (!showdown) break :miss true; } // GLITCH: Thrash / Petal Dance / Rage get their accuracy overwritten on subsequent hits var state = &side.active.volatiles.state; const overwritten = (move.effect == .Thrashing or move.effect == .Rage) and state.* > 0; assert(!overwritten or (0 < state.* and state.* < 255 and !side.active.volatiles.Bide)); var accuracy = if (!showdown and overwritten) state.* else @as(u16, Gen12.percent(move.accuracy)); var boost = BOOSTS[@intCast(u4, @as(i8, side.active.boosts.accuracy) + 6)]; accuracy = accuracy * boost[0] / boost[1]; boost = BOOSTS[@intCast(u4, @as(i8, -foe.active.boosts.evasion) + 6)]; accuracy = accuracy * boost[0] / boost[1]; accuracy = @minimum(255, @maximum(1, accuracy)); state.* = accuracy; // GLITCH: max accuracy is 255 so 1/256 chance of miss break :miss if (showdown) !battle.rng.chance(u8, @truncate(u8, accuracy), 256) else battle.rng.next() >= accuracy; }; // Pokémon Showdown reports miss instead of fail for moves blocked by Mist that 1/256 miss if (showdown and mist.*) { mist.* = !miss; miss = true; } if (!miss) return true; battle.last_damage = 0; side.active.volatiles.Trapping = false; return false; } fn checkFaint( battle: anytype, player: Player, log: anytype, ) @TypeOf(log).Error!?Result { const side = battle.side(player); if (side.stored().hp > 0) return null; const foe = battle.foe(player); const foe_fainted = foe.stored().hp == 0; const player_out = findFirstAlive(side) == 0; const foe_out = findFirstAlive(foe) == 0; const tie = player_out and foe_out; const more = tie or player_out or foe_out; if (try faint(battle, player, log, !(more or foe_fainted))) |r| return r; if (foe_fainted) if (try faint(battle, player.foe(), log, !more)) |r| return r; if (tie) { try log.tie(); return Result.Tie; } else if (player_out) { try log.win(player.foe()); return if (player == .P1) Result.Lose else Result.Win; } else if (foe_out) { try log.win(player); return if (player == .P1) Result.Win else Result.Lose; } // Emitting |request| for each side will advance the RNG by 2 for each "locked" move if (showdown) { const locked = @as(u2, @boolToInt(isLocked(side.active))) + @as(u2, @boolToInt(!foe_fainted and isLocked(foe.active))); battle.rng.advance(locked * 2); } const foe_choice: Choice.Type = if (foe_fainted) .Switch else .Pass; if (player == .P1) return Result{ .p1 = .Switch, .p2 = foe_choice }; return Result{ .p1 = foe_choice, .p2 = .Switch }; } fn faint(battle: anytype, player: Player, log: anytype, done: bool) !?Result { var side = battle.side(player); var foe = battle.foe(player); assert(side.stored().hp == 0); var foe_volatiles = &foe.active.volatiles; foe_volatiles.MultiHit = false; if (foe_volatiles.Bide) { assert(!foe_volatiles.Thrashing and !foe_volatiles.Rage); foe_volatiles.state = if (showdown) 0 else foe_volatiles.state & 255; if (foe_volatiles.state != 0) return Result.Error; } side.active.volatiles = .{}; side.last_used_move = .None; try log.faint(battle.active(player), done); return null; } fn handleResidual(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var stored = side.stored(); const ident = battle.active(player); var volatiles = &side.active.volatiles; const brn = Status.is(stored.status, .BRN); if (brn or Status.is(stored.status, .PSN)) { var damage = @maximum(stored.stats.hp / 16, 1); if (volatiles.Toxic) { volatiles.toxic += 1; damage *= volatiles.toxic; } stored.hp -= @minimum(damage, stored.hp); // Pokémon Showdown uses damageOf here but its not relevant in Generation I try log.damage(ident, stored, if (brn) Damage.Burn else Damage.Poison); } if (volatiles.LeechSeed) { var damage = @maximum(stored.stats.hp / 16, 1); // GLITCH: Leech Seed + Toxic glitch if (volatiles.Toxic) { volatiles.toxic += 1; damage *= volatiles.toxic; } stored.hp -= @minimum(damage, stored.hp); var foe = battle.foe(player); var foe_stored = foe.stored(); const foe_ident = battle.active(player.foe()); // As above, Pokémon Showdown uses damageOf but its not relevant try log.damage(ident, stored, .LeechSeed); const before = foe_stored.hp; // Uncapped damage is added back to the foe foe_stored.hp = @minimum(foe_stored.hp + damage, foe_stored.stats.hp); // Pokémon Showdown uses the less specific heal here instead of drain... because reasons? if (foe_stored.hp > before) try log.heal(foe_ident, foe_stored, .Silent); } } fn endTurn(battle: anytype, log: anytype) @TypeOf(log).Error!Result { if (showdown and options.ebc and checkEBC(battle)) { try log.tie(); return Result.Tie; } battle.turn += 1; if (showdown and battle.turn >= 1000) { try log.tie(); return Result.Tie; } else if (battle.turn >= 65535) { return Result.Error; } try log.turn(battle.turn); // Emitting |request| for each side will advance the RNG by 2 for each "locked" move if (showdown) { const locked = @as(u2, @boolToInt(isLocked(battle.side(.P1).active))) + @as(u2, @boolToInt(isLocked(battle.side(.P2).active))); battle.rng.advance(locked * 2); } return Result.Default; } fn checkEBC(battle: anytype) bool { ebc: for (battle.sides) |side, i| { var foe_all_ghosts = true; var foe_all_transform = true; for (battle.sides[~@truncate(u1, i)].pokemon) |pokemon| { if (pokemon.species == .None) continue; const ghost = pokemon.hp == 0 or pokemon.types.includes(.Ghost); foe_all_ghosts = foe_all_ghosts and ghost; foe_all_transform = foe_all_transform and pokemon.hp == 0 or transform: { for (pokemon.moves) |m| { if (m.id == .None) break :transform true; if (m.id != .Transform) break :transform false; } break :transform true; }; } for (side.pokemon) |pokemon| { if (pokemon.hp == 0 or Status.is(pokemon.status, .FRZ)) continue; const transform = foe_all_transform and transform: { for (pokemon.moves) |m| { if (m.id == .None) break :transform true; if (m.id != .Transform) break :transform false; } break :transform true; }; if (transform) continue; const no_pp = foe_all_ghosts and no_pp: { for (pokemon.moves) |m| { if (m.pp != 0) break :no_pp false; } break :no_pp true; }; if (no_pp) continue; continue :ebc; } return true; } return false; } fn moveEffect(battle: anytype, player: Player, move: Move.Data, mslot: u8, log: anytype) !void { return switch (move.effect) { .Bide => Effects.bide(battle, player, log), .BurnChance1, .BurnChance2 => Effects.burnChance(battle, player, move, log), .Confusion, .ConfusionChance => Effects.confusion(battle, player, move, log), .Conversion => Effects.conversion(battle, player, log), .Disable => Effects.disable(battle, player, move, log), .DrainHP, .DreamEater => Effects.drainHP(battle, player, log), .Explode => Effects.explode(battle, player), .FlinchChance1, .FlinchChance2 => Effects.flinchChance(battle, player, move), .FocusEnergy => Effects.focusEnergy(battle, player, log), .FreezeChance => Effects.freezeChance(battle, player, move, log), .Haze => Effects.haze(battle, player, log), .Heal => Effects.heal(battle, player, log), .HyperBeam => Effects.hyperBeam(battle, player), .LeechSeed => Effects.leechSeed(battle, player, move, log), .LightScreen => Effects.lightScreen(battle, player, log), .Mimic => Effects.mimic(battle, player, move, mslot, log), .Mist => Effects.mist(battle, player, log), .MultiHit, .DoubleHit, .Twineedle => Effects.multiHit(battle, player, move), .Paralyze => Effects.paralyze(battle, player, move, log), .ParalyzeChance1, .ParalyzeChance2 => Effects.paralyzeChance(battle, player, move, log), .PayDay => Effects.payDay(log), .Poison, .PoisonChance1, .PoisonChance2 => Effects.poison(battle, player, move, log), .Rage => Effects.rage(battle, player), .Recoil => Effects.recoil(battle, player, log), .Reflect => Effects.reflect(battle, player, log), .Sleep => Effects.sleep(battle, player, move, log), .Splash => Effects.splash(battle, player, log), .Substitute => Effects.substitute(battle, player, log), .SwitchAndTeleport => Effects.switchAndTeleport(battle, player, move, log), .Transform => Effects.transform(battle, player, log), // zig fmt: off .AttackUp1, .AttackUp2, .DefenseUp1, .DefenseUp2, .EvasionUp1, .SpecialUp1, .SpecialUp2, .SpeedUp2 => Effects.boost(battle, player, move, log), .AccuracyDown1, .AttackDown1, .DefenseDown1, .DefenseDown2, .SpeedDown1, .AttackDownChance, .DefenseDownChance, .SpecialDownChance, .SpeedDownChance => Effects.unboost(battle, player, move, log), // zig fmt: on else => {}, }; } pub const Effects = struct { fn bide(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); side.active.volatiles.Bide = true; assert(!side.active.volatiles.Thrashing and !side.active.volatiles.Rage); side.active.volatiles.state = 0; side.active.volatiles.attacks = @truncate(u3, if (showdown) battle.rng.range(u4, 3, 5) - 1 else (battle.rng.next() & 1) + 2); try log.start(battle.active(player), .Bide); } fn burnChance(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); // GLITCH: Freeze top move selection desync can occur if thawed Pokémon is slower if (Status.is(foe_stored.status, .FRZ)) { assert(move.type == .Fire); foe_stored.status = 0; } if (foe.active.volatiles.Substitute or Status.any(foe_stored.status)) { return log.fail( battle.active(player.foe()), if (Status.is(foe_stored.status, .BRN)) .Burn else .None, ); } const chance = !foe.active.types.includes(move.type) and if (showdown) battle.rng.chance(u8, @as(u8, if (move.effect == .BurnChance1) 26 else 77), 256) else battle.rng.next() < 1 + (if (move.effect == .BurnChance1) Gen12.percent(10) else Gen12.percent(30)); if (!chance) return; if (showdown) battle.rng.advance(1); foe_stored.status = Status.init(.BRN); foe.active.stats.atk = @maximum(foe.active.stats.atk / 2, 1); try log.status(battle.active(player.foe()), foe_stored.status, .None); } fn charge(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var volatiles = &side.active.volatiles; volatiles.Charging = true; const move = side.last_selected_move; if (move == .Fly or move == .Dig) volatiles.Invulnerable = true; try log.prepare(battle.active(player), move); } fn confusion(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); if (move.effect == .ConfusionChance) { // Substitute incorrectly blocks secondary effect confusion on Pokémon Showdown if (showdown and foe.active.volatiles.Substitute) return; const chance = if (showdown) // Due to a Pokémon Showdown bug this is incorrectly 26 instead of 25 battle.rng.chance(u8, 26, 256) else battle.rng.next() < Gen12.percent(10); if (!chance) return; } else if (foe.active.volatiles.Substitute or !try checkHit(battle, player, move, log)) return; if (foe.active.volatiles.Confusion) return; foe.active.volatiles.Confusion = true; foe.active.volatiles.confusion = @truncate(u3, if (showdown) battle.rng.range(u8, 2, 6) else (battle.rng.next() & 3) + 2); try log.start(battle.active(player.foe()), .Confusion); } fn conversion(battle: anytype, player: Player, log: anytype) !void { const foe = battle.foe(player); if (foe.active.volatiles.Invulnerable) { return log.miss(battle.active(player)); } battle.side(player).active.types = foe.active.types; return log.typechange(battle.active(player), foe.active.types); } fn disable(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var volatiles = &foe.active.volatiles; const foe_ident = battle.active(player.foe()); if (!try checkHit(battle, player, move, log)) return; if (volatiles.disabled.move != 0) { try log.lastmiss(); return log.miss(battle.active(player)); } const moves = &foe.active.moves; // Pokémon Showdown incorrectly does not check for moves with 0 PP volatiles.disabled.move = randomMoveSlot(&battle.rng, moves, !showdown); // On Pokémon Showdown this range is incorrectly 2-7 instead of 1-8 volatiles.disabled.duration = @truncate(u4, if (showdown) battle.rng.range(u8, 1, 7) + 1 else (battle.rng.next() & 7) + 1); try log.startEffect(foe_ident, .Disable, moves[volatiles.disabled.move].id); } fn drainHP(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var stored = side.stored(); const drain = @maximum(battle.last_damage / 2, 1); // Pokémon Showdown doesn't update `Battle.lastDamage` here which only matters for the // self-Counter glitch (Grass/Bug move damage would not be Counter-able otherwise) if (!showdown) battle.last_damage = drain; if (stored.hp == stored.stats.hp) return; stored.hp = @minimum(stored.stats.hp, stored.hp + drain); try log.drain(battle.active(player), stored, battle.active(player.foe())); } fn explode(battle: anytype, player: Player) !void { var side = battle.side(player); var stored = side.stored(); stored.hp = 0; stored.status = 0; side.active.volatiles.LeechSeed = false; } fn flinchChance(battle: anytype, player: Player, move: Move.Data) void { var volatiles = &battle.foe(player).active.volatiles; if (volatiles.Substitute) return; const chance = if (showdown) battle.rng.chance(u8, @as(u8, if (move.effect == .FlinchChance1) 26 else 77), 256) else battle.rng.next() < 1 + (if (move.effect == .FlinchChance1) Gen12.percent(10) else Gen12.percent(30)); if (!chance) return; volatiles.Flinch = true; // Pokémon Showdown incorrectly does not cancel recharging on flinch if (!showdown) volatiles.Recharging = false; } fn focusEnergy(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); if (side.active.volatiles.FocusEnergy) return; side.active.volatiles.FocusEnergy = true; try log.start(battle.active(player), .FocusEnergy); } fn freezeChance(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); const foe_ident = battle.active(player.foe()); if (foe.active.volatiles.Substitute or Status.any(foe_stored.status)) { return log.fail( foe_ident, if (Status.is(foe_stored.status, .FRZ)) .Freeze else .None, ); } const chance = !foe.active.types.includes(move.type) and if (showdown) battle.rng.chance(u8, 26, 256) else battle.rng.next() < 1 + Gen12.percent(10); if (!chance) return; // Freeze Clause Mod if (showdown) { battle.rng.advance(1); for (foe.pokemon) |p| { if (Status.is(p.status, .FRZ)) return log.fail(foe_ident, .Freeze); } } foe_stored.status = Status.init(.FRZ); // GLITCH: Hyper Beam recharging status is not cleared try log.status(foe_ident, foe_stored.status, .None); } fn haze(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var foe = battle.foe(player); var side_stored = side.stored(); var foe_stored = foe.stored(); const player_ident = battle.active(player); const foe_ident = battle.active(player.foe()); side.active.boosts = .{}; foe.active.boosts = .{}; side.active.stats = side_stored.stats; foe.active.stats = foe_stored.stats; try log.activate(player_ident, .Haze); try log.clearallboost(); if (Status.any(foe_stored.status)) { // Pokémon Showdown incorrectly does not prevent sleep/freeze from moving immediately if (!showdown) { if (Status.is(foe_stored.status, .FRZ) or Status.is(foe_stored.status, .SLP)) { foe.last_selected_move = .SKIP_TURN; } } try log.curestatus(foe_ident, foe_stored.status, .Silent); foe_stored.status = 0; } try clearVolatiles(&side.active, player_ident, log); try clearVolatiles(&foe.active, foe_ident, log); } fn heal(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var stored = side.stored(); const ident = battle.active(player); // GLITCH: HP recovery move failure glitches const delta = stored.stats.hp - stored.hp; if (delta == 0 or delta & 255 == 255) return try log.fail(ident, .None); const rest = side.last_selected_move == .Rest; if (rest) { // Adding the sleep status runs the sleep condition handler to roll duration as well // as rolling for the the "speed tie" between Sleep Clause Mod / Freeze Clause Mod if (showdown) battle.rng.advance(2); stored.status = Status.slf(2); try log.statusFrom(ident, stored.status, Move.Rest); stored.hp = stored.stats.hp; } else { stored.hp = @minimum(stored.stats.hp, stored.hp + (stored.stats.hp / 2)); } try log.heal(ident, stored, if (rest) Heal.Silent else Heal.None); } fn hyperBeam(battle: anytype, player: Player) !void { battle.side(player).active.volatiles.Recharging = true; } fn leechSeed(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); if (showdown) { if (foe.active.types.includes(.Grass)) { return log.immune(battle.active(player.foe()), .None); } if (!try checkHit(battle, player, move, log)) return; if (foe.active.volatiles.LeechSeed) return; } else { if (!try checkHit(battle, player, move, log)) return; if (foe.active.types.includes(.Grass) or foe.active.volatiles.LeechSeed) { try log.lastmiss(); return log.miss(battle.active(player)); } } foe.active.volatiles.LeechSeed = true; try log.start(battle.active(player.foe()), .LeechSeed); } fn lightScreen(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); if (side.active.volatiles.LightScreen) return log.fail(battle.active(player), .None); side.active.volatiles.LightScreen = true; try log.start(battle.active(player), .LightScreen); } fn mimic(battle: anytype, player: Player, move: Move.Data, mslot: u8, log: anytype) !void { var side = battle.side(player); var foe = battle.foe(player); // Pokémon Showdown incorrectly requires the user to have Mimic (but not necessarily at // mslot). In reality, Mimic can also be called via Metronome or Mirror Move assert(showdown or side.active.moves[mslot].id == .Mimic or side.active.moves[mslot].id == .Metronome or side.active.moves[mslot].id == .MirrorMove); // Pokémon Showdown incorrectly replaces the existing Mimic's slot instead of mslot var oslot = mslot; // Pokémon Showdown considers Mimic to never miss instead of having 100% accuracy if (showdown) { const has_mimic = has_mimic: { for (side.active.moves) |m, i| { if (m.id == .Mimic) { oslot = @truncate(u8, i + 1); break :has_mimic true; } } break :has_mimic false; }; if (!has_mimic) return; } else if (!try checkHit(battle, player, move, log)) { return; } const moves = &foe.active.moves; const rslot = randomMoveSlot(&battle.rng, moves, false); side.active.moves[oslot].id = moves[rslot].id; try log.startEffect(battle.active(player), .Mimic, moves[rslot].id); } fn mist(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); if (side.active.volatiles.Mist) return; side.active.volatiles.Mist = true; try log.start(battle.active(player), .Mist); } fn multiHit(battle: anytype, player: Player, move: Move.Data) void { var side = battle.side(player); assert(!side.active.volatiles.MultiHit); side.active.volatiles.MultiHit = true; side.active.volatiles.attacks = if (move.effect == .MultiHit) distribution(battle) else 2; } fn paralyze(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); const foe_ident = battle.active(player.foe()); // Only Thunder Wave checks for type-immunity, not Glare const immune = move.type == .Electric and foe.active.types.immune(move.type); if (showdown) { if (immune) return log.immune(foe_ident, .None); if (!try checkHit(battle, player, move, log)) return; } if (Status.any(foe_stored.status)) { return log.fail( foe_ident, if (Status.is(foe_stored.status, .PAR)) .Paralysis else .None, ); } if (!showdown) { if (immune) return log.immune(foe_ident, .None); if (!try checkHit(battle, player, move, log)) return; } if (showdown) battle.rng.advance(1); foe_stored.status = Status.init(.PAR); foe.active.stats.spe = @maximum(foe.active.stats.spe / 4, 1); try log.status(foe_ident, foe_stored.status, .None); } fn paralyzeChance(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); if (foe.active.volatiles.Substitute or Status.any(foe_stored.status)) { return log.fail( battle.active(player.foe()), if (Status.is(foe_stored.status, .PAR)) .Paralysis else .None, ); } // Body Slam can't paralyze a Normal type Pokémon const chance = !foe.active.types.includes(move.type) and if (showdown) battle.rng.chance(u8, @as(u8, if (move.effect == .ParalyzeChance1) 26 else 77), 256) else battle.rng.next() < 1 + (if (move.effect == .ParalyzeChance1) Gen12.percent(10) else Gen12.percent(30)); if (!chance) return; if (showdown) battle.rng.advance(1); foe_stored.status = Status.init(.PAR); foe.active.stats.spe = @maximum(foe.active.stats.spe / 4, 1); try log.status(battle.active(player.foe()), foe_stored.status, .None); } fn payDay(log: anytype) !void { try log.fieldactivate(); } fn poison(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); const foe_ident = battle.active(player.foe()); if (showdown and move.effect == .Poison and !try checkHit(battle, player, move, log)) { return; } const cant = foe.active.volatiles.Substitute or Status.any(foe_stored.status) or foe.active.types.includes(.Poison); if (cant) { return log.fail(foe_ident, if (Status.is(foe_stored.status, .PSN)) .Poison else .None); } if (move.effect == .Poison) { if (!showdown and !try checkHit(battle, player, move, log)) return; } else { const chance = if (showdown) battle.rng.chance(u8, @as(u8, if (move.effect == .PoisonChance1) 52 else 103), 256) else battle.rng.next() < 1 + (if (move.effect == .PoisonChance1) Gen12.percent(20) else Gen12.percent(40)); if (!chance) return; } if (showdown) battle.rng.advance(1); foe_stored.status = Status.init(.PSN); if (battle.side(player).last_selected_move == .Toxic) { foe.active.volatiles.Toxic = true; foe.active.volatiles.toxic = 0; } try log.status(foe_ident, foe_stored.status, .None); } fn rage(battle: anytype, player: Player) !void { var volatiles = &battle.side(player).active.volatiles; volatiles.Rage = true; assert(!volatiles.Bide); volatiles.state = 0; } fn recoil(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); var stored = side.stored(); const damage = @maximum(battle.last_damage / @as(u8, if (side.last_selected_move == .Struggle) 2 else 4), 1); stored.hp = @maximum(stored.hp - damage, 0); try log.damageOf(battle.active(player), stored, .RecoilOf, battle.active(player.foe())); } fn reflect(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); if (side.active.volatiles.Reflect) return log.fail(battle.active(player), .None); side.active.volatiles.Reflect = true; try log.start(battle.active(player), .Reflect); } fn sleep(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); var foe_stored = foe.stored(); const foe_ident = battle.active(player.foe()); if (foe.active.volatiles.Recharging) { foe.active.volatiles.Recharging = false; // Hit test not applied if the target is recharging (bypass) } else { if (Status.any(foe_stored.status)) { return log.fail( foe_ident, if (Status.is(foe_stored.status, .SLP)) .Sleep else .None, ); } // If checkHit in doMove didn't return true Pokémon Showdown wouldn't be in here if (!showdown and !try checkHit(battle, player, move, log)) return; } // Sleep Clause Mod if (showdown) { battle.rng.advance(1); for (foe.pokemon) |p| { if (Status.is(p.status, .SLP) and !Status.is(p.status, .SLF)) { return log.fail(foe_ident, .Sleep); } } } const duration = @truncate(u3, if (showdown) battle.rng.range(u8, 1, 8) else loop: { while (true) { const r = battle.rng.next() & 7; if (r != 0) break :loop r; } }); foe_stored.status = Status.slp(duration); try log.statusFrom(foe_ident, foe_stored.status, battle.side(player).last_selected_move); } fn splash(battle: anytype, player: Player, log: anytype) !void { try log.activate(battle.active(player), .Splash); } fn substitute(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); if (side.active.volatiles.Substitute) { try log.fail(battle.active(player), .Substitute); return; } assert(side.stored().stats.hp <= 1023); // Will be 0 if HP is <= 3 meaning that the user gets a 1 HP Substitute for "free" const hp = @truncate(u8, side.stored().stats.hp / 4); if (side.stored().hp < hp) { try log.fail(battle.active(player), .Weak); return; } // GLITCH: can leave the user with 0 HP (faints later) because didn't check '<=' above side.stored().hp -= hp; side.active.volatiles.substitute = hp + 1; side.active.volatiles.Substitute = true; try log.start(battle.active(player), .Substitute); try log.damage(battle.active(player), side.stored(), .None); } fn switchAndTeleport(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { if (!showdown or battle.side(player).last_selected_move == .Teleport) return; // Whirlwind/Roar should not roll to hit but Pokémon Showdown does anyway _ = try checkHit(battle, player, move, log); } fn thrashing(battle: anytype, player: Player) void { var volatiles = &battle.side(player).active.volatiles; volatiles.Thrashing = true; assert(!volatiles.Bide); volatiles.state = 0; volatiles.attacks = @truncate(u3, if (showdown) battle.rng.range(u8, 3, 5) - 1 else (battle.rng.next() & 1) + 2); } fn transform(battle: anytype, player: Player, log: anytype) !void { var side = battle.side(player); const foe = battle.foe(player); const foe_ident = battle.active(player.foe()); if (foe.active.volatiles.Invulnerable) return; side.active.volatiles.Transform = true; // foe could themselves be transformed side.active.volatiles.transform = if (foe.active.volatiles.transform != 0) foe.active.volatiles.transform else foe_ident.int(); // HP is not copied by Transform side.active.stats.atk = foe.active.stats.atk; side.active.stats.def = foe.active.stats.def; side.active.stats.spe = foe.active.stats.spe; side.active.stats.spc = foe.active.stats.spc; side.active.species = foe.active.species; side.active.types = foe.active.types; side.active.boosts = foe.active.boosts; for (foe.active.moves) |m, i| { side.active.moves[i].id = m.id; side.active.moves[i].pp = if (m.id != .None) 5 else 0; } try log.transform(battle.active(player), foe_ident); } fn trapping(battle: anytype, player: Player) void { var side = battle.side(player); var foe = battle.foe(player); if (side.active.volatiles.Trapping) return; side.active.volatiles.Trapping = true; // GLITCH: Hyper Beam automatic selection glitch if Recharging gets cleared on miss // (Pokémon Showdown unitentionally patches this glitch, preventing automatic selection) if (!showdown) foe.active.volatiles.Recharging = false; side.active.volatiles.attacks = distribution(battle); } fn boost(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var side = battle.side(player); const ident = battle.active(player); var stats = &side.active.stats; var boosts = &side.active.boosts; switch (move.effect) { .AttackUp1, .AttackUp2, .Rage => { assert(boosts.atk >= -6 and boosts.atk <= 6); if (boosts.atk == 6) return try log.fail(ident, .None); const n: u2 = if (move.effect == .AttackUp2) 2 else 1; boosts.atk = @truncate(i4, @minimum(6, @as(i8, boosts.atk) + n)); if (!showdown and stats.atk == MAX_STAT_VALUE) { boosts.atk -= 1; return try log.fail(ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.atk) + 6)]; const stat = unmodifiedStats(battle, player).atk; stats.atk = @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1]); try log.boost(ident, if (move.effect == .Rage) .Rage else .Attack, n); }, .DefenseUp1, .DefenseUp2 => { assert(boosts.def >= -6 and boosts.def <= 6); if (boosts.def == 6) return try log.fail(ident, .None); const n: u2 = if (move.effect == .DefenseUp2) 2 else 1; boosts.def = @truncate(i4, @minimum(6, @as(i8, boosts.def) + n)); if (!showdown and stats.def == MAX_STAT_VALUE) { boosts.def -= 1; return try log.fail(ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.def) + 6)]; const stat = unmodifiedStats(battle, player).def; stats.def = @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1]); try log.boost(ident, .Defense, n); }, .SpeedUp2 => { assert(boosts.spe >= -6 and boosts.spe <= 6); if (boosts.spe == 6) return try log.fail(ident, .None); boosts.spe = @truncate(i4, @minimum(6, @as(i8, boosts.spe) + 1)); if (!showdown and stats.spe == MAX_STAT_VALUE) { boosts.spe -= 1; return try log.fail(ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.spe) + 6)]; const stat = unmodifiedStats(battle, player).spe; stats.spe = @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1]); try log.boost(ident, .Speed, 1); }, .SpecialUp1, .SpecialUp2 => { assert(boosts.spc >= -6 and boosts.spc <= 6); if (boosts.spc == 6) return try log.fail(ident, .None); const n: u2 = if (move.effect == .SpecialUp2) 2 else 1; boosts.spc = @truncate(i4, @minimum(6, @as(i8, boosts.spc) + n)); if (!showdown and stats.spc == MAX_STAT_VALUE) { boosts.spc -= 1; return try log.fail(ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.spc) + 6)]; const stat = unmodifiedStats(battle, player).spc; stats.spc = @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1]); try log.boost(ident, .SpecialAttack, n); try log.boost(ident, .SpecialDefense, n); }, .EvasionUp1 => { assert(boosts.evasion >= -6 and boosts.evasion <= 6); if (boosts.evasion == 6) return try log.fail(ident, .None); boosts.evasion = @truncate(i4, @minimum(6, @as(i8, boosts.evasion) + 1)); try log.boost(ident, .Evasion, 1); }, else => unreachable, } // GLITCH: Stat modification errors glitch statusModify(battle.foe(player).stored().status, &battle.foe(player).active.stats); } fn unboost(battle: anytype, player: Player, move: Move.Data, log: anytype) !void { var foe = battle.foe(player); const foe_ident = battle.active(player.foe()); if (foe.active.volatiles.Substitute) return; if (move.effect.isStatDownChance()) { const chance = if (showdown) battle.rng.chance(u8, 85, 256) else battle.rng.next() < Gen12.percent(33) + 1; if (!chance or foe.active.volatiles.Invulnerable) return; } else if (!showdown and !try checkHit(battle, player, move, log)) { return; // checkHit already checks for Invulnerable } var stats = &foe.active.stats; var boosts = &foe.active.boosts; switch (move.effect) { .AttackDown1, .AttackDownChance => { assert(boosts.atk >= -6 and boosts.atk <= 6); if (boosts.atk == -6) return try log.fail(foe_ident, .None); boosts.atk = @truncate(i4, @maximum(-6, @as(i8, boosts.atk) - 1)); if (!showdown and stats.atk == 1) { boosts.atk += 1; return try log.fail(foe_ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.atk) + 6)]; const stat = unmodifiedStats(battle, player.foe()).atk; if (showdown) { stats.atk = @maximum(1, @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1])); } else { stats.atk = @maximum(1, stat * mod[0] / mod[1]); } try log.unboost(foe_ident, .Attack, 1); }, .DefenseDown1, .DefenseDown2, .DefenseDownChance => { assert(boosts.def >= -6 and boosts.def <= 6); if (boosts.def == -6) return try log.fail(foe_ident, .None); const n: u2 = if (move.effect == .DefenseDown2) 2 else 1; boosts.def = @truncate(i4, @maximum(-6, @as(i8, boosts.def) - n)); if (!showdown and stats.def == 1) { boosts.def += 1; return try log.fail(foe_ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.def) + 6)]; const stat = unmodifiedStats(battle, player.foe()).def; if (showdown) { stats.def = @maximum(1, @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1])); } else { stats.def = @maximum(1, stat * mod[0] / mod[1]); } try log.unboost(foe_ident, .Defense, n); }, .SpeedDown1, .SpeedDownChance => { assert(boosts.spe >= -6 and boosts.spe <= 6); if (boosts.spe == -6) return try log.fail(foe_ident, .None); boosts.spe = @truncate(i4, @maximum(-6, @as(i8, boosts.spe) - 1)); if (!showdown and stats.spe == 1) { boosts.spe += 1; return try log.fail(foe_ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.spe) + 6)]; const stat = unmodifiedStats(battle, player.foe()).spe; if (showdown) { stats.spe = @maximum(1, @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1])); } else { stats.spe = @maximum(1, stat * mod[0] / mod[1]); } try log.unboost(foe_ident, .Speed, 1); assert(boosts.spe >= -6); }, .SpecialDownChance => { assert(boosts.spc >= -6 and boosts.spc <= 6); if (boosts.spc == -6) return try log.fail(foe_ident, .None); boosts.spc = @truncate(i4, @maximum(-6, @as(i8, boosts.spc) - 1)); if (!showdown and stats.spc == 1) { boosts.spc += 1; return try log.fail(foe_ident, .None); } var mod = BOOSTS[@intCast(u4, @as(i8, boosts.spc) + 6)]; const stat = unmodifiedStats(battle, player.foe()).spc; if (showdown) { stats.spc = @maximum(1, @minimum(MAX_STAT_VALUE, stat * mod[0] / mod[1])); } else { stats.spc = @maximum(1, stat * mod[0] / mod[1]); } try log.unboost(foe_ident, .SpecialAttack, 1); try log.unboost(foe_ident, .SpecialDefense, 1); }, .AccuracyDown1 => { assert(boosts.accuracy >= -6 and boosts.accuracy <= 6); if (boosts.accuracy == -6) return try log.fail(foe_ident, .None); boosts.accuracy = @truncate(i4, @maximum(-6, @as(i8, boosts.accuracy) - 1)); try log.unboost(foe_ident, .Accuracy, 1); }, else => unreachable, } // GLITCH: Stat modification errors glitch statusModify(foe.stored().status, stats); } }; fn unmodifiedStats(battle: anytype, who: Player) *Stats(u16) { const side = battle.side(who); if (!side.active.volatiles.Transform) return &side.stored().stats; const id = ID.from(side.active.volatiles.transform); return &battle.side(id.player).pokemon[id.id].stats; } fn statusModify(status: u8, stats: *Stats(u16)) void { if (Status.is(status, .PAR)) { stats.spe = @maximum(stats.spe / 4, 1); } else if (Status.is(status, .BRN)) { stats.atk = @maximum(stats.atk / 2, 1); } } fn isLocked(active: ActivePokemon) bool { return active.volatiles.Recharging or active.volatiles.Rage or active.volatiles.Thrashing or active.volatiles.Charging; } fn clearVolatiles(active: *ActivePokemon, ident: ID, log: anytype) !void { var volatiles = &active.volatiles; if (volatiles.disabled.move != 0) { volatiles.disabled = .{}; try log.end(ident, .DisableSilent); } if (volatiles.Confusion) { // volatiles.confusion is left unchanged volatiles.Confusion = false; try log.end(ident, .ConfusionSilent); } if (volatiles.Mist) { volatiles.Mist = false; try log.end(ident, .Mist); } if (volatiles.FocusEnergy) { volatiles.FocusEnergy = false; try log.end(ident, .FocusEnergy); } if (volatiles.LeechSeed) { volatiles.LeechSeed = false; try log.end(ident, .LeechSeed); } if (volatiles.Toxic) { // volatiles.toxic is left unchanged volatiles.Toxic = false; // no protocol for clearing Toxic because Pokémon Showdown considers it a status } if (volatiles.LightScreen) { volatiles.LightScreen = false; try log.end(ident, .LightScreen); } if (volatiles.Reflect) { volatiles.Reflect = false; try log.end(ident, .Reflect); } } const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 }; fn distribution(battle: anytype) u3 { if (showdown) return DISTRIBUTION[battle.rng.range(u8, 0, DISTRIBUTION.len)]; const r = (battle.rng.next() & 3); return @truncate(u3, (if (r < 2) r else battle.rng.next() & 3) + 2); } fn randomMoveSlot(rand: anytype, moves: []MoveSlot, check_pp: bool) u4 { if (showdown) { var i: usize = moves.len; while (i > 0) { i -= 1; if (moves[i].id != .None and (!check_pp or moves[i].pp > 0)) { return rand.range(u4, 0, @truncate(u4, i)); } } unreachable; } while (true) { const r = @truncate(u4, rand.next() & 3); if (moves[r].id != .None and (!check_pp or moves[r].pp > 0)) return r; } } test "RNG agreement" { if (!showdown) return; var expected: [256]u32 = undefined; var i: usize = 0; while (i < expected.len) : (i += 1) { expected[i] = @truncate(u32, i * 0x1000000); } var spe = rng.FixedRNG(1, expected.len){ .rolls = expected }; var cfz = rng.FixedRNG(1, expected.len){ .rolls = expected }; var par = rng.FixedRNG(1, expected.len){ .rolls = expected }; var brn = rng.FixedRNG(1, expected.len){ .rolls = expected }; var eff = rng.FixedRNG(1, expected.len){ .rolls = expected }; i = 0; while (i < expected.len) : (i += 1) { try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1); try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1); try expectEqual(par.chance(u8, 63, 256), i < Gen12.percent(25)); try expectEqual(brn.chance(u8, 26, 256), i < Gen12.percent(10) + 1); try expectEqual(eff.chance(u8, 85, 256), i < Gen12.percent(33) + 1); } } pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 { var n: u8 = 0; switch (request) { .Pass => { out[n] = .{}; n += 1; }, .Switch => { const side = battle.side(player); var slot: u4 = 2; while (slot <= 6) : (slot += 1) { const id = side.order[slot - 1]; if (id == 0 or side.pokemon[id - 1].hp == 0) continue; out[n] = .{ .type = .Switch, .data = slot }; n += 1; } if (n == 0) { out[n] = .{}; n += 1; } }, .Move => { const side = battle.side(player); const foe = battle.foe(player); var active = side.active; const stored = side.stored(); // While players are not given any input options on the cartridge in these cases, // Pokémon Showdown instead produces a list with a single move that must be chosen. if (isLocked(active)) { out[n] = if (showdown) .{ .type = .Move, .data = 1 } else .{}; n += 1; return n; } if (!foe.active.volatiles.Trapping) { var slot: u4 = 2; while (slot <= 6) : (slot += 1) { const id = side.order[slot - 1]; if (id == 0 or side.pokemon[id - 1].hp == 0) continue; out[n] = .{ .type = .Switch, .data = slot }; n += 1; } } const limited = active.volatiles.Bide or active.volatiles.Trapping; // On the cartridge, all of these happen after "FIGHT" (indicating you are not // switching) but before you are allowed to select a move. Pokémon Showdown instead // either disables all other moves in the case of limited or requires you to select a // move normally if sleeping/frozen/trapped. if (!showdown and (limited or foe.active.volatiles.Trapping or Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP))) { out[n] = .{ .type = .Move, .data = 0 }; n += 1; return n; } var slot: u4 = 1; // Pokémon Showdown handles Bide and Trapping moves by checking if the move in question // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror // Move will not result in forcing the subsequent use unless the user also had the // proc-ed move in their moveset) and disabling all other moves. if (limited) { assert(showdown); assert(side.last_selected_move != .None); while (slot <= 4) : (slot += 1) { const m = active.moves[slot - 1]; if (m.id == .None) break; if (m.id == side.last_selected_move) { assert(m.pp > 0 or Move.get(m.id).effect == .Trapping); out[n] = .{ .type = .Move, .data = slot }; n += 1; return n; } } } const before = n; slot = 1; while (slot <= 4) : (slot += 1) { const m = active.moves[slot - 1]; if (m.id == .None) break; if (m.pp == 0) continue; if (active.volatiles.disabled.move == slot) continue; out[n] = .{ .type = .Move, .data = slot }; n += 1; } // Struggle (Pokémon Showdown would use 'move 1' here) if (n == before) { out[n] = .{ .type = .Move, .data = 0 }; n += 1; } }, } return n; }
src/lib/gen1/mechanics.zig
const std = @import("std"); const mem = std.mem; const math = std.math; pub const Error = error{ OutOfMemory, NoMinimum, Missing }; pub fn Art(comptime T: type) type { return extern struct { root: ?*Node, size: usize, allocator: *const std.mem.Allocator, const Tree = @This(); const max_prefix_len = 10; const BaseNode = extern struct { num_children: u8, partial_len: u8, partial: [max_prefix_len]u8 = [1]u8{0} ** max_prefix_len, }; fn SizedNode(comptime _num_keys: usize, comptime _num_children: usize) type { // work around for error: extern structs cannot contain fields of type '*[0]u8' const num_keys_adj = if (_num_keys == 0) 1 else _num_keys; return extern struct { num_children: u8, partial_len: u8, partial: [max_prefix_len]u8 = [1]u8{0} ** max_prefix_len, keys: *[num_keys_adj]u8, children: *[num_children]?*Node, const Self = @This(); pub const num_keys = num_keys_adj; pub const num_children = _num_children; pub fn baseNode(self: *Self) *BaseNode { return @ptrCast(*BaseNode, self); } }; } pub const Leaf = struct { value: T, key: []const u8, }; pub const Node4 = SizedNode(4, 4); pub const Node16 = SizedNode(16, 16); pub const Node48 = SizedNode(256, 48); pub const Node256 = SizedNode(0, 256); const NodeType = std.meta.Tag(Node); pub const Node = union(enum) { leaf: Leaf, node4: Node4, node16: Node16, node48: Node48, node256: Node256, pub fn baseNode(n: *Node) *BaseNode { return switch (n.*) { .node4 => n.node4.baseNode(), .node16 => n.node16.baseNode(), .node48 => n.node48.baseNode(), .node256 => n.node256.baseNode(), .leaf => unreachable, }; } pub fn childIterator(n: *Node) ChildIterator { return ChildIterator{ .i = 0, .parent = n }; } pub const ChildIterator = struct { i: u9, parent: *Node, pub fn next(self: *ChildIterator) ?*Node { return switch (self.parent.*) { .node4 => self.yieldNext(self.parent.node4, 4, bodyGeneral), .node16 => self.yieldNext(self.parent.node16, 16, bodyGeneral), .node48 => self.yieldNext(self.parent.node48, 256, body48), .node256 => self.yieldNext(self.parent.node256, 256, bodyGeneral), .leaf => unreachable, }; } fn yieldNext(self: *ChildIterator, node: anytype, max: u9, loopBody: fn (self: *ChildIterator, parent: anytype) bool) ?*Node { if (self.i == max) return null; defer self.i += 1; while (true) : (self.i += 1) { if (loopBody(self, node)) |n| return n; if (self.i == max - 1) break; } return null; } fn bodyGeneral(_self: *ChildIterator, parent: anytype) ?*Node { if (parent.children[_self.i] != null) return parent.children[_self.i]; return null; } fn body48(_self: *ChildIterator, parent: anytype) ?*Node { const idx = parent.keys[_self.i]; if (idx != 0 and parent.children[idx - 1] != null) return parent.children[idx - 1]; return null; } }; }; pub fn init(a: *const std.mem.Allocator) Tree { return .{ .root = null, .size = 0, .allocator = a }; } pub fn deinit(t: *Tree) void { t.deinitNode(t.root); } pub const Result = union(enum) { missing, found: Leaf }; pub fn insert(t: *Tree, key: [:0]const u8, value: T) !Result { var _key = key; _key.len += 1; const result = try t.recursiveInsert(t.root, &t.root, _key, value, 0); if (result == .missing) t.size += 1; return result; } pub fn print(t: *Tree) !void { const stderr = std.io.getStdErr().writer(); _ = try t.iter(showCb, stderr, Error!bool); } pub fn printToStream(t: *Tree, stream: anytype) !void { _ = try t.iter(showCb, stream, Error!bool); } pub fn displayNode(stream: anytype, n: ?*Node, depth: usize) void { _ = showCb(n, stream, depth); } pub fn displayChildren(stream: anytype, _n: ?*Node, depth: usize) void { const n = _n orelse return; var it = n.childIterator(); while (it.next()) |child| { displayNode(stream, child, depth + 1); } } pub fn delete(t: *Tree, key: [:0]const u8) Error!Result { var _key = key; _key.len += 1; const result = try t.recursiveDelete(t.root, &t.root, _key, 0); if (result == .found) t.size -= 1; return result; } pub fn search(t: *Tree, key: [:0]const u8) Result { var _key = key; _key.len += 1; var child: ?**Node = null; var _n: ?*Node = t.root; var prefix_len: usize = undefined; var depth: u32 = 0; while (_n) |n| { // Might be a leaf if (n.* == .leaf) { // Check if the expanded path matches if (std.mem.eql(u8, n.leaf.key, _key)) { return Result{ .found = n.leaf }; } return .missing; } const base = n.baseNode(); // Bail if the prefix does not match if (base.partial_len > 0) { prefix_len = checkPrefix(base, _key, depth); if (prefix_len != math.min(max_prefix_len, base.partial_len)) return .missing; depth += base.partial_len; } // Recursively search child = findChild(n, _key[depth]); _n = if (child) |c| c.* else null; depth += 1; } return .missing; } pub fn iter(t: *Tree, comptime cb: anytype, data: anytype, comptime CbRet: type) CbRet { return t.recursiveIter(t.root, data, 0, cb, CbRet); } pub fn iterAll(t: *Tree, comptime cb: anytype, data: anytype, comptime CbRet: type) CbRet { return t.recursiveIterAll(t.root, data, 0, cb, CbRet); } fn leafPrefixMatches(n: Leaf, prefix: []const u8) bool { return n.key.len > prefix.len and std.mem.startsWith(u8, n.key, prefix); } pub fn iterPrefix(t: *Tree, prefix: []const u8, cb: anytype, data: anytype, comptime CbRet: type) CbRet { std.debug.assert(prefix.len == 0 or prefix[prefix.len - 1] != 0); var child: ?**Node = undefined; var _n: ?*Node = t.root; var prefix_len: usize = undefined; var depth: u32 = 0; while (_n) |n| { // Might be a leaf if (n.* == .leaf) { // Check if the expanded path matches if (leafPrefixMatches(n.leaf, prefix)) return cb(n, data, depth); return false; } // If the depth matches the prefix, we need to handle this node if (depth == prefix.len) { if (minimum(n)) |l| { if (leafPrefixMatches(l.*, prefix)) return t.recursiveIter(n, data, depth, cb, CbRet); } return false; } const base = n.baseNode(); // Bail if the prefix does not match if (base.partial_len > 0) { prefix_len = prefixMismatch(n, prefix, depth); // Guard if the mis-match is longer than the MAX_PREFIX_LEN if (prefix_len > base.partial_len) prefix_len = base.partial_len; // If there is no match, search is terminated if (prefix_len == 0) { return false; // If we've matched the prefix, iterate on this node } else if (depth + prefix_len == prefix.len) { return t.recursiveIter(n, data, depth, cb, CbRet); } // if there is a full match, go deeper depth = depth + base.partial_len; } // Recursively search child = findChild(n, prefix[depth]); _n = if (child) |c| c.* else null; depth += 1; } return false; } // Recursively destroys the tree fn deinitNode(t: *Tree, _n: ?*Node) void { const n = _n orelse return; switch (n.*) { .leaf => {}, .node4, .node16, .node48, .node256 => { var it = n.childIterator(); while (it.next()) |child| { t.deinitNode(child); } }, } t.deinitNodeBytes(n); } fn deinitNodeBytes(t: *Tree, n: *Node) void { // destroy Node + [num_keys]u8 + [num_children]*Node const bytes_ptr = @ptrCast([*]u8, n); const bytes = bytes_ptr[0 .. @sizeOf(Node) + switch (n.*) { .node4 => Node4.num_keys + Node4.num_children * @sizeOf(*Node), .node16 => Node16.num_keys + Node16.num_children * @sizeOf(*Node), .node48 => Node48.num_keys + Node48.num_children * @sizeOf(*Node), .node256 => Node256.num_keys + Node256.num_children * @sizeOf(*Node), .leaf => { t.allocator.destroy(n); return; }, }]; t.allocator.free(bytes); } // don't allocate for the key. the client owns the keys fn makeLeaf(t: *Tree, key: []const u8, value: T) !*Node { const n = try t.allocator.create(Node); n.* = .{ .leaf = .{ .key = key, .value = value } }; return n; } fn allocNode(t: *Tree, comptime tag: NodeType) !*Node { const NodeT = switch (tag) { .node4 => Node4, .node16 => Node16, .node48 => Node48, .node256 => Node256, else => unreachable, }; // allocate enough space for a Node + [num_keys]u8 + [num_children]*Node var bytes = try t.allocator.alignedAlloc(u8, @alignOf(*Node), @sizeOf(Node) + 1 * NodeT.num_keys + @sizeOf(*Node) * NodeT.num_children); const n = mem.bytesAsValue(Node, bytes[0..@sizeOf(Node)]); bytes = bytes[@sizeOf(Node)..]; const KeysT = [NodeT.num_keys]u8; const keys_ptr = @ptrCast(*KeysT, bytes[0..NodeT.num_keys]); bytes = bytes[NodeT.num_keys..]; const ChildrenT = [NodeT.num_children]?*Node; const children_ptr_size = @sizeOf(*ChildrenT) * NodeT.num_children; const children_ptr = @ptrCast(*ChildrenT, mem.bytesAsSlice(ChildrenT, bytes[0..children_ptr_size]).ptr); const tag_name = @tagName(tag); n.* = @unionInit(Node, tag_name, .{ .num_children = 0, .partial_len = 0, .keys = keys_ptr, .children = children_ptr, }); var node = &@field(n, tag_name); node.keys.* = [1]u8{0} ** NodeT.num_keys; node.children.* = [1]?*Node{null} ** NodeT.num_children; return n; } fn recursiveInsert(t: *Tree, _n: ?*Node, ref: *?*Node, key: []const u8, value: T, depth: u32) Error!Result { const n = _n orelse { ref.* = try t.makeLeaf(key, value); return .missing; }; if (n.* == .leaf) { var l = n.leaf; if (mem.eql(u8, l.key, key)) { const result = Result{ .found = l }; n.leaf.value = value; return result; } var new_node = try t.allocNode(.node4); var l2 = try t.makeLeaf(key, value); const longest_prefix = longestCommonPrefix(l, l2.*.leaf, depth); new_node.node4.partial_len = longest_prefix; mem.copy(u8, &new_node.node4.partial, key[depth..][0..math.min(max_prefix_len, longest_prefix)]); ref.* = new_node; try t.addChild4(new_node, ref, l.key[depth + longest_prefix], n); try t.addChild4(new_node, ref, l2.*.leaf.key[depth + longest_prefix], l2); return .missing; } var base = n.baseNode(); if (base.partial_len != 0) { // Determine if the prefixes differ, since we need to split const prefix_diff = prefixMismatch(n, key, depth); if (prefix_diff >= base.partial_len) return try t.recursiveInsertSearch(n, ref, key, value, depth + base.partial_len); // Create a new node var new_node = try t.allocNode(.node4); ref.* = new_node; new_node.node4.partial_len = prefix_diff; mem.copy(u8, &new_node.node4.partial, base.partial[0..math.min(max_prefix_len, prefix_diff)]); // Adjust the prefix of the old node if (base.partial_len <= max_prefix_len) { try t.addChild4(new_node, ref, base.partial[prefix_diff], n); base.partial_len -= (prefix_diff + 1); mem.copy(u8, &base.partial, base.partial[prefix_diff + 1 ..][0..math.min(max_prefix_len, base.partial_len)]); } else { base.partial_len -= (prefix_diff + 1); var l = minimum(n) orelse return error.NoMinimum; try t.addChild4(new_node, ref, l.key[depth + prefix_diff], n); mem.copy(u8, &base.partial, l.key[depth + prefix_diff + 1 ..][0..math.min(max_prefix_len, base.partial_len)]); } // Insert the new leaf var l = try t.makeLeaf(key, value); try t.addChild4(new_node, ref, key[depth + prefix_diff], l); return .missing; } return try t.recursiveInsertSearch(n, ref, key, value, depth); } fn recursiveInsertSearch(t: *Tree, _n: ?*Node, ref: *?*Node, key: []const u8, value: T, depth: u32) Error!Result { const child = findChild(_n, key[depth]); if (child != null) { return try t.recursiveInsert(child.?.*, @ptrCast(*?*Node, child.?), key, value, depth + 1); } // No child, node goes within us var l = try t.makeLeaf(key, value); const n = _n orelse return error.Missing; try t.addChild(n, ref, key[depth], l); return .missing; } fn longestCommonPrefix(l: Leaf, l2: Leaf, depth: usize) u8 { const max_cmp = math.min(l.key.len, l2.key.len) - depth; var idx: u8 = 0; while (idx < max_cmp) : (idx += 1) { if (l.key[depth + idx] != l2.key[depth + idx]) return idx; } return idx; } fn copyHeader(dest: *BaseNode, src: *BaseNode) void { dest.num_children = src.num_children; dest.partial_len = src.partial_len; mem.copy(u8, &dest.partial, src.partial[0..math.min(max_prefix_len, src.partial_len)]); } /// Calculates the index at which the prefixes mismatch fn prefixMismatch(n: *Node, key: []const u8, depth: u32) u8 { const base = n.baseNode(); var max_cmp: u32 = math.min(math.min(max_prefix_len, base.partial_len), key.len - depth); var idx: u8 = 0; while (idx < max_cmp) : (idx += 1) { if (base.partial[idx] != key[depth + idx]) return idx; } if (base.partial_len > max_prefix_len) { const l = minimum(n); max_cmp = @truncate(u32, math.min(l.?.key.len, key.len)) - depth; while (idx < max_cmp) : (idx += 1) { if (l.?.key[idx + depth] != key[depth + idx]) return idx; } } return idx; } // Find the minimum Leaf under a node pub fn minimum(_n: ?*Node) ?*Leaf { const n = _n orelse return null; return switch (n.*) { .leaf => &n.leaf, .node4 => minimum(n.node4.children[0]), .node16 => minimum(n.node16.children[0]), .node48 => blk: { var idx: usize = 0; while (n.node48.keys[idx] == 0) : (idx += 1) {} break :blk minimum(n.node48.children[n.node48.keys[idx] - 1]); }, .node256 => blk: { var idx: u8 = 0; while (idx < 255 and n.node256.children[idx] == null) : (idx += 1) {} break :blk minimum(n.node256.children[idx]); }, }; } pub fn maximum(_n: ?*Node) ?*Leaf { const n = _n orelse return null; // Handle base cases return switch (n.*) { .leaf => &n.leaf, .node4 => maximum(n.node4.children[n.node4.num_children - 1]), .node16 => maximum(n.node16.children[n.node16.num_children - 1]), .node48 => blk: { var idx: u8 = 255; while (n.node48.keys[idx] == 0) idx -= 1; break :blk maximum(n.node48.children[n.node48.keys[idx] - 1]); }, .node256 => blk: { var idx: u8 = 255; while (idx > 0 and n.node256.children[idx] == null) idx -= 1; break :blk maximum(n.node256.children[idx]); }, }; } fn findChild(_n: ?*Node, c: u8) ?**Node { const n = _n orelse return null; const base = n.baseNode(); switch (n.*) { .node4 => { var i: u8 = 0; while (i < base.num_children) : (i += 1) { if (n.node4.keys[i] == c) return &n.node4.children[i].?; } }, .node16 => { var cmp = @splat(16, c) == @as(@Vector(16, u8), n.node16.keys.*); const mask = (@as(u17, 1) << @truncate(u5, n.node16.num_children)) - 1; const bitfield = @ptrCast(*u17, &cmp).* & mask; if (bitfield != 0) return &n.node16.children[@ctz(usize, bitfield)].?; }, .node48 => { const i = n.node48.keys[c]; if (i != 0) return &n.node48.children[i - 1].?; }, .node256 => { // seems like it shouldn't be, but this check is necessary // removing it makes many things fail spectularly and mysteriously // i thought removing this check would be ok as all children are initialized to null // but that is NOT the case... // the reason its necessary is that the address of the child is _NOT_ null. of course it isnt. if (n.node256.children[c]) |*child| return child; }, .leaf => unreachable, } return null; } fn addChild(t: *Tree, n: *Node, ref: *?*Node, c: u8, child: *Node) Error!void { switch (n.*) { .node4 => try t.addChild4(n, ref, c, child), .node16 => try t.addChild16(n, ref, c, child), .node48 => try t.addChild48(n, ref, c, child), .node256 => try t.addChild256(n, ref, c, child), .leaf => unreachable, } } fn addChild4(t: *Tree, n: *Node, ref: *?*Node, c: u8, child: *Node) !void { if (n.node4.num_children < 4) { var idx: usize = 0; while (idx < n.node4.num_children) : (idx += 1) { if (c < n.node4.keys[idx]) break; } const shift_len = n.node4.num_children - idx; mem.copyBackwards(u8, n.node4.keys[idx + 1 ..], n.node4.keys[idx..][0..shift_len]); mem.copyBackwards(?*Node, n.node4.children[idx + 1 ..], n.node4.children[idx..][0..shift_len]); n.node4.keys[idx] = c; n.node4.children[idx] = child; n.node4.num_children += 1; } else { var new_node = try t.allocNode(.node16); mem.copy(?*Node, new_node.node16.children, n.node4.children); mem.copy(u8, new_node.node16.keys, n.node4.keys); copyHeader(new_node.node16.baseNode(), n.node4.baseNode()); ref.* = new_node; t.deinitNodeBytes(n); try t.addChild16(new_node, ref, c, child); } } fn addChild16(t: *Tree, n: *Node, ref: *?*Node, c: u8, child: anytype) Error!void { if (n.node16.num_children < 16) { var cmp = @splat(16, c) < @as(@Vector(16, u8), n.node16.keys.*); const mask = (@as(u17, 1) << @truncate(u5, n.node16.num_children)) - 1; const bitfield = @ptrCast(*u17, &cmp).* & mask; var idx: usize = 0; if (bitfield != 0) { idx = @ctz(usize, bitfield); const shift_len = n.node16.num_children - idx; mem.copyBackwards(u8, n.node16.keys[idx + 1 ..], n.node16.keys[idx..][0..shift_len]); mem.copyBackwards(?*Node, n.node16.children[idx + 1 ..], n.node16.children[idx..][0..shift_len]); } else idx = n.node16.num_children; n.node16.keys[idx] = c; n.node16.children[idx] = child; n.node16.num_children += 1; } else { var new_node = try t.allocNode(.node48); mem.copy(?*Node, new_node.node48.children, n.node16.children); const base = n.baseNode(); var i: u8 = 0; while (i < base.num_children) : (i += 1) new_node.node48.keys[n.node16.keys[i]] = i + 1; copyHeader(new_node.baseNode(), base); ref.* = new_node; t.deinitNodeBytes(n); try t.addChild48(new_node, ref, c, child); } } fn addChild48(t: *Tree, _n: ?*Node, ref: *?*Node, c: u8, child: anytype) Error!void { const n = _n orelse return error.Missing; if (n.node48.num_children < 48) { var pos: u8 = 0; while (n.node48.children[pos] != null) : (pos += 1) {} n.node48.children[pos] = child; n.node48.keys[c] = pos + 1; n.node48.num_children += 1; } else { var new_node = try t.allocNode(.node256); var i: usize = 0; const old_children = n.node48.children; const old_keys = n.node48.keys; while (i < 256) : (i += 1) { if (old_keys[i] != 0) new_node.node256.children[i] = old_children[old_keys[i] - 1]; } copyHeader(new_node.baseNode(), n.baseNode()); ref.* = new_node; t.deinitNodeBytes(n); try t.addChild256(new_node, ref, c, child); } } fn addChild256(t: *Tree, _n: ?*Node, _: *?*Node, c: u8, child: anytype) Error!void { _ = child; _ = t; const n = _n orelse return error.Missing; n.node256.children[c] = child; // prevent overflow with saturating addition n.node256.num_children = n.node256.num_children +| 1; } fn checkPrefix(n: *BaseNode, key: []const u8, depth: usize) usize { // FIXME should this be key.len - 1? const max_cmp = math.min(math.min(n.partial_len, max_prefix_len), key.len - depth); var idx: usize = 0; while (idx < max_cmp) : (idx += 1) { if (n.partial[idx] != key[depth + idx]) return idx; } return idx; } /// calls cb in order on leaf nodes until cb returns true fn recursiveIter(t: *Tree, _n: ?*Node, data: anytype, depth: usize, cb: anytype, comptime CbRet: type) CbRet { const n = _n orelse return error.Missing; switch (n.*) { .leaf => return cb(n, data, depth), .node4, .node16, .node48, .node256 => { var ci = n.childIterator(); while (ci.next()) |child| { if (try t.recursiveIter(child, data, depth + 1, cb, CbRet)) return true; } }, } return false; } /// calls cb in order on all nodes (not just leaves) until cb returns true fn recursiveIterAll(t: *Tree, n: ?*Node, data: anytype, depth: usize, cb: anytype, comptime CbRet: type) CbRet { switch (n.*) { .empty => {}, .leaf => return cb(n, data, depth), .node4, .node16, .node48, .node256 => { if (cb(n, data, depth)) return true; var ci = n.childIterator(); while (ci.next()) |child| { if (t.recursiveIterAll(child, data, depth + 1, cb, CbRet)) return true; } }, } return false; } const spaces = [1]u8{' '} ** 256; pub fn showCb(_n: ?*Node, data: anytype, depth: usize) bool { const streamPrint = struct { fn _(stream: anytype, comptime fmt: []const u8, args: anytype) void { _ = stream.print(fmt, args) catch unreachable; } }._; const n = _n orelse { streamPrint(data, "empty\n", .{}); return false; }; switch (n.*) { .leaf => streamPrint(data, "{s}-> {s} = {}\n", .{ spaces[0 .. depth * 2], n.leaf.key, n.leaf.value }), .node4 => streamPrint(data, "{s}4 [{s}] ({s}) {} children\n", .{ spaces[0 .. depth * 2], &n.node4.keys.*, n.node4.partial[0..math.min(max_prefix_len, n.node4.partial_len)], n.node4.num_children, }), .node16 => streamPrint(data, "{s}16 [{s}] ({s}) {} children\n", .{ spaces[0 .. depth * 2], n.node16.keys.*, n.node16.partial[0..math.min(max_prefix_len, n.node16.partial_len)], n.node16.num_children, }), .node48 => |nn| { streamPrint(data, "{s}48 [", .{spaces[0 .. depth * 2]}); for (nn.keys) |c, i| { if (c != 0) streamPrint(data, "{c}", .{@truncate(u8, i)}); } streamPrint(data, "] ({s}) {} children\n", .{ nn.partial, n.node48.num_children }); }, .node256 => |nn| { streamPrint(data, "{s}256 [", .{spaces[0 .. depth * 2]}); for (nn.children) |child, i| { if (child != null) streamPrint(data, "{c}", .{@truncate(u8, i)}); } streamPrint(data, "] ({s}) {} children\n", .{ nn.partial, n.node256.num_children }); }, } return false; } fn recursiveDelete(t: *Tree, _n: ?*Node, ref: *?*Node, key: []const u8, _depth: usize) Error!Result { var depth = _depth; const n = _n orelse return .missing; if (n.* == .leaf) { const l = n.leaf; if (mem.eql(u8, n.leaf.key, key)) { const result = Result{ .found = l }; t.deinitNode(n); ref.* = null; return result; } return .missing; } const base = n.baseNode(); if (base.partial_len > 0) { const prefix_len = checkPrefix(base, key, depth); if (prefix_len != math.min(max_prefix_len, base.partial_len)) return .missing; depth += base.partial_len; } const opt_child = findChild(n, key[depth]); var child = (opt_child orelse return .missing).*; if (child.* == .leaf) { const l = child.*.leaf; if (mem.eql(u8, l.key, key)) { try t.removeChild(n, ref, key[depth], opt_child); return Result{ .found = l }; } return .missing; } else return try t.recursiveDelete(child, @ptrCast(*?*Node, opt_child.?), key, depth + 1); } fn removeChild(t: *Tree, _n: ?*Node, ref: *?*Node, c: u8, l: ?**Node) !void { const n = _n orelse return error.Missing; switch (n.*) { .node4 => return t.removeChild4(n, ref, l), .node16 => return try t.removeChild16(n, ref, l), .node48 => return try t.removeChild48(n, ref, c), .node256 => return try t.removeChild256(n, ref, c), .leaf => unreachable, } } fn removeChild4(t: *Tree, _n: ?*Node, ref: *?*Node, l: ?**Node) Error!void { const n = _n orelse return error.Missing; const pos = (@ptrToInt(l) - @ptrToInt(&n.node4.children.*)) / 8; if (!(0 <= pos and pos < 4)) std.log.err("bad pos found {}\n", .{pos}); std.debug.assert(0 <= pos and pos < 4); t.deinitNode(n.node4.children[pos]); const base = n.baseNode(); mem.copy(u8, n.node4.keys[pos..], n.node4.keys[pos + 1 ..]); mem.copy(?*Node, n.node4.children[pos..], n.node4.children[pos + 1 ..]); base.num_children -= 1; n.node4.keys[base.num_children] = 0; n.node4.children[base.num_children] = null; // Remove nodes with only a single child if (base.num_children == 1) { const child = n.node4.children[0] orelse return error.Missing; if (child.* != .leaf) { // Concatenate the prefixes var prefix = base.partial_len; if (prefix < max_prefix_len) { base.partial[prefix] = n.node4.keys[0]; prefix += 1; } const child_base = child.baseNode(); if (prefix < max_prefix_len) { const sub_prefix = math.min(child_base.partial_len, max_prefix_len - prefix); mem.copy(u8, base.partial[prefix..], child_base.partial[0..sub_prefix]); prefix += sub_prefix; } mem.copy(u8, &child_base.partial, base.partial[0..math.min(prefix, max_prefix_len)]); child_base.partial_len += base.partial_len + 1; } ref.* = child; t.deinitNodeBytes(n); } } fn removeChild16(t: *Tree, _n: ?*Node, ref: *?*Node, l: ?**Node) Error!void { const n = _n orelse return error.Missing; const pos = (@ptrToInt(l) - @ptrToInt(&n.node16.children.*)) / 8; std.debug.assert(0 <= pos and pos < 16); t.deinitNode(n.node16.children[pos]); const base = n.baseNode(); mem.copy(u8, n.node16.keys[pos..], n.node16.keys[pos + 1 ..]); mem.copy(?*Node, n.node16.children[pos..], n.node16.children[pos + 1 ..]); base.num_children -= 1; n.node16.keys[base.num_children] = 0; n.node16.children[base.num_children] = null; if (base.num_children == 3) { const new_node = try t.allocNode(.node4); ref.* = new_node; copyHeader(new_node.baseNode(), base); mem.copy(u8, new_node.node4.keys, n.node16.keys[0..3]); mem.copy(?*Node, new_node.node4.children, n.node16.children[0..3]); t.deinitNodeBytes(n); } } fn removeChild48(t: *Tree, _n: ?*Node, ref: *?*Node, c: u8) Error!void { const n = _n orelse return error.Missing; const base = n.baseNode(); var pos = n.node48.keys[c]; n.node48.keys[c] = 0; t.deinitNode(n.node48.children[pos - 1]); n.node48.children[pos - 1] = null; base.num_children -= 1; if (base.num_children == 12) { const new_node = try t.allocNode(.node16); ref.* = new_node; copyHeader(new_node.baseNode(), base); var childi: u8 = 0; var i: u8 = 0; while (true) : (i += 1) { pos = n.node48.keys[i]; if (pos != 0) { new_node.node16.keys[childi] = i; new_node.node16.children[childi] = n.node48.children[pos - 1]; childi += 1; } if (i == 255) break; } t.deinitNodeBytes(n); } } fn removeChild256(t: *Tree, _n: ?*Node, ref: *?*Node, c: u8) Error!void { const n = _n orelse return error.Missing; const base = n.baseNode(); t.deinitNode(n.node256.children[c]); n.node256.children[c] = null; // Resize to a node48 on underflow, not immediately to prevent // trashing if we sit on the 48/49 boundary if (base.num_children == 37) { const new_node = try t.allocNode(.node48); ref.* = new_node; copyHeader(new_node.baseNode(), base); var pos: u8 = 0; var i: u8 = 0; while (true) : (i += 1) { if (n.node256.children[i] != null) { new_node.node48.children[pos] = n.node256.children[i]; new_node.node48.keys[i] = pos + 1; pos += 1; } if (i == 255) break; } t.deinitNodeBytes(n); } } }; } const warn = std.log.warn; fn replUsage(input: []const u8) void { const usage = \\ usage - command <command> \\ insert <key ?value> \\ delete <d:key> \\ --commands-- \\ :q - quit \\ :r - reset (deinit/init) the tree \\ :h - show usage \\ --insert-- \\ key - insert 'key' with value = t.size \\ key number - inserts key with value = parse(number) \\ --delete-- \\ d:key - deletes key \\ ; if (input.len > 0) { warn("invalid input: '{s}'\n", .{input}); } warn(usage, .{}); } pub fn main() !void { var t = Art(usize).init(&std.heap.c_allocator); const stdin = std.io.getStdIn().reader(); var buf: [256]u8 = undefined; replUsage(""); warn("> ", .{}); while (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |input| { var parts: [2][]const u8 = undefined; if (std.mem.eql(u8, input, ":q")) { break; } else if (std.mem.eql(u8, input, ":r")) { t.deinit(); t = Art(usize).init(&std.heap.c_allocator); continue; } var itr = std.mem.split(u8, input, " "); var i: u8 = 0; var delete = false; while (itr.next()) |part| : (i += 1) { if (i == 0 and part.len > 1 and std.mem.eql(u8, "d:", part[0..2])) { delete = true; parts[i] = part[2..]; } else parts[i] = part; } var res: ?Art(usize).Result = null; var buf2: [256]u8 = undefined; var key = try std.fmt.bufPrintZ(&buf2, "{s}", .{parts[0]}); if (delete) { res = try t.delete(key); } else { if (i == 1) { res = try t.insert(key, t.size); } else if (i == 2) { const n = try std.fmt.parseInt(usize, parts[1], 10); res = try t.insert(key, n); } else replUsage(input); } if (res) |result| { var ouput: []const u8 = if (result == .missing) "insert:"[0..] else "update:"[0..]; warn("{s} size {}\n", .{ ouput, t.size }); try t.print(); } warn("> ", .{}); } }
src/art.zig
usingnamespace @import("root").preamble; pub const IA32_EFER = MSR(u64, 0xC0000080); pub const IA32_STAR = MSR(u64, 0xC0000081); pub const IA32_LSTAR = MSR(u64, 0xC0000082); pub const IA32_FMASK = MSR(u64, 0xC0000084); pub const IA32_FS_BASE = MSR(u64, 0xC0000100); pub const IA32_GS_BASE = MSR(u64, 0xC0000101); fn read_msr(comptime T: type, msr_num: u32) T { switch (T) { u64 => { var low: u32 = undefined; var high: u32 = undefined; asm volatile ("rdmsr" : [_] "={eax}" (low), [_] "={edx}" (high) : [_] "{ecx}" (msr_num) ); return (@as(u64, high) << 32) | @as(u64, low); }, u32 => { return asm volatile ("rdmsr" : [_] "={eax}" (-> u32) : [_] "{ecx}" (msr_num) ); }, else => @compileError("read_msr not implemented for type"), } } fn write_msr(comptime T: type, msr_num: u32, val: T) void { switch (T) { u64 => { const low = @truncate(u32, val); const high = @truncate(u32, val >> 32); asm volatile ("wrmsr" : : [_] "{eax}" (low), [_] "{edx}" (high), [_] "{ecx}" (msr_num) ); }, u32 => { asm volatile ("wrmsr" : : [_] "{eax}" (val), [_] "{edx}" (@as(u32, 0)), [_] "{ecx}" (msr_num) ); }, else => @compileError("write_msr not implemented for type"), } } pub fn MSR(comptime T: type, comptime msr_num: u32) type { return struct { pub fn read() T { return read_msr(T, msr_num); } pub fn write(val: T) void { write_msr(T, msr_num, val); } }; } pub fn ControlRegister(comptime T: type, comptime name: []const u8) type { return struct { pub fn read() T { return asm volatile ("mov %%" ++ name ++ ", %[out]" : [out] "=r" (-> T) ); } pub fn write(val: T) void { asm volatile ("mov %[in], %%" ++ name : : [in] "r" (val) ); } }; } pub fn eflags() u64 { return asm volatile ( \\pushfq \\pop %[flags] : [flags] "=r" (-> u64) ); } pub fn fill_cpuid(res: anytype, leaf: u32) bool { if (leaf & 0x7FFFFFFF != 0) { if (!check_has_cpuid_leaf(leaf)) return false; } var eax: u32 = undefined; var ebx: u32 = undefined; var edx: u32 = undefined; var ecx: u32 = undefined; asm volatile ( \\cpuid : [eax] "={eax}" (eax), [ebx] "={ebx}" (ebx), [edx] "={edx}" (edx), [ecx] "={ecx}" (ecx) : [leaf] "{eax}" (leaf) ); res.eax = eax; res.ebx = ebx; res.edx = edx; res.ecx = ecx; return true; } pub fn check_has_cpuid_leaf(leaf: u32) bool { const max_func = cpuid(leaf & 0x80000000).?.eax; return leaf <= max_func; } const default_cpuid = struct { eax: u32, ebx: u32, edx: u32, ecx: u32, }; pub fn cpuid(leaf: u32) ?default_cpuid { var result: default_cpuid = undefined; if (fill_cpuid(&result, leaf)) return result; return null; }
subprojects/flork/src/platform/x86_64/regs.zig
const std = @import("std"); const testing = std.testing; const RelevantFields = &[_][]const u8{ "install", "source", "pkgver()", "check()", "package()", "install()", }; const Content = struct { const Self = @This(); value: []const u8, updated: bool = false, // allocator.create does not respect default values so safeguard via an init() call pub fn init(allocator: std.mem.Allocator, value: []const u8) !*Self { var new = try allocator.create(Self); new.value = value; new.updated = false; return new; } pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { allocator.free(self.value); allocator.destroy(self); } }; pub const Pkgbuild = struct { const Self = @This(); allocator: std.mem.Allocator, file_contents: []const u8, fields: std.StringHashMap(*Content), pub fn init(allocator: std.mem.Allocator, file_contents: []const u8) Self { return Self{ .allocator = allocator, .file_contents = file_contents, .fields = std.StringHashMap(*Content).init(allocator), }; } pub fn deinit(self: *Self) void { defer self.fields.deinit(); var iter = self.fields.iterator(); while (iter.next()) |entry| { self.allocator.free(entry.key_ptr.*); entry.value_ptr.*.deinit(self.allocator); } } pub fn readLines(self: *Self) !void { var stream = std.io.fixedBufferStream(self.file_contents).reader(); var buf = std.ArrayList(u8).init(self.allocator); defer buf.deinit(); while (true) { const byte = stream.readByte() catch |err| switch (err) { error.EndOfStream => break, }; switch (byte) { // PKGBUILD comments '#' => { while (true) { // footer comments cause this to return EndOfStream error const lookahead = stream.readByte() catch |err| switch (err) { error.EndOfStream => break, }; if (lookahead == '\n') break; } }, // PKGBUILD key=value '=' => { var key = buf.toOwnedSlice(); var in_quotes = false; while (true) { const lookahead = try stream.readByte(); if (lookahead == '(') { while (true) { const moreahead = try stream.readByte(); // This naive parsing goofs when there are parens in quotes if (moreahead == '\'') in_quotes = !in_quotes; if (moreahead == ')' and !in_quotes) break; if (moreahead != ' ' and moreahead != '\t') { try buf.append(moreahead); } } } else if (lookahead == '\n') { var content = try Content.init(self.allocator, buf.toOwnedSlice()); // Content.deinit() happens in Pkgbuild.deinit() try self.fields.putNoClobber(key, content); break; } else { try buf.append(lookahead); } } }, // PKGBUILD functions() {} // TODO: looks like PKGBUILDS shared across multiple packages can do something like package_PKGNAME() '(' => { // functions get a () in their keys because // 'pkgver' can both be a function and a key=value try buf.appendSlice("()"); var key = buf.toOwnedSlice(); const close_paren = try stream.readByte(); if (close_paren != ')') { return error.MalformedPkgbuildFunction; } const maybe_space = try stream.readByte(); if (maybe_space != ' ') { try buf.append(maybe_space); } var prev: u8 = undefined; while (true) { const lookahead = try stream.readByte(); try buf.append(lookahead); // TODO: Is it a valid assumption that the function closing paren is always on a new line? if (lookahead == '}' and prev == '\n') { var content = try Content.init(self.allocator, buf.toOwnedSlice()); // Content.deinit() happens in Pkgbuild.deinit() try self.fields.putNoClobber(key, content); break; } prev = lookahead; } }, '\n' => {}, else => { try buf.append(byte); }, } } } pub fn comparePrev(self: *Self, prev_pkgbuild: Pkgbuild) !void { for (RelevantFields) |field| { const prev = prev_pkgbuild.fields.get(field); const curr = self.fields.get(field); if (prev == null and curr != null) { curr.?.updated = true; } else if (prev != null and curr == null) { curr.?.value = "(removed)"; curr.?.updated = true; } else if (prev == null and curr == null) { continue; } else if (prev != null and curr != null and !std.mem.eql(u8, prev.?.value, curr.?.value)) { curr.?.updated = true; } } } pub fn indentValues(self: *Self, spaces_count: usize) !void { var buf = std.ArrayList(u8).init(self.allocator); var fields_iter = self.fields.iterator(); while (fields_iter.next()) |field| { if (!std.mem.containsAtLeast(u8, field.key_ptr.*, 1, "()")) { continue; } var lines_iter = std.mem.split(u8, field.value_ptr.*.value, "\n"); while (lines_iter.next()) |line| { var count: usize = 0; while (count < spaces_count) { try buf.append(' '); count += 1; } try buf.appendSlice(line); try buf.append('\n'); } self.allocator.free(field.value_ptr.*.value); field.value_ptr.*.value = buf.toOwnedSlice(); } } }; test "Pkgbuild - readLines - neovim-git" { var file_contents = \\# Maintainer: <NAME> <florian+<EMAIL>> \\# Contributor: <NAME> <<EMAIL>> \\# Contributor: <NAME> <<EMAIL>> \\ \\pkgname=neovim-git \\pkgver=0.4.0.r2972.g3fbff98cf \\pkgrel=1 \\pkgdesc='Fork of Vim aiming to improve user experience, plugins, and GUIs.' \\arch=('i686' 'x86_64' 'armv7h' 'armv6h' 'aarch64') \\url='https://neovim.io' \\backup=('etc/xdg/nvim/sysinit.vim') \\license=('custom:neovim') \\depends=('libluv' 'libtermkey' 'libutf8proc' 'libuv' 'libvterm>=0.1.git5' 'luajit' 'msgpack-c' 'unibilium' 'tree-sitter') \\makedepends=('cmake' 'git' 'gperf' 'lua51-mpack' 'lua51-lpeg') \\optdepends=('python2-neovim: for Python 2 plugin support (see :help provider-python)' \\ 'python-neovim: for Python 3 plugin support (see :help provider-python)' \\ 'ruby-neovim: for Ruby plugin support (see :help provider-ruby)' \\ 'xclip: for clipboard support (or xsel) (see :help provider-clipboard)' \\ 'xsel: for clipboard support (or xclip) (see :help provider-clipboard)' \\ 'wl-clipboard: for clipboard support on wayland (see :help clipboard)') \\source=("${pkgname}::git+https://github.com/neovim/neovim.git") \\sha256sums=('SKIP') \\provides=("neovim=${pkgver}" 'vim-plugin-runtime') \\conflicts=('neovim') \\install=neovim-git.install \\options=(!strip) \\ \\pkgver() { \\ cd "${pkgname}" \\ git describe --long | sed 's/^v//;s/\([^-]*-g\)/r\1/;s/-/./g' \\} \\ \\build() { \\ cmake -S"${pkgname}" -Bbuild \ \\ -DCMAKE_BUILD_TYPE=RelWithDebInfo \ \\ -DCMAKE_INSTALL_PREFIX=/usr \\ cmake --build build \\} \\ \\check() { \\ cd "${srcdir}/build" \\ ./bin/nvim --version \\ ./bin/nvim --headless -u NONE -i NONE -c ':quit' \\} \\ \\package() { \\ cd "${srcdir}/build" \\ DESTDIR="${pkgdir}" cmake --build . --target install \\ \\ cd "${srcdir}/${pkgname}" \\ install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE" \\ install -Dm644 runtime/nvim.desktop "${pkgdir}/usr/share/applications/nvim.desktop" \\ install -Dm644 runtime/nvim.png "${pkgdir}/usr/share/pixmaps/nvim.png" \\ \\ # Make Arch vim packages work \\ mkdir -p "${pkgdir}"/etc/xdg/nvim \\ echo "\" This line makes pacman-installed global Arch Linux vim packages work." > "${pkgdir}"/etc/xdg/nvim/sysinit.vim \\ echo "source /usr/share/nvim/archlinux.vim" >> "${pkgdir}"/etc/xdg/nvim/sysinit.vim \\ \\ mkdir -p "${pkgdir}"/usr/share/vim \\ echo "set runtimepath+=/usr/share/vim/vimfiles" > "${pkgdir}"/usr/share/nvim/archlinux.vim \\} \\ \\# vim:set sw=2 sts=2 et: ; var expectedMap = std.StringHashMap(*Content).init(testing.allocator); defer expectedMap.deinit(); var install_val = std.ArrayList(u8).init(testing.allocator); try install_val.appendSlice("neovim-git.install"); var install_content = try Content.init(testing.allocator, install_val.toOwnedSlice()); defer install_content.deinit(testing.allocator); try expectedMap.putNoClobber("install", install_content); var package_val = std.ArrayList(u8).init(testing.allocator); try package_val.appendSlice( \\{ \\ cd "${srcdir}/build" \\ DESTDIR="${pkgdir}" cmake --build . --target install \\ \\ cd "${srcdir}/${pkgname}" \\ install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE" \\ install -Dm644 runtime/nvim.desktop "${pkgdir}/usr/share/applications/nvim.desktop" \\ install -Dm644 runtime/nvim.png "${pkgdir}/usr/share/pixmaps/nvim.png" \\ \\ # Make Arch vim packages work \\ mkdir -p "${pkgdir}"/etc/xdg/nvim \\ echo "\" This line makes pacman-installed global Arch Linux vim packages work." > "${pkgdir}"/etc/xdg/nvim/sysinit.vim \\ echo "source /usr/share/nvim/archlinux.vim" >> "${pkgdir}"/etc/xdg/nvim/sysinit.vim \\ \\ mkdir -p "${pkgdir}"/usr/share/vim \\ echo "set runtimepath+=/usr/share/vim/vimfiles" > "${pkgdir}"/usr/share/nvim/archlinux.vim \\} ); var package_content = try Content.init(testing.allocator, package_val.toOwnedSlice()); defer package_content.deinit(testing.allocator); try expectedMap.putNoClobber("package()", package_content); var pkgbuild = Pkgbuild.init(testing.allocator, file_contents); defer pkgbuild.deinit(); try pkgbuild.readLines(); try testing.expectEqualStrings(expectedMap.get("install").?.value, pkgbuild.fields.get("install").?.value); try testing.expectEqualStrings(expectedMap.get("package()").?.value, pkgbuild.fields.get("package()").?.value); } test "Pkgbuild - readLines - google-chrome-dev" { var file_contents = \\# Maintainer: <NAME> <knut at ahlers dot me> \\# Contributor: Det <nimetonmaili g-mail> \\# Contributors: t3ddy, <NAME> aka x-demon, ruario \\ \\# Check for new Linux releases in: http://googlechromereleases.blogspot.com/search/label/Dev%20updates \\# or use: $ curl -s https://dl.google.com/linux/chrome/rpm/stable/x86_64/repodata/other.xml.gz | gzip -df | awk -F\" '/pkgid/{ sub(".*-","",$4); print $4": "$10 }' \\ \\pkgname=google-chrome-dev \\pkgver=91.0.4464.5 \\pkgrel=1 \\pkgdesc="The popular and trusted web browser by Google (Dev Channel)" \\arch=('x86_64') \\url="https://www.google.com/chrome" \\license=('custom:chrome') \\depends=('alsa-lib' 'gtk3' 'libcups' 'libxss' 'libxtst' 'nss') \\optdepends=( \\ 'libpipewire02: WebRTC desktop sharing under Wayland' \\ 'kdialog: for file dialogs in KDE' \\ 'gnome-keyring: for storing passwords in GNOME keyring' \\ 'kwallet: for storing passwords in KWallet' \\ 'libunity: for download progress on KDE' \\ 'ttf-liberation: fix fonts for some PDFs - CRBug #369991' \\ 'xdg-utils' \\) \\provides=('google-chrome') \\options=('!emptydirs' '!strip') \\install=$pkgname.install \\_channel=unstable \\source=("https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-${_channel}/google-chrome-${_channel}_${pkgver}-1_amd64.deb" \\ 'eula_text.html' \\ "google-chrome-$_channel.sh") \\sha512sums=('<KEY>' \\ '<KEY>' \\ '<KEY>') \\ \\package() { \\ msg2 "Extracting the data.tar.xz..." \\ bsdtar -xf data.tar.xz -C "$pkgdir/" \\ \\ msg2 "Moving stuff in place..." \\ # Launcher \\ install -m755 google-chrome-$_channel.sh "$pkgdir"/usr/bin/google-chrome-$_channel \\ \\ # Icons \\ for i in 16x16 24x24 32x32 48x48 64x64 128x128 256x256; do \\ install -Dm644 "$pkgdir"/opt/google/chrome-$_channel/product_logo_${i/x*/}_${pkgname/*-/}.png \ \\ "$pkgdir"/usr/share/icons/hicolor/$i/apps/google-chrome-$_channel.png \\ done \\ \\ # License \\ install -Dm644 eula_text.html "$pkgdir"/usr/share/licenses/google-chrome-$_channel/eula_text.html \\ \\ msg2 "Fixing Chrome icon resolution..." \\ sed -i \ \\ -e "/Exec=/i\StartupWMClass=Google-chrome-$_channel" \ \\ -e "s/x-scheme-handler\/ftp;\?//g" \ \\ "$pkgdir"/usr/share/applications/google-chrome-$_channel.desktop \\ \\ msg2 "Removing Debian Cron job and duplicate product logos..." \\ rm -r "$pkgdir"/etc/cron.daily/ "$pkgdir"/opt/google/chrome-$_channel/cron/ \\ rm "$pkgdir"/opt/google/chrome-$_channel/product_logo_*.png \\} ; var expectedMap = std.StringHashMap(*Content).init(testing.allocator); defer expectedMap.deinit(); var install_val = std.ArrayList(u8).init(testing.allocator); try install_val.appendSlice("$pkgname.install"); var install_content = try Content.init(testing.allocator, install_val.toOwnedSlice()); defer install_content.deinit(testing.allocator); try expectedMap.putNoClobber("install", install_content); var source_val = std.ArrayList(u8).init(testing.allocator); try source_val.appendSlice( \\"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-${_channel}/google-chrome-${_channel}_${pkgver}-1_amd64.deb" \\'eula_text.html' \\"google-chrome-$_channel.sh" ); var source_content = try Content.init(testing.allocator, source_val.toOwnedSlice()); defer source_content.deinit(testing.allocator); try expectedMap.putNoClobber("source", source_content); var package_val = std.ArrayList(u8).init(testing.allocator); try package_val.appendSlice( \\{ \\ msg2 "Extracting the data.tar.xz..." \\ bsdtar -xf data.tar.xz -C "$pkgdir/" \\ \\ msg2 "Moving stuff in place..." \\ # Launcher \\ install -m755 google-chrome-$_channel.sh "$pkgdir"/usr/bin/google-chrome-$_channel \\ \\ # Icons \\ for i in 16x16 24x24 32x32 48x48 64x64 128x128 256x256; do \\ install -Dm644 "$pkgdir"/opt/google/chrome-$_channel/product_logo_${i/x*/}_${pkgname/*-/}.png \ \\ "$pkgdir"/usr/share/icons/hicolor/$i/apps/google-chrome-$_channel.png \\ done \\ \\ # License \\ install -Dm644 eula_text.html "$pkgdir"/usr/share/licenses/google-chrome-$_channel/eula_text.html \\ \\ msg2 "Fixing Chrome icon resolution..." \\ sed -i \ \\ -e "/Exec=/i\StartupWMClass=Google-chrome-$_channel" \ \\ -e "s/x-scheme-handler\/ftp;\?//g" \ \\ "$pkgdir"/usr/share/applications/google-chrome-$_channel.desktop \\ \\ msg2 "Removing Debian Cron job and duplicate product logos..." \\ rm -r "$pkgdir"/etc/cron.daily/ "$pkgdir"/opt/google/chrome-$_channel/cron/ \\ rm "$pkgdir"/opt/google/chrome-$_channel/product_logo_*.png \\} ); var package_content = try Content.init(testing.allocator, package_val.toOwnedSlice()); defer package_content.deinit(testing.allocator); try expectedMap.putNoClobber("package()", package_content); var pkgbuild = Pkgbuild.init(testing.allocator, file_contents); defer pkgbuild.deinit(); try pkgbuild.readLines(); try testing.expectEqualStrings(expectedMap.get("install").?.value, pkgbuild.fields.get("install").?.value); try testing.expectEqualStrings(expectedMap.get("source").?.value, pkgbuild.fields.get("source").?.value); try testing.expectEqualStrings(expectedMap.get("package()").?.value, pkgbuild.fields.get("package()").?.value); } test "Pkgbuild - compare" { var old = \\pkgname=google-chrome-dev \\pkgver=91.0.4464.5 \\pkgrel=1 \\pkgdesc="The popular and trusted web browser by Google (Dev Channel)" \\arch=('x86_64') \\url="https://www.google.com/chrome" \\license=('custom:chrome') \\depends=('alsa-lib' 'gtk3' 'libcups' 'libxss' 'libxtst' 'nss') \\optdepends=('optdepends') \\provides=('google-chrome') \\options=('!emptydirs' '!strip') \\install=$pkgname.install \\_channel=unstable \\source=("source") \\sha512sums=('sha' 'sum' '512') \\pkgver() { \\ pkgver function \\} \\check() { \\ check function \\} \\package() { \\ package function \\} \\install() { \\ install function \\} ; var new = \\pkgname=google-chrome-dev \\pkgver=9001 \\pkgrel=1 \\pkgdesc="The popular and trusted web browser by Google (Dev Channel)" \\arch=('x86_64') \\url="https://www.google.com/chrome" \\license=('custom:chrome') \\depends=('alsa-lib' 'gtk3' 'libcups' 'libxss' 'libxtst' 'nss') \\optdepends=('optdepends') \\provides=('google-chrome') \\options=('!emptydirs' '!strip') \\install=malicious.install \\_channel=unstable \\source=("source") \\sha512sums=('sha' 'sum' '512') \\pkgver() { \\ pkgver function \\ aha! I changed to perform some nasty shell commands \\} \\check() { \\ check function \\} \\package() { \\ package function \\} \\install() { \\ install function \\} ; var pkgbuild_old = Pkgbuild.init(testing.allocator, old); defer pkgbuild_old.deinit(); try pkgbuild_old.readLines(); var pkgbuild_new = Pkgbuild.init(testing.allocator, new); defer pkgbuild_new.deinit(); try pkgbuild_new.readLines(); try pkgbuild_new.comparePrev(pkgbuild_old); try testing.expect(pkgbuild_new.fields.get("install").?.updated); try testing.expect(pkgbuild_new.fields.get("pkgver()").?.updated); } test "Pkgbuild - indentValue - google-chrome-dev" { var file_contents = \\# Maintainer: <NAME> <knut at ahlers dot me> \\# Contributor: Det <nimetonmaili g-mail> \\# Contributors: t3ddy, <NAME> aka x-demon, ruario \\ \\# Check for new Linux releases in: http://googlechromereleases.blogspot.com/search/label/Dev%20updates \\# or use: $ curl -s https://dl.google.com/linux/chrome/rpm/stable/x86_64/repodata/other.xml.gz | gzip -df | awk -F\" '/pkgid/{ sub(".*-","",$4); print $4": "$10 }' \\ \\pkgname=google-chrome-dev \\pkgver=91.0.4464.5 \\pkgrel=1 \\pkgdesc="The popular and trusted web browser by Google (Dev Channel)" \\arch=('x86_64') \\url="https://www.google.com/chrome" \\license=('custom:chrome') \\depends=('alsa-lib' 'gtk3' 'libcups' 'libxss' 'libxtst' 'nss') \\optdepends=( \\ 'libpipewire02: WebRTC desktop sharing under Wayland' \\ 'kdialog: for file dialogs in KDE' \\ 'gnome-keyring: for storing passwords in GNOME keyring' \\ 'kwallet: for storing passwords in KWallet' \\ 'libunity: for download progress on KDE' \\ 'ttf-liberation: fix fonts for some PDFs - CRBug #369991' \\ 'xdg-utils' \\) \\provides=('google-chrome') \\options=('!emptydirs' '!strip') \\install=$pkgname.install \\_channel=unstable \\source=("https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-${_channel}/google-chrome-${_channel}_${pkgver}-1_amd64.deb" \\ 'eula_text.html' \\ "google-chrome-$_channel.sh") \\sha512sums=('7ab84e51b0cd80c51e0092fe67af1e4e9dd886c6437d9d0fec1552e511c1924d2dac21c02153382cbb7c8c52ef82df97428fbb12139ebc048f1db6964ddc3b45' \\ 'a225555c06b7c32f9f2657004558e3f996c981481dbb0d3cd79b1d59fa3f05d591af88399422d3ab29d9446c103e98d567aeafe061d9550817ab6e7eb0498396' \\ '349fc419796bdea83ebcda2c33b262984ce4d37f2a0a13ef7e1c87a9f619fd05eb8ff1d41687f51b907b43b9a2c3b4a33b9b7c3a3b28c12cf9527ffdbd1ddf2e') \\ \\package() { \\ msg2 "Extracting the data.tar.xz..." \\ bsdtar -xf data.tar.xz -C "$pkgdir/" \\ \\ msg2 "Moving stuff in place..." \\ # Launcher \\ install -m755 google-chrome-$_channel.sh "$pkgdir"/usr/bin/google-chrome-$_channel \\ \\ # Icons \\ for i in 16x16 24x24 32x32 48x48 64x64 128x128 256x256; do \\ install -Dm644 "$pkgdir"/opt/google/chrome-$_channel/product_logo_${i/x*/}_${pkgname/*-/}.png \ \\ "$pkgdir"/usr/share/icons/hicolor/$i/apps/google-chrome-$_channel.png \\ done \\ \\ # License \\ install -Dm644 eula_text.html "$pkgdir"/usr/share/licenses/google-chrome-$_channel/eula_text.html \\ \\ msg2 "Fixing Chrome icon resolution..." \\ sed -i \ \\ -e "/Exec=/i\StartupWMClass=Google-chrome-$_channel" \ \\ -e "s/x-scheme-handler\/ftp;\?//g" \ \\ "$pkgdir"/usr/share/applications/google-chrome-$_channel.desktop \\ \\ msg2 "Removing Debian Cron job and duplicate product logos..." \\ rm -r "$pkgdir"/etc/cron.daily/ "$pkgdir"/opt/google/chrome-$_channel/cron/ \\ rm "$pkgdir"/opt/google/chrome-$_channel/product_logo_*.png \\} ; var expectedMap = std.StringHashMap(*Content).init(testing.allocator); defer expectedMap.deinit(); var package_val = std.ArrayList(u8).init(testing.allocator); try package_val.appendSlice( \\ { \\ msg2 "Extracting the data.tar.xz..." \\ bsdtar -xf data.tar.xz -C "$pkgdir/" \\ \\ msg2 "Moving stuff in place..." \\ # Launcher \\ install -m755 google-chrome-$_channel.sh "$pkgdir"/usr/bin/google-chrome-$_channel \\ \\ # Icons \\ for i in 16x16 24x24 32x32 48x48 64x64 128x128 256x256; do \\ install -Dm644 "$pkgdir"/opt/google/chrome-$_channel/product_logo_${i/x*/}_${pkgname/*-/}.png \ \\ "$pkgdir"/usr/share/icons/hicolor/$i/apps/google-chrome-$_channel.png \\ done \\ \\ # License \\ install -Dm644 eula_text.html "$pkgdir"/usr/share/licenses/google-chrome-$_channel/eula_text.html \\ \\ msg2 "Fixing Chrome icon resolution..." \\ sed -i \ \\ -e "/Exec=/i\StartupWMClass=Google-chrome-$_channel" \ \\ -e "s/x-scheme-handler\/ftp;\?//g" \ \\ "$pkgdir"/usr/share/applications/google-chrome-$_channel.desktop \\ \\ msg2 "Removing Debian Cron job and duplicate product logos..." \\ rm -r "$pkgdir"/etc/cron.daily/ "$pkgdir"/opt/google/chrome-$_channel/cron/ \\ rm "$pkgdir"/opt/google/chrome-$_channel/product_logo_*.png \\ } \\ ); var package_content = try Content.init(testing.allocator, package_val.toOwnedSlice()); defer package_content.deinit(testing.allocator); try expectedMap.putNoClobber("package()", package_content); var pkgbuild = Pkgbuild.init(testing.allocator, file_contents); defer pkgbuild.deinit(); try pkgbuild.readLines(); try pkgbuild.indentValues(2); try testing.expectEqualStrings(expectedMap.get("package()").?.value, pkgbuild.fields.get("package()").?.value); }
src/pkgbuild.zig
const std = @import("std"); const StringHashMap = std.StringHashMap; const StringArrayHashMap = std.StringArrayHashMap; const StringHashMapUnmanaged = std.StringHashMapUnmanaged; const StringArrayHashMapUnmanaged = std.StringArrayHashMapUnmanaged; const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const ArrayListUnmanaged = std.ArrayListUnmanaged; const json = std.json; const util = @import("util.zig"); pub fn SlicePtrIterator(comptime T: type) type { return struct { slice: []T, pub fn init(sl: []T) @This() { return @This(){.slice=sl}; } pub fn next(this: *@This()) ?*T { if (this.slice.len > 0) { defer this.slice = this.slice[1..]; return &this.slice[0]; } else { return null; } } }; } pub const DictError = error { put_clobber, OutOfMemory, }; fn WarpedUnmanaged(comptime StdHashedUnmanaged: fn (type) type) fn (type) type { // frees key-strings on deinit return struct { pub fn val_t(comptime V: type) type { return struct { const Data = StdHashedUnmanaged(V); data: Data = .{}, const Self = @This(); const K = []const u8; const Size = switch (StdHashedUnmanaged) { StringHashMapUnmanaged => u32, StringArrayHashMapUnmanaged => usize, else => @compileError("WarpedUnmanaged.Size nonexhaustive switch on StdHashedUnmanaged"), }; pub const Error = DictError; pub fn deinit(this: *Self, ator: Allocator) void { var key_it = this.keyIterator(); while (key_it.next()) |key_ptr| { ator.free(key_ptr.*); } this.data.deinit(ator); } pub const OperationOptions = struct { kopy: bool, // cOPY Keys }; pub fn rawPut( this: *Self, key: K, val: V, ator: Allocator, options: OperationOptions, ) Error!void { if (options.kopy) { var copy = try strCopyAlloc(key, ator); errdefer ator.free(copy); try this.data.put(ator, copy, val); } else { try this.data.put(ator, key, val); } } pub fn rawPutAssumeCapacity( this: *Self, key: K, val: V, ator: Allocator, options: OperationOptions, ) Error!void { if (options.kopy) { var copy = try strCopyAlloc(key, ator); errdefer ator.free(copy); this.data.putAssumeCapacity(copy, val); } else { this.data.putAssumeCapacity(key, val); } } /// on ks == .copy key is not copied iff entry already exists!!! pub fn put( this: *Self, key: K, val: V, ator: Allocator, options: OperationOptions, ) Error!void { if (this.getEntry(key)) |entry| { if (options.kopy) { // const key_copy = try strCopyAlloc(key, ator); // ator.free(entry.key_ptr.*); // entry.key_ptr.* = key_copy; entry.value_ptr.* = val; } else { ator.free(entry.key_ptr.*); entry.key_ptr.* = key; entry.value_ptr.* = val; } } else { try this.rawPut(key, val, ator, options); } } pub fn putAssumeCapacity( this: *Self, key: K, val: V, ator: Allocator, options: OperationOptions, ) Error!void { if (this.getEntry(key)) |entry| { if (options.kopy) { // const key_copy = try strCopyAlloc(key, ator); // ator.free(entry.key_ptr.*); // entry.key_ptr.* = key_copy; entry.value_ptr.* = val; } else { ator.free(entry.key_ptr.*); entry.key_ptr.* = key; entry.value_ptr.* = val; } } else { try this.rawPutAssumeCapacity(key, val, ator, options); } } pub fn putNoClobber( this: *Self, key: K, val: V, ator: Allocator, options: OperationOptions, ) Error!void { if (this.contains(key)) { return Error.put_clobber; } try this.rawPut(key, val, ator, options); } pub fn get(this: Self, key: K) ?V { return this.data.get(key); } pub fn getPtr(this: Self, key: K) ?*V { return this.data.getPtr(key); } pub fn getKey(this: Self, key: K) ?K { return this.data.getKey(key); } pub fn getKeyPtr(this: Self, key: K) ?*K { return this.data.getKeyPtr(key); } pub const Entry = Data.Entry; pub fn getEntry(this: Self, key: K) ?Entry { return this.data.getEntry(key); } pub fn remove(this: *Self, key: K, ator: Allocator) bool { if (this.getKeyPtr(key)) |key_ptr| { const k = key_ptr.*; // not a single clue why this in needed, segfault otherwise switch (StdHashedUnmanaged) { StringHashMapUnmanaged => { _ = this.data.remove(key); }, StringArrayHashMapUnmanaged => { _ = this.data.orderedRemove(key); }, else => { @compileError("WarpedUnmanaged.remove() nonexhaustive switch on StdHashedUnmanaged"); }, } ator.free(k); return true; } return false; } pub fn contains(this: *Self, key: K) bool { return this.data.contains(key); } pub fn clone(self: Self, ator: Allocator) Error!Self { var data_copy = try self.data.clone(ator); errdefer data_copy.deinit(ator); var key_copies_storage = ArrayListUnmanaged([]const u8){}; defer key_copies_storage.deinit(ator); try key_copies_storage.ensureTotalCapacity(ator, self.data.count()); errdefer { for (key_copies_storage.items) |item| { ator.free(item); } } var k_it = self.keyIterator(); while (k_it.next()) |key_ptr| { var key_copy = try strCopyAlloc(key_ptr.*, ator); errdefer ator.free(key_copy); // try key_copies_storage.append(ator, key_copy); key_copies_storage.appendAssumeCapacity(key_copy); data_copy.getKeyPtr(key_ptr.*).?.* = key_copy; } return Self{.data=data_copy}; } pub const clown = clone; // im the funniest pub fn move(this: *Self) Self { var res = Self{.data=this.data}; this.* = Self{}; return res; } pub fn swap(this: *Self, other: *Self) void { var swapper = other.move(); other.* = this.*; this.* = swapper.move(); } pub const Iterator = Data.Iterator; pub fn FieldIterator(comptime T: type) type { switch (StdHashedUnmanaged) { StringHashMapUnmanaged => { switch (T) { K => { return Data.KeyIterator; }, V => { return Data.ValueIterator; }, else => { @compileError("DictUnmanaged.FieldIterator(comptime) can only take K or V"); }, } // return Data.FieldIterator(T); }, StringArrayHashMapUnmanaged => { switch (T) { K => { return SlicePtrIterator(K); }, V => { return SlicePtrIterator(V); }, else => { @compileError("DictArrayUnmanaged.FieldIterator(comptime) can only take K or V"); }, } }, else => { @compileError("Warped.FieldIterator(comptime) nonexhaustive switch on StdHashedUnmanaged"); }, } } pub const KeyIterator = FieldIterator(K); pub const ValueIterator = FieldIterator(V); pub fn iterator(self: Self) Iterator { return self.data.iterator(); } pub fn keyIterator(self: Self) KeyIterator { switch (StdHashedUnmanaged) { StringHashMapUnmanaged => { return self.data.keyIterator(); }, StringArrayHashMapUnmanaged => { return KeyIterator.init(self.data.keys()); }, else => { @compileError("Warped.keyIterator() nonexhaustive switch on stdHashed"); }, } } pub fn valueIterator(self: Self) ValueIterator { switch (StdHashedUnmanaged) { StringHashMapUnmanaged => { return self.data.valueIterator(); }, StringArrayHashMapUnmanaged => { return ValueIterator.init(self.data.values()); }, else => { @compileError("Warped.valueIterator() nonexhaustive switch on stdHashed"); }, } } pub fn count(self: Self) Size { return self.data.count(); } pub fn toJson( self: Self, ator: Allocator, comptime settings: util.ToJsonSettings, ) util.ToJsonError!util.ToJsonResult { return dictLikeToJson(self, ator, settings); } pub fn equal( lhs: anytype, rhs: anytype, comptime settings: util.EqualSettings, ) bool { return dictLikeEqual(lhs, rhs, settings); } }; } }.val_t; } fn Warped(comptime StdHashed: fn (type) type) fn (type) type { // frees key-strings on deinit return struct { pub fn val_t(comptime V: type) type { return struct { const Data = StdHashed(V); data: Data, ator: Allocator, const Self = @This(); const K = []const u8; const Size = switch (StdHashed) { StringHashMap => u32, StringArrayHashMap => usize, else => @compileError("Warped.Size nonexhaustive switch on StdHashed"), }; pub const Error = DictError; pub fn init(ator: Allocator) Self { return Self{.data=Data.init(ator), .ator=ator}; } pub fn deinit(this: *Self) void { var key_it = this.keyIterator(); while (key_it.next()) |key_ptr| { this.ator.free(key_ptr.*); } this.data.deinit(); } pub const OperationOptions = struct { kopy: bool, // cOPY Keys }; pub fn rawPut( this: *Self, key: K, val: V, options: OperationOptions, ) Error!void { if (options.kopy) { var copy = try strCopyAlloc(key, this.ator); errdefer this.ator.free(copy); try this.data.put(copy, val); } else { try this.data.put(key, val); } } pub fn rawPutAssumeCapacity( this: *Self, key: K, val: V, options: OperationOptions, ) Error!void { if (options.kopy) { var copy = try strCopyAlloc(key, this.ator); errdefer this.ator.free(copy); this.data.putAssumeCapacity(copy, val); } else { this.data.putAssumeCapacity(key, val); } } /// on ks == .copy key is not copied iff entry already exists!!! pub fn put( this: *Self, key: K, val: V, options: OperationOptions, ) Error!void { if (this.getEntry(key)) |entry| { if (options.kopy) { // const key_copy = try strCopyAlloc(key, this.ator); // this.ator.free(entry.key_ptr.*); // entry.key_ptr.* = key_copy; entry.value_ptr.* = val; } else { this.ator.free(entry.key_ptr.*); entry.key_ptr.* = key; entry.value_ptr.* = val; } } else { try this.rawPut(key, val, options); } } pub fn putAssumeCapacity( this: *Self, key: K, val: V, options: OperationOptions, ) Error!void { if (this.getEntry(key)) |entry| { if (options.kopy) { // const key_copy = try strCopyAlloc(key, this.ator); // this.ator.free(entry.key_ptr.*); // entry.key_ptr.* = key_copy; entry.value_ptr.* = val; } else { this.ator.free(entry.key_ptr.*); entry.key_ptr.* = key; entry.value_ptr.* = val; } } else { try this.rawPutAssumeCapacity(key, val, options); } } pub fn putNoClobber( this: *Self, key: K, val: V, options: OperationOptions, ) Error!void { if (this.contains(key)) { return Error.put_clobber; } try this.rawPut(key, val, options); } pub fn get(this: Self, key: K) ?V { return this.data.get(key); } pub fn getPtr(this: Self, key: K) ?*V { return this.data.getPtr(key); } pub fn getKey(this: Self, key: K) ?K { return this.data.getKey(key); } pub fn getKeyPtr(this: Self, key: K) ?*K { return this.data.getKeyPtr(key); } pub const Entry = Data.Entry; pub fn getEntry(this: Self, key: K) ?Entry { return this.data.getEntry(key); } pub fn remove(this: *Self, key: K) bool { if (this.getKeyPtr(key)) |key_ptr| { const k = key_ptr.*; // not a single clue why this in needed, segfault otherwise switch (StdHashed) { StringHashMap => { _ = this.data.remove(key); }, StringArrayHashMap => { _ = this.data.orderedRemove(key); }, else => { @compileError("Warped.remove() nonexhaustive switch on StdHashed"); }, } this.ator.free(k); return true; } return false; } pub fn contains(this: *Self, key: K) bool { return this.data.contains(key); } pub fn clone(self: Self) Error!Self { var data_copy = try self.data.clone(); errdefer data_copy.deinit(); var key_copies_storage = ArrayList([]const u8).init(self.ator); defer key_copies_storage.deinit(); try key_copies_storage.ensureTotalCapacity(self.data.count()); errdefer { for (key_copies_storage.items) |item| { self.ator.free(item); } } var k_it = self.keyIterator(); while (k_it.next()) |key_ptr| { var key_copy = try strCopyAlloc(key_ptr.*, self.ator); errdefer self.ator.free(key_copy); // try key_copies_storage.append(key_copy); key_copies_storage.appendAssumeCapacity(key_copy); data_copy.getKeyPtr(key_ptr.*).?.* = key_copy; } return Self{.data=data_copy, .ator=self.ator}; } pub const clown = clone; // im the funniest pub fn move(this: *Self) Self { var res = Self{.data=this.data, .ator=this.ator}; this.* = Self.init(this.ator); return res; } pub fn swap(this: *Self, other: *Self) void { if (this.ator.vtable != other.ator.vtable) unreachable; var swapper = other.move(); other.* = this.*; this.* = swapper.move(); } pub const Iterator = Data.Iterator; pub fn FieldIterator(comptime T: type) type { switch (StdHashed) { StringHashMap => { switch (T) { K => { return Data.KeyIterator; }, V => { return Data.ValueIterator; }, else => { @compileError("Dict.FieldIterator(comptime) can only take K or V"); }, } // return Data.FieldIterator(T); }, StringArrayHashMap => { switch (T) { K => { return SlicePtrIterator(K); }, V => { return SlicePtrIterator(V); }, else => { @compileError("DictArray.FieldIterator(comptime) can only take K or V"); }, } }, else => { @compileError("Warped.FieldIterator(comptime) nonexhaustive switch on StdHashed"); }, } } pub const KeyIterator = FieldIterator(K); pub const ValueIterator = FieldIterator(V); pub fn iterator(self: Self) Iterator { return self.data.iterator(); } pub fn keyIterator(self: Self) KeyIterator { switch (StdHashed) { StringHashMap => { return self.data.keyIterator(); }, StringArrayHashMap => { return KeyIterator.init(self.data.keys()); }, else => { @compileError("Warped.keyIterator() nonexhaustive switch on stdHashed"); }, } } pub fn valueIterator(self: Self) ValueIterator { switch (StdHashed) { StringHashMap => { return self.data.valueIterator(); }, StringArrayHashMap => { return ValueIterator.init(self.data.values()); }, else => { @compileError("Warped.valueIterator() nonexhaustive switch on stdHashed"); }, } } pub fn count(self: Self) Size { return self.data.count(); } pub fn toJson( self: Self, ator: Allocator, comptime settings: util.ToJsonSettings, ) util.ToJsonError!util.ToJsonResult { return dictLikeToJson(self, ator, settings); } pub fn equal( lhs: anytype, rhs: anytype, comptime settings: util.EqualSettings, ) bool { return dictLikeEqual(lhs, rhs, settings); } }; } }.val_t; } pub fn dictLikeToJson( self: anytype, _ator: Allocator, comptime settings: util.ToJsonSettings, ) util.ToJsonError!util.ToJsonResult { // TODO make 2 if's 1 var res = util.ToJsonResult{ .value = undefined, .arena = if (settings.apply_arena) ArenaAllocator.init(_ator) else null, }; errdefer res.deinit(); const ator = if (res.arena) |*arena| arena.allocator() else _ator; res.value = .{.Object=json.ObjectMap.init(ator)}; const settings_to_pass = util.ToJsonSettings{ .allow_overload = settings.allow_overload, // must be true .apply_arena = false, }; try res.value.Object.ensureUnusedCapacity(self.count()); var viter = self.valueIterator(); var kiter = self.keyIterator(); while (viter.next()) |val| { if (kiter.next()) |key| { var value = try util.toJson(val.*, ator, settings_to_pass); // TODO should it be no-clobber??? res.value.Object.putAssumeCapacity(key.*, value.value); } else { break; } } return res; } pub fn dictLikeEqual( lhs: anytype, rhs: anytype, comptime settings: util.EqualSettings, ) bool { if (lhs.count() != rhs.count()) { std.debug.print("\n{d} != {d}: count mismatch\n", .{lhs.count(), rhs.count()}); return false; } var liter = lhs.iterator(); while (liter.next()) |lentry| { if (rhs.get(lentry.key_ptr.*)) |rval| { if (!util.equal(lentry.value_ptr.*, rval, settings)) { std.debug.print("\n{s} key mismatch!\n", .{lentry.key_ptr.*}); return false; } } else { std.debug.print("\n{s} key abscence!\n", .{lentry.key_ptr.*}); return false; } } return true; } pub const DictUnmanaged = WarpedUnmanaged(StringHashMapUnmanaged); pub const DictArrayUnmanaged = WarpedUnmanaged(StringArrayHashMapUnmanaged); pub const Dict = Warped(StringHashMap); pub const DictArray = Warped(StringArrayHashMap); const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; const expectError = testing.expectError; const tator = testing.allocator; test "dict unmanaged" { var d = DictUnmanaged(i32){}; defer d.deinit(tator); try d.put("osetr", 1, tator, .{.kopy=true}); try expect(d.get("osetr").? == 1); var e_it = d.iterator(); var unhandled_str = try strCopyAlloc("ahahahahaha", tator); // no defer free try d.put(unhandled_str, 2, tator, .{.kopy=false}); try expectError(Dict(i32).Error.put_clobber, d.putNoClobber("osetr", 2, tator, .{.kopy=true})); try expect(d.remove("osetr", tator)); try expect(!d.remove("osetr", tator)); try d.put("osetr", 2, tator, .{.kopy=true}); try d.put("osetr", 3, tator, .{.kopy=true}); try expect(d.get("osetr").? == 3); try expect(d.get(unhandled_str).? == 2); d.getPtr("osetr").?.* = 4; try expect(d.get("osetr").? == 4); while (e_it.next()) |entry| { try expect(@TypeOf(entry.key_ptr.*) == []const u8); try expect(@TypeOf(entry.value_ptr.*) == i32); } var v_it = d.valueIterator(); while (v_it.next()) |v_ptr| { try expect(@TypeOf(v_ptr.*) == i32); } var k_it = d.keyIterator(); while (k_it.next()) |k_ptr| { try expect(@TypeOf(k_ptr.*) == []const u8); } var c = try d.clown(tator); defer c.deinit(tator); try expect(c.get("osetr").? == 4); var cc = try c.clown(tator); // no defer deinit var m = cc.move(); defer m.deinit(tator); var s = DictUnmanaged(i32){}; defer s.deinit(tator); var ccc = try c.clown(tator); // no defer deinit s.swap(&ccc); try expect(ccc.data.count() == 0); try expect(s.get("osetr").? == 4); } test "dict array unmanaged" { var d = DictArrayUnmanaged(i32){}; defer d.deinit(tator); try d.put("osetr", 1, tator, .{.kopy=true}); try expect(d.get("osetr").? == 1); var e_it = d.iterator(); var unhandled_str = try strCopyAlloc("ahahahahaha", tator); // no defer free try d.put(unhandled_str, 2, tator, .{.kopy=false}); try expectError(Dict(i32).Error.put_clobber, d.putNoClobber("osetr", 2, tator, .{.kopy=true})); try expect(d.remove("osetr", tator)); try expect(!d.remove("osetr", tator)); try d.put("osetr", 2, tator, .{.kopy=true}); try d.put("osetr", 3, tator, .{.kopy=true}); try expect(d.get("osetr").? == 3); try expect(d.get(unhandled_str).? == 2); d.getPtr("osetr").?.* = 4; try expect(d.get("osetr").? == 4); while (e_it.next()) |entry| { try expect(@TypeOf(entry.key_ptr.*) == []const u8); try expect(@TypeOf(entry.value_ptr.*) == i32); } var v_it = d.valueIterator(); while (v_it.next()) |v_ptr| { try expect(@TypeOf(v_ptr.*) == i32); } var k_it = d.keyIterator(); while (k_it.next()) |k_ptr| { try expect(@TypeOf(k_ptr.*) == []const u8); } var c = try d.clown(tator); defer c.deinit(tator); try expect(c.get("osetr").? == 4); var cc = try c.clown(tator); // no defer deinit var m = cc.move(); defer m.deinit(tator); var s = DictArrayUnmanaged(i32){}; defer s.deinit(tator); var ccc = try c.clown(tator); // no defer deinit s.swap(&ccc); try expect(ccc.data.count() == 0); try expect(s.get("osetr").? == 4); } test "dict" { var d = Dict(i32).init(tator); defer d.deinit(); try d.put("osetr", 1, .{.kopy=true}); try expect(d.get("osetr").? == 1); var e_it = d.iterator(); var unhandled_str = try strCopyAlloc("ahahahahaha", tator); // no defer free try d.put(unhandled_str, 2, .{.kopy=false}); try expectError(Dict(i32).Error.put_clobber, d.putNoClobber("osetr", 2, .{.kopy=true})); try expect(d.remove("osetr")); try expect(!d.remove("osetr")); try d.put("osetr", 2, .{.kopy=true}); try d.put("osetr", 3, .{.kopy=true}); try expect(d.get("osetr").? == 3); try expect(d.get(unhandled_str).? == 2); d.getPtr("osetr").?.* = 4; try expect(d.get("osetr").? == 4); while (e_it.next()) |entry| { try expect(@TypeOf(entry.key_ptr.*) == []const u8); try expect(@TypeOf(entry.value_ptr.*) == i32); } var v_it = d.valueIterator(); while (v_it.next()) |v_ptr| { try expect(@TypeOf(v_ptr.*) == i32); } var k_it = d.keyIterator(); while (k_it.next()) |k_ptr| { try expect(@TypeOf(k_ptr.*) == []const u8); } var c = try d.clown(); defer c.deinit(); try expect(c.get("osetr").? == 4); var cc = try c.clown(); // no defer deinit var m = cc.move(); defer m.deinit(); var s = Dict(i32).init(tator); defer s.deinit(); var ccc = try c.clown(); // no defer deinit s.swap(&ccc); try expect(ccc.data.count() == 0); try expect(s.get("osetr").? == 4); } test "dict array" { var d = DictArray(i32).init(tator); defer d.deinit(); try d.put("osetr", 1, .{.kopy=true}); try expect(d.get("osetr").? == 1); var e_it = d.iterator(); var unhandled_str = try strCopyAlloc("ahahahahaha", tator); // no defer free try d.put(unhandled_str, 2, .{.kopy=false}); try expectError(Dict(i32).Error.put_clobber, d.putNoClobber("osetr", 2, .{.kopy=true})); try expect(d.remove("osetr")); try expect(!d.remove("osetr")); try d.put("osetr", 2, .{.kopy=true}); try d.put("osetr", 3, .{.kopy=true}); try expect(d.get("osetr").? == 3); try expect(d.get(unhandled_str).? == 2); d.getPtr("osetr").?.* = 4; try expect(d.get("osetr").? == 4); while (e_it.next()) |entry| { try expect(@TypeOf(entry.key_ptr.*) == []const u8); try expect(@TypeOf(entry.value_ptr.*) == i32); } var v_it = d.valueIterator(); while (v_it.next()) |v_ptr| { try expect(@TypeOf(v_ptr.*) == i32); } var k_it = d.keyIterator(); while (k_it.next()) |k_ptr| { try expect(@TypeOf(k_ptr.*) == []const u8); } var c = try d.clown(); defer c.deinit(); try expect(c.get("osetr").? == 4); } test "to json" { { var dict = DictUnmanaged(i64){}; defer dict.deinit(tator); try dict.put("key1", 1, tator, .{.kopy=true}); var j_dict_ = try dict.toJson(tator, .{}); defer j_dict_.deinit(); var j_dict = j_dict_.value.Object; try expectEqual(dict.get("key1").?, j_dict.get("key1").?.Integer); } { var dict = Dict(i64).init(tator); defer dict.deinit(); try dict.put("key1", 1, .{.kopy=true}); var j_dict_ = try dict.toJson(tator, .{}); defer j_dict_.deinit(); var j_dict = j_dict_.value.Object; try expectEqual(dict.get("key1").?, j_dict.get("key1").?.Integer); } { var ddict = Dict(Dict(i64)).init(tator); defer ddict.deinit(); var dict = Dict(i64).init(tator); defer dict.deinit(); try dict.put("key", 1, .{.kopy=true}); try ddict.put("kkey", dict, .{.kopy=true}); var j_ddict_ = try ddict.toJson(tator, .{}); defer j_ddict_.deinit(); var j_ddict = j_ddict_.value.Object; try expectEqual( ddict.get("kkey").?.get("key"), j_ddict.get("kkey").?.Object.get("key").?.Integer, ); } } fn strCopyAlloc(from: []const u8, ator: Allocator) ![]u8 { var res = try ator.alloc(u8, from.len); for (from) |c, i| { res[i] = c; } return res; } fn strEqual(lhs: []const u8, rhs: []const u8) bool { if (lhs.len != rhs.len) return false; for (lhs) |c, i| { if (c != rhs[i]) return false; } return true; }
src/dict.zig
const Builder = @This(); const std = @import("std"); const SrcEntry = @import("SrcEntry.zig"); const string = []const u8; pub const DEFAULT_BUILD_DIR = "fimbs-out"; pub const DEFAULT_OBJS_DIR = "objs"; allocator: std.mem.Allocator, cc: string = "clang", cflags: string = "-DDEBUG -Wall", bin_name: string = "a.out", build_dir: string, objs_dir: string, srcs: std.ArrayList(SrcEntry), objs: std.ArrayList([]u8), argv: std.ArrayList(string), pub fn init( allocator: std.mem.Allocator, bin_name: ?string, build_dir: ?string, objs_dir: ?string, ) Builder { return .{ .allocator = allocator, .bin_name = bin_name orelse "a.out", .build_dir = build_dir orelse DEFAULT_BUILD_DIR, .objs_dir = objs_dir orelse DEFAULT_OBJS_DIR, .srcs = std.ArrayList(SrcEntry).init(allocator), .objs = std.ArrayList([]u8).init(allocator), .argv = std.ArrayList(string).init(allocator), }; } pub fn deinit(self: Builder) void { for (self.srcs.items) |src| src.deinit(); self.srcs.deinit(); for (self.objs.items) |obj| self.allocator.free(obj); self.objs.deinit(); self.argv.deinit(); } pub fn setOutputDir(self: *Builder, dir_name: string) void { self.build_dir = dir_name; } pub fn build(self: *Builder) !void { var cwd = std.fs.cwd(); try makeDirIfNotExist(cwd, self.build_dir); var build_dir = try cwd.openDir(self.build_dir, .{}); try self.argv.append(self.cc); try self.buildObjectFiles(build_dir); try self.linkObjectFiles(build_dir); } fn buildObjectFiles(self: *Builder, build_dir: std.fs.Dir) !void { try makeDirIfNotExist(build_dir, self.objs_dir); try self.argv.append(self.cflags); try self.argv.append("-c"); for (self.srcs.items) |src| { std.log.info("Compiling {s}", .{src.name}); try self.argv.append(try src.toFullPath(self.allocator)); try self.argv.append("-o"); var obj_name = try src.toObjName(self.allocator); defer self.allocator.free(obj_name); var obj_output_path = try std.fs.path.join(self.allocator, &.{ self.build_dir, self.objs_dir, obj_name, }); try self.argv.append(obj_output_path); try self.objs.append(obj_output_path); const exec_result = try std.ChildProcess.exec(.{ .allocator = self.allocator, .argv = self.argv.items, }); if (exec_result.stderr.len > 1) { std.debug.print("{s}", .{exec_result.stderr}); } _ = self.argv.popOrNull(); _ = self.argv.popOrNull(); var src_full_path = self.argv.popOrNull().?; self.allocator.free(src_full_path); } _ = self.argv.popOrNull(); _ = self.argv.popOrNull(); } fn linkObjectFiles(self: *Builder, build_dir: std.fs.Dir) !void { try makeDirIfNotExist(build_dir, "bin"); for (self.objs.items) |obj| try self.argv.append(obj); try self.argv.append("-o"); var bin_output_dir = try std.fs.path.join(self.allocator, &.{ self.build_dir, "bin", self.bin_name, }); defer self.allocator.free(bin_output_dir); try self.argv.append(bin_output_dir); const exec_result = try std.ChildProcess.exec(.{ .allocator = self.allocator, .argv = self.argv.items, }); if (exec_result.stderr.len > 1) std.debug.print("{s}", .{exec_result.stderr}); _ = self.argv.popOrNull(); _ = self.argv.popOrNull(); // remove all objs from argv var i: usize = 1; while (i != self.objs.items.len) : (i += 1) { _ = self.argv.popOrNull(); } } fn makeDirIfNotExist(dir: std.fs.Dir, dir_name: string) !void { dir.makeDir(dir_name) catch |err| switch (err) { error.PathAlreadyExists => return, else => return err, }; }
src/Builder.zig
const std = @import("std"); const utils = @import("../../utils.zig"); const imgio = @import("../../io.zig"); const color = @import("../../color.zig"); const PixelFormat = @import("../../pixel_format.zig").PixelFormat; const bigToNative = std.mem.bigToNative; const Allocator = std.mem.Allocator; const Colorf32 = color.Colorf32; pub const ImageParsingError = error{InvalidData} || Allocator.Error || imgio.ImageReadError; pub const magic_header = "\x89PNG\x0D\x0A\x1A\x0A"; pub const ColorType = enum(u8) { grayscale = 0, rgb_color = 2, indexed = 3, grayscale_alpha = 4, rgba_color = 6, const Self = @This(); pub fn channelCount(self: Self) u8 { return switch (self) { .grayscale => 1, .rgb_color => 3, .indexed => 1, .grayscale_alpha => 2, .rgba_color => 4, }; } }; pub const FilterType = enum(u8) { none = 0, sub = 1, up = 2, average = 3, paeth = 4, }; pub const InterlaceMethod = enum(u8) { none = 0, adam7 = 1, }; /// The compression methods supported by PNG pub const CompressionMethod = enum(u8) { deflate = 0 }; /// The filter methods supported by PNG pub const FilterMethod = enum(u8) { adaptive = 0 }; pub const ChunkHeader = packed struct { length_big_endian: u32, type: u32, const Self = @This(); pub fn length(self: Self) u32 { return bigToNative(u32, self.length_big_endian); } pub fn name(self: Self) []const u8 { return std.mem.asBytes(&self.type); } }; pub const HeaderData = packed struct { pub const chunk_type = "IHDR"; pub const chunk_type_id = std.mem.bytesToValue(u32, chunk_type); width_big_endian: u32, height_big_endian: u32, bit_depth: u8, color_type: ColorType, compression_method: CompressionMethod, filter_method: FilterMethod, interlace_method: InterlaceMethod, const Self = @This(); pub fn width(self: *const Self) u32 { return bigToNative(u32, self.width_big_endian); } pub fn height(self: *const Self) u32 { return bigToNative(u32, self.height_big_endian); } pub fn isValid(self: *const Self) bool { const max_dim = std.math.maxInt(u32) >> 1; const w = self.width(); const h = self.height(); if (w == 0 or w > max_dim) return false; if (h == 0 or h > max_dim) return false; if (!utils.isEnumValid(self.color_type)) return false; if (!utils.isEnumValid(self.compression_method)) return false; if (!utils.isEnumValid(self.filter_method)) return false; if (!utils.isEnumValid(self.interlace_method)) return false; const bd = self.bit_depth; return switch (self.color_type) { .grayscale => bd == 1 or bd == 2 or bd == 4 or bd == 8 or bd == 16, .indexed => bd == 1 or bd == 2 or bd == 4 or bd == 8, else => bd == 8 or bd == 16, }; } pub fn allowsPalette(self: *const Self) bool { return self.color_type == .indexed or self.color_type == .rgb_color or self.color_type == .rgba_color; } pub fn maxPaletteSize(self: *const Self) u16 { return if (self.bit_depth > 8) 256 else @as(u16, 1) << @truncate(u4, self.bit_depth); } pub fn channelCount(self: *const Self) u8 { return switch (self.color_type) { .grayscale => 1, .rgb_color => 3, .indexed => 1, .grayscale_alpha => 2, .rgba_color => 4, }; } pub fn pixelBits(self: *const Self) u8 { return self.bit_depth * self.channelCount(); } pub fn lineBytes(self: *const Self) u32 { return (self.pixelBits() * self.width() + 7) / 8; } pub fn getPixelFormat(self: *const Self) PixelFormat { return switch (self.color_type) { .grayscale => switch (self.bit_depth) { 1 => PixelFormat.grayscale1, 2 => PixelFormat.grayscale2, 4 => PixelFormat.grayscale4, 8 => PixelFormat.grayscale8, 16 => PixelFormat.grayscale16, else => unreachable, }, .rgb_color => switch (self.bit_depth) { 8 => PixelFormat.rgb24, 16 => PixelFormat.rgb48, else => unreachable, }, .indexed => switch (self.bit_depth) { 1 => PixelFormat.index1, 2 => PixelFormat.index2, 4 => PixelFormat.index4, 8 => PixelFormat.index8, else => unreachable, }, .grayscale_alpha => switch (self.bit_depth) { 8 => PixelFormat.grayscale8Alpha, 16 => PixelFormat.grayscale16Alpha, else => unreachable, }, .rgba_color => switch (self.bit_depth) { 8 => PixelFormat.rgba32, 16 => PixelFormat.rgba64, else => unreachable, }, }; } };
src/formats/png/types.zig
const std = @import("std"); const requestz = @import("requestz"); pub fn run(event_handler: fn (*std.mem.Allocator, []const u8) anyerror![]const u8) !void { // TODO: remove inferred error set? const prefix = "http://"; const postfix = "/2018-06-01/runtime/invocation"; const lambda_runtime_uri = std.os.getenv("AWS_LAMBDA_RUNTIME_API"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; const url = try std.fmt.allocPrint(allocator, "{s}{s}{s}/next", .{ prefix, lambda_runtime_uri, postfix }); defer allocator.free(url); std.log.notice("Bootstrap initializing with event url: {s}", .{url}); while (true) { var req_alloc = std.heap.ArenaAllocator.init(allocator); defer req_alloc.deinit(); const req_allocator = &req_alloc.allocator; var client = try requestz.Client.init(req_allocator); // defer client.deinit(); // Lambda freezes the process at this line of code. During warm start, // the process will unfreeze and data will be sent in response to client.get var response = client.get(url, .{}) catch |err| { std.log.err("Get fail: {}", .{err}); // Documentation says something about "exit immediately". The // Lambda infrastrucutre restarts, so it's unclear if that's necessary. // It seems as though a continue should be fine, and slightly faster // std.os.exit(1); continue; }; defer response.deinit(); var request_id: ?[]const u8 = null; for (response.headers.items()) |h| { if (std.mem.indexOf(u8, h.name.value, "Lambda-Runtime-Aws-Request-Id")) |_| request_id = h.value; // TODO: XRay uses an environment variable to do its magic. It's our // responsibility to set this, but no zig-native setenv(3)/putenv(3) // exists. I would kind of rather not link in libc for this, // so we'll hold for now and think on this // if (std.mem.indexOf(u8, h.name.value, "Lambda-Runtime-Trace-Id")) |_| // std.process. // std.os.setenv("AWS_LAMBDA_RUNTIME_API"); } if (request_id == null) { // We can't report back an issue because the runtime error reporting endpoint // uses request id in its path. So the best we can do is log the error and move // on here. std.log.err("Could not find request id: skipping request", .{}); continue; } const req_id = request_id.?; const event_response = event_handler(req_allocator, response.body) catch |err| { // Stack trace will return null if stripped const return_trace = @errorReturnTrace(); std.log.err("Caught error: {}. Return Trace: {}", .{ err, return_trace }); const err_url = try std.fmt.allocPrint(req_allocator, "{s}{s}/runtime/invocation/{s}/error", .{ prefix, lambda_runtime_uri, req_id }); defer req_allocator.free(err_url); const content = \\ {s} \\ "errorMessage": "{s}", \\ "errorType": "HandlerReturnedError", \\ "stackTrace": [ "{}" ] \\ {s} ; const content_fmt = try std.fmt.allocPrint(req_allocator, content, .{ "{", @errorName(err), return_trace, "}" }); defer req_allocator.free(content_fmt); std.log.err("Posting to {s}: Data {s}", .{ err_url, content_fmt }); var headers = .{.{ "Lambda-Runtime-Function-Error-Type", "HandlerReturned" }}; // TODO: Determine why this post is not returning var err_resp = client.post(err_url, .{ .content = content_fmt, .headers = headers, }) catch |post_err| { // Well, at this point all we can do is shout at the void std.log.err("Error posting response for request id {s}: {}", .{ req_id, post_err }); std.os.exit(0); continue; }; std.log.err("Post complete", .{}); defer err_resp.deinit(); continue; }; const response_url = try std.fmt.allocPrint(req_allocator, "{s}{s}{s}/{s}/response", .{ prefix, lambda_runtime_uri, postfix, req_id }); // defer req_allocator.free(response_url); var resp_resp = client.post(response_url, .{ .content = event_response }) catch |err| { // TODO: report error std.log.err("Error posting response for request id {s}: {}", .{ req_id, err }); continue; }; defer resp_resp.deinit(); } }
src/lambda.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const Bus = @import("bus.zig").Bus; const Cart = @import("cart.zig").Cart; const Cpu = @import("cpu/cpu.zig").Cpu; const Vip = @import("hw/vip.zig").Vip; const Vsu = @import("hw/vsu.zig").Vsu; const sdl = @cImport(@cInclude("SDL2/SDL.h")); const WRAM_SIZE = comptime 64 * 1024; pub const Vb = struct { allocator: *Allocator, cpu: Cpu, vip: Vip, vsu: Vsu, wram: []u8, cart: Cart, pub fn new(allocator: *Allocator, rom_path: []const u8) !Vb { var cart = try Cart.new(allocator, rom_path); var vip = try Vip.new(allocator); var vsu = try Vsu.new(allocator); var wram = try allocator.alloc(u8, WRAM_SIZE); mem.set(u8, wram, 0); const debug_mode = true; var cpu = Cpu.new(allocator, &cart, debug_mode); return Vb{ .allocator = allocator, .cpu = cpu, .vip = vip, .vsu = vsu, .wram = wram, .cart = cart, }; } pub fn run(self: *Vb) void { self.cpu.boot(self.wram[0..], &self.cart, &self.vip, &self.vsu); // var window: ?*sdl.SDL_Window = null; // var surface: ?*sdl.SDL_Surface = null; // const disp_width = 384; // const disp_height = 224; // if (sdl.SDL_Init(sdl.SDL_INIT_VIDEO) != 0) { // std.debug.warn("Error initializing SDL: {s}", .{sdl.SDL_GetError()}); // std.process.exit(1); // } else { // window = sdl.SDL_CreateWindow("ichigo", 200, 200, disp_width, disp_height, sdl.SDL_WINDOW_SHOWN); // if (window == null) { // std.debug.warn("Error creating SDL window: {s}", .{sdl.SDL_GetError()}); // std.process.exit(1); // } else { // surface = sdl.SDL_GetWindowSurface(window); // } // } while (true) { self.cpu.cycle(); self.vip.cycle(); // _ = sdl.SDL_FillRect(surface.?, null, sdl.SDL_MapRGB(surface.?.format, 0, 0, 0)); // _ = sdl.SDL_UpdateWindowSurface(window); } } };
src/vb.zig
const prompts = @import("../components/prompt.zig"); const gamepad = @import("../gamepad.zig"); const w4 = @import("../wasm4.zig"); const statemachine = @import("../state-machine.zig"); const std = @import("std"); const Situation = @import("../components/situation.zig").Situation; const sprites = @import("../assets/sprites.zig"); const statusbar = @import("../components/status-bar.zig"); var start_ticks: u32 = 0; const all_situations = @import("../assets/presscon-situations.zig").all_press_conference_situations; const SCREEN_SIZE: u8 = 160; const MAX_CONFIDENCE = 120; var confidenceBar: statusbar.StatusBar = undefined; pub const PressState = struct { prompt: prompts.Prompt, situation_history: [3]u8 = [3]u8{ 0, 0, 0 }, weights: [3]u8 = [3]u8{ 0, 0, 0 }, round: u8 = 0, rnd: *std.rand.Random, pub fn reset(self: *@This()) void { for (self.situation_history) |*i| { i.* = 0; } self.round = 0; } pub fn init(rnd: *std.rand.Random) PressState { var ps = PressState{ // pass temporary situation .prompt = prompts.buttonPrompt(), .rnd = rnd, }; confidenceBar = statusbar.StatusBar{ .locy = 8, .maximum_value = MAX_CONFIDENCE, .value = MAX_CONFIDENCE }; ps.setRandomSituation(); return ps; } pub fn setSituationByIndex(self: *@This(), i: u8) void { self.prompt.setSituation(&all_situations[i]); self.prompt.shuffleOrder(self.rnd); self.newRandomWeights(); self.prompt.selection = 0; //self.situation_history[self.round] = i; } pub fn update(self: *@This(), state: *statemachine.StateMachine, pl: *const gamepad.GamePad, disallowed: []const u8) void { // init confidence bar value confidenceBar.value = state.confidence; // draw the confidence bar confidenceBar.draw(); w4.DRAW_COLORS.* = 0x24; w4.text("PRESS CONFERENCE", 0, 0); w4.text("CONFIDENCE", SCREEN_SIZE - (10 * 8), 18); // set disallowed self.prompt.disallow = disallowed[self.round]; self.handleInput(state, pl); self.prompt.update(); var xOff: u32 = 0; if (start_ticks % 20 > 10) { xOff = 16; } w4.DRAW_COLORS.* = 0x0432; w4.blitSub(sprites.guest.data, 20, 70, // x, y sprites.guest.height, sprites.guest.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.guest.width, // Assumes stride and width are equal sprites.guest.flags); w4.blitSub(sprites.guest.data, 20, 30, // x, y sprites.guest.height, sprites.guest.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.guest.width, // Assumes stride and width are equal sprites.guest.flags); w4.DRAW_COLORS.* = 0x0432; w4.blitSub(sprites.boris.data, 50, 50, // x, y sprites.boris.height, sprites.boris.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.boris.width, // Assumes stride and width are equal sprites.boris.flags); w4.blitSub(sprites.press.data, 80, 30, // x, y sprites.press.height, sprites.press.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.press.width, // Assumes stride and width are equal sprites.press.flags | 0x2); w4.blitSub(sprites.press.data, 110, 40, // x, y sprites.press.height, sprites.press.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.press.width, // Assumes stride and width are equal sprites.press.flags | 0x2); w4.blitSub(sprites.press.data, 90, 50, // x, y sprites.press.height, sprites.press.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.press.width, // Assumes stride and width are equal sprites.press.flags | 0x2); w4.blitSub(sprites.press.data, 110, 60, // x, y sprites.press.height, sprites.press.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.press.width, // Assumes stride and width are equal sprites.press.flags | 0x2); w4.blitSub(sprites.press.data, 80, 70, // x, y sprites.press.height, sprites.press.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.press.width, // Assumes stride and width are equal sprites.press.flags | 0x2); start_ticks += 1; } pub fn setRandomSituation(self: *@This()) void { const i = self.newRandomSituationIndex(); self.setSituationByIndex(i); } fn newRandomWeights(self: *@This()) void { // generate low weight 5-10 self.weights[0] = self.rnd.intRangeLessThan(u8, 5, 11); // genereate medium weight 10-30 self.weights[1] = self.rnd.intRangeLessThan(u8, 10, 31); // generate high weight 30-50 self.weights[2] = self.rnd.intRangeLessThan(u8, 30, 51); } fn newRandomSituationIndex(self: *@This()) u8 { return self.rnd.intRangeLessThan(u8, 0, all_situations.len); } fn handleInput(self: *@This(), state: *statemachine.StateMachine, pl: *const gamepad.GamePad) void { if (pl.isPressed(w4.BUTTON_DOWN)) { self.prompt.incSelection(); } else if (pl.isPressed(w4.BUTTON_UP)) { self.prompt.decSelection(); } else if (pl.isPressed(w4.BUTTON_1)) { // save choice var choice = self.prompt.getSelection(); // update confidence score state.confidence += self.weights[choice]; // log it for now // update round self.round += 1; if (self.round >= 3) { // reset self self.reset(); state.change(.TO_COMMONS_TRANSITION); } else { // new situation self.setRandomSituation(); } } } };
src/screens/press-conference.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/test/day16.txt"); const HexToIntReader = struct { const Self = @This(); raw: []const u8, offset: usize = 0, val: u4 = 0, bits_left: u3 = 0, total_bits_read: usize = 0, fn readInt(self: *Self, comptime T: type) T { const total_bit_count: usize = @typeInfo(T).Int.bits; var return_bit_count: usize = total_bit_count; var result: T = 0; while (return_bit_count > 0) { if (self.bits_left == 0) { self.val = parseInt(u4, self.raw[self.offset .. self.offset + 1], 16) catch unreachable; self.offset += 1; self.bits_left = 4; // print("Read: {0x} {0b:0>4}\n", .{self.val}); } if (return_bit_count >= self.bits_left) { if (result > 0) result <<= @intCast(Log2Int(T), self.bits_left); result |= @intCast(T, self.val); self.val = 0; return_bit_count -= self.bits_left; self.total_bits_read += self.bits_left; self.bits_left = 0; } else { var shift: u2 = @intCast(u2, self.bits_left - return_bit_count); var x = self.val >> shift; if (result > 0) result <<= @intCast(Log2Int(T), return_bit_count); result |= @intCast(T, x); self.bits_left = shift; self.total_bits_read += return_bit_count; return_bit_count = 0; switch (self.bits_left) { 0 => self.val = 0, 1 => self.val &= 0b1, 2 => self.val &= 0b11, 3 => self.val &= 0b111, else => {}, } } } return result; } }; const Packet = struct { const Self = @This(); version: u3 = 0, id: u3 = 0, value: i64 = 0, length_type: u1 = 0, length_val: u15 = 0, bit_length: usize = 0, sub_packets: ArrayList(Packet), fn init(allocator: *Allocator) Packet { return .{ .sub_packets = ArrayList(Packet).init(allocator), }; } fn deinit(self: Self) void { for (self.sub_packets.items) |p| { p.deinit(); } self.sub_packets.deinit(); } }; fn readPacket(reader: *HexToIntReader, allocator: *Allocator) Packet { var result = Packet.init(allocator); result.version = reader.readInt(u3); result.id = reader.readInt(u3); result.bit_length = 6; if (result.id == 4) { var num: i64 = 0; var part = reader.readInt(u5); while (part & (1 << 4) != 0) { num |= (part & 0b1111); num <<= 4; result.bit_length += 5; part = reader.readInt(u5); } num |= part & 0b1111; result.value = num; result.bit_length += 5; } else { result.length_type = reader.readInt(u1); result.bit_length += 1; if (result.length_type == 0) { var subpacket_length = reader.readInt(u15); result.bit_length += 15; result.length_val = subpacket_length; var children_length: usize = 0; while (children_length < subpacket_length) { var p = readPacket(reader, allocator); result.sub_packets.append(p) catch unreachable; children_length += p.bit_length; result.bit_length += p.bit_length; } } else { var subpacket_count = reader.readInt(u11); result.bit_length += 11; result.length_val = subpacket_count; var idx: u11 = 0; while (idx < subpacket_count) : (idx += 1) { var p = readPacket(reader, allocator); result.sub_packets.append(p) catch unreachable; result.bit_length += p.bit_length; } } } return result; } fn printPacket(p: Packet, depth: usize) void { var idx: usize = 0; while (idx < depth) : (idx += 1) { print(" ", .{}); } var symbol: u8 = ' '; switch (p.id) { 0 => symbol = '+', 1 => symbol = '*', 2 => symbol = 'v', 3 => symbol = '^', 4 => symbol = ' ', 5 => symbol = '>', 6 => symbol = '<', 7 => symbol = '=', } if (p.id == 4) { print("{0}-{0b:0>3} {1c} {2}\n", .{ p.version, symbol, p.value }); } else { print("{0}-{0b:0>3} {1c} {4} ({2} {3})\n", .{ p.version, symbol, p.length_type, p.length_val, p.sub_packets.items.len }); } } fn printPacketTree(packet: Packet, depth: usize) void { printPacket(packet, depth); if (packet.id != 4) { for (packet.sub_packets.items) |p| { printPacketTree(p, depth + 2); } } } fn versionSum(packet: Packet) u64 { var result: u64 = packet.version; for (packet.sub_packets.items) |p| { result += versionSum(p); } return result; } fn evalPacket(packet: Packet) i64 { switch (packet.id) { 0 => { var result = evalPacket(packet.sub_packets.items[0]); for (packet.sub_packets.items[1..]) |p| { result += evalPacket(p); } return result; }, 1 => { var result = evalPacket(packet.sub_packets.items[0]); for (packet.sub_packets.items[1..]) |p| { result *= evalPacket(p); } return result; }, 2 => { var result = evalPacket(packet.sub_packets.items[0]); for (packet.sub_packets.items[1..]) |p| { result = min(result, evalPacket(p)); } return result; }, 3 => { var result = evalPacket(packet.sub_packets.items[0]); for (packet.sub_packets.items[1..]) |p| { result = max(result, evalPacket(p)); } return result; }, 4 => { return packet.value; }, 5 => { var a = evalPacket(packet.sub_packets.items[0]); var b = evalPacket(packet.sub_packets.items[1]); if (a > b) return 1; return 0; }, 6 => { var a = evalPacket(packet.sub_packets.items[0]); var b = evalPacket(packet.sub_packets.items[1]); if (a < b) return 1; return 0; }, 7 => { var a = evalPacket(packet.sub_packets.items[0]); var b = evalPacket(packet.sub_packets.items[1]); if (a == b) return 1; return 0; }, } } pub fn main() !void { var input = tokenize(data, "\r\n").next().?; var reader: HexToIntReader = .{ .raw = input }; var root_packet = readPacket(&reader, gpa); defer root_packet.deinit(); printPacketTree(root_packet, 0); print("Version sum: {}\n", .{versionSum(root_packet)}); print("Eval: {}\n", .{evalPacket(root_packet)}); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const Log2Int = std.math.Log2Int; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day16.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const c = @import("card.zig"); const Card = c.Card; const CardSchema = c.CardSchema; const i = @import("image.zig"); const Image = i.Image; const lua = @import("lua.zig").lua; const util = @import("util.zig"); const sqlite = @import("sqlite.zig").sqlite; const magick_wand = @import("magick_wand.zig").magick_wand; const base16 = @import("base16.zig").standard_base16; pub const DatabaseError = error{ Open, Prepare, Bind, Query, HashCheck }; pub const ByteCodeError = error{ Load, Execute, InvalidReturn }; pub const EngineError = DatabaseError || ByteCodeError || Allocator.Error; pub const EngineMajor = 0; pub const EngineMinor = 1; pub const Engine = struct { allocator: Allocator, db: ?*sqlite.sqlite3, database_path: []const u8, L: ?*lua.lua_State, pub fn init(allocator: Allocator, database_path: anytype) EngineError!Engine { var db: ?*sqlite.sqlite3 = undefined; errdefer _ = sqlite.sqlite3_close(db); const result = try allocator.dupeZ(u8, database_path[0..database_path.len]); errdefer allocator.free(result); var rc = sqlite.sqlite3_open(result.ptr, &db); if (rc != sqlite.SQLITE_OK) { _ = sqlite.sqlite3_close(db); std.log.err("rc={d} {s}", .{ rc, sqlite.sqlite3_errstr(rc) }); return DatabaseError.Open; } var L = lua.luaL_newstate(); errdefer lua.lua_close(L); util.init(L, db); return Engine{ .allocator = allocator, .db = db, .database_path = result, .L = L }; } pub fn deinit(self: *const Engine) void { _ = sqlite.sqlite3_close(self.db); _ = lua.lua_close(self.L); self.allocator.free(self.database_path); } pub fn getByteCodeError(self: *const Engine, _: EngineError) ![]u8 { const string = try std.fmt.allocPrint(self.allocator, "{s}", .{lua.lua_tolstring(self.L, -1, null)}); errdefer self.allocator.free(string); return string; } pub fn freeByteCodeError(self: *const Engine, s: anytype) void { self.allocator.free(s); } pub fn loadCard(self: *const Engine, id: anytype) EngineError!Card { var res: ?*sqlite.sqlite3_stmt = undefined; defer _ = sqlite.sqlite3_finalize(res); var rc = sqlite.sqlite3_prepare_v2(self.db, "SELECT id,hash FROM 'cards' WHERE id=$1", -1, &res, 0); if (rc != sqlite.SQLITE_OK) return DatabaseError.Prepare; rc = sqlite.sqlite3_bind_text(res, 1, id, @intCast(c_int, id.len), null); if (rc != sqlite.SQLITE_OK) return DatabaseError.Query; rc = sqlite.sqlite3_step(res); if (rc == sqlite.SQLITE_ROW) { const got_id_length = sqlite.sqlite3_column_bytes(res, 0); const got_id = sqlite.sqlite3_column_text(res, 0); const hash_length = sqlite.sqlite3_column_bytes(res, 1); const hash = sqlite.sqlite3_column_text(res, 1); try util.validateHash(self, got_id[0..@intCast(usize, got_id_length)], hash[0..@intCast(usize, hash_length)]); const result = try self.allocator.dupe(u8, got_id[0..@intCast(usize, got_id_length)]); errdefer self.allocator.free(result); return Card.init(self.allocator, result); } else return DatabaseError.Query; } pub fn loadByteCode(self: *const Engine, card: *Card) EngineError!void { var res: ?*sqlite.sqlite3_stmt = undefined; defer _ = sqlite.sqlite3_finalize(res); var rc = sqlite.sqlite3_prepare_v2(self.db, "SELECT data FROM 'card_blocks' WHERE card_id=$1 AND name='card.lua'", -1, &res, 0); if (rc != sqlite.SQLITE_OK) return DatabaseError.Prepare; rc = sqlite.sqlite3_bind_text(res, 1, card.id.ptr, @intCast(c_int, card.id.len), null); if (rc != sqlite.SQLITE_OK) return DatabaseError.Bind; rc = sqlite.sqlite3_step(res); if (rc == sqlite.SQLITE_ROW) { const block = sqlite.sqlite3_column_text(res, 0); const length = sqlite.sqlite3_column_bytes(res, 0); const load_status = lua.luaL_loadbufferx(self.L, block, @intCast(usize, length), "card.lua", "bt"); if (load_status != lua.LUA_OK) return ByteCodeError.Load; var binary_hash: [32]u8 = undefined; var encoded_hash: [64]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(block[0..@intCast(usize, length)], &binary_hash, .{}); base16.encode(&encoded_hash, &binary_hash); const result = try self.allocator.dupe(u8, &encoded_hash); errdefer self.allocator.free(result); card.hash = result; } else return DatabaseError.Query; } pub fn executeByteCode(self: *const Engine, card: *Card) EngineError!void { const call_status = lua.lua_pcallk(self.L, 0, lua.LUA_MULTRET, 0, 0, null); if (call_status != lua.LUA_OK) return ByteCodeError.Execute; try util.checkReturn(self); card.version_major = try util.checkVersionMajor(self); card.version_minor = try util.checkversionMinor(self); card.body = try util.getString(self, CardSchema.Body); card.primary_title = try util.getString(self, CardSchema.PrimaryTitle); card.sub_title = try util.getString(self, CardSchema.SubTitle); } pub fn render(self: *const Engine, card: *Card) EngineError!void { magick_wand.MagickWandGenesis(); defer magick_wand.MagickWandTerminus(); var wand = magick_wand.NewMagickWand(); defer _ = magick_wand.DestroyMagickWand(wand); _ = magick_wand.MagickSetImageAlphaChannel(wand, magick_wand.ActivateAlphaChannel); var pixel_wand = magick_wand.NewPixelWand(); defer _ = magick_wand.DestroyPixelWand(pixel_wand); _ = magick_wand.PixelSetColor(pixel_wand, "rgb(255,255,255)"); _ = magick_wand.PixelSetAlpha(pixel_wand, 0.0); _ = magick_wand.MagickSetImageBackgroundColor(wand, pixel_wand); _ = magick_wand.MagickNewImage(wand, 750, 1050, pixel_wand); _ = magick_wand.MagickTransparentPaintImage(wand, pixel_wand, 0.0, 10, magick_wand.MagickFalse); var draw_wand = magick_wand.NewDrawingWand(); defer _ = magick_wand.DestroyDrawingWand(draw_wand); _ = magick_wand.PixelSetAlpha(pixel_wand, 1.0); _ = magick_wand.PixelSetColor(pixel_wand, "rgb(66, 66, 84)"); _ = magick_wand.DrawSetFillColor(draw_wand, pixel_wand); _ = magick_wand.DrawRoundRectangle( draw_wand, 0, 0, 750, 1050, 40, 40, ); _ = magick_wand.MagickDrawImage(wand, draw_wand); // write title text if (card.primary_title) |primary_title| { _ = magick_wand.PixelSetColor(pixel_wand, "white"); _ = magick_wand.DrawSetFillColor(draw_wand, pixel_wand); _ = magick_wand.DrawSetFont(draw_wand, "Verdana-Bold-Italic"); _ = magick_wand.DrawSetFontSize(draw_wand, 72); _ = magick_wand.DrawSetTextAntialias(draw_wand, magick_wand.MagickTrue); _ = magick_wand.DrawAnnotation(draw_wand, 25, 65, primary_title.ptr); _ = magick_wand.MagickDrawImage(wand, draw_wand); } // write subtitle text if (card.sub_title) |sub_title| { _ = magick_wand.PixelSetColor(pixel_wand, "white"); _ = magick_wand.DrawSetFillColor(draw_wand, pixel_wand); _ = magick_wand.DrawSetFont(draw_wand, "Verdana-Bold-Italic"); _ = magick_wand.DrawSetFontSize(draw_wand, 30); _ = magick_wand.DrawSetTextAntialias(draw_wand, magick_wand.MagickTrue); _ = magick_wand.DrawAnnotation(draw_wand, 470, 635, sub_title.ptr); _ = magick_wand.MagickDrawImage(wand, draw_wand); } // write body text if (card.body) |body| { _ = magick_wand.PixelSetColor(pixel_wand, "white"); _ = magick_wand.DrawSetFillColor(draw_wand, pixel_wand); _ = magick_wand.DrawSetFont(draw_wand, "Verdana-Bold-Italic"); _ = magick_wand.DrawSetFontSize(draw_wand, 35); _ = magick_wand.DrawSetTextAntialias(draw_wand, magick_wand.MagickTrue); _ = magick_wand.DrawAnnotation(draw_wand, 220, 700, body.ptr); _ = magick_wand.MagickDrawImage(wand, draw_wand); } // write serial number _ = magick_wand.PixelSetColor(pixel_wand, "white"); _ = magick_wand.PixelSetAlpha(pixel_wand, 0.3); _ = magick_wand.DrawSetFillColor(draw_wand, pixel_wand); _ = magick_wand.DrawSetFont(draw_wand, "Verdana-Bold-Italic"); _ = magick_wand.DrawSetFontSize(draw_wand, 12); _ = magick_wand.DrawSetTextAntialias(draw_wand, magick_wand.MagickTrue); _ = magick_wand.DrawAnnotation(draw_wand, 430, 1045, card.id.ptr); _ = magick_wand.MagickDrawImage(wand, draw_wand); // overlay photo const photo = try util.getImage(self, CardSchema.Photo); defer photo.deinit(); _ = magick_wand.MagickResizeImage(photo.wand, 660, 500, magick_wand.BesselFilter); _ = magick_wand.MagickCompositeImage(wand, photo.wand, magick_wand.OverCompositeOp, magick_wand.MagickTrue, 40, 100); // overlay icon const icon = try util.getImage(self, CardSchema.Icon); defer icon.deinit(); _ = magick_wand.MagickCompositeImage(wand, icon.wand, magick_wand.OverCompositeOp, magick_wand.MagickTrue, 40, 540); // end _ = magick_wand.MagickWriteImages(wand, "output.png", magick_wand.MagickTrue); } };
engine/src/engine.zig
const Self = @This(); const std = @import("std"); const mem = std.mem; const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const Box = @import("Box.zig"); const Seat = @import("Seat.zig"); const Subsurface = @import("Subsurface.zig"); const View = @import("View.zig"); const ViewStack = @import("view_stack.zig").ViewStack; const XdgPopup = @import("XdgPopup.zig"); const log = std.log.scoped(.xdg_shell); /// The view this xdg toplevel implements view: *View, /// The corresponding wlroots object xdg_surface: *wlr.XdgSurface, /// Set to true when the client acks the configure with serial View.pending_serial. acked_pending_serial: bool = false, // Listeners that are always active over the view's lifetime destroy: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(handleDestroy), map: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(handleMap), unmap: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(handleUnmap), new_popup: wl.Listener(*wlr.XdgPopup) = wl.Listener(*wlr.XdgPopup).init(handleNewPopup), new_subsurface: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleNewSubsurface), // Listeners that are only active while the view is mapped ack_configure: wl.Listener(*wlr.XdgSurface.Configure) = wl.Listener(*wlr.XdgSurface.Configure).init(handleAckConfigure), commit: wl.Listener(*wlr.Surface) = wl.Listener(*wlr.Surface).init(handleCommit), request_fullscreen: wl.Listener(*wlr.XdgToplevel.event.SetFullscreen) = wl.Listener(*wlr.XdgToplevel.event.SetFullscreen).init(handleRequestFullscreen), request_move: wl.Listener(*wlr.XdgToplevel.event.Move) = wl.Listener(*wlr.XdgToplevel.event.Move).init(handleRequestMove), request_resize: wl.Listener(*wlr.XdgToplevel.event.Resize) = wl.Listener(*wlr.XdgToplevel.event.Resize).init(handleRequestResize), set_title: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(handleSetTitle), set_app_id: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(handleSetAppId), pub fn init(self: *Self, view: *View, xdg_surface: *wlr.XdgSurface) void { self.* = .{ .view = view, .xdg_surface = xdg_surface }; xdg_surface.data = @ptrToInt(self); // Add listeners that are active over the view's entire lifetime xdg_surface.events.destroy.add(&self.destroy); xdg_surface.events.map.add(&self.map); xdg_surface.events.unmap.add(&self.unmap); xdg_surface.events.new_popup.add(&self.new_popup); xdg_surface.surface.events.new_subsurface.add(&self.new_subsurface); Subsurface.handleExisting(xdg_surface.surface, .{ .xdg_toplevel = self }); } /// Returns true if a configure must be sent to ensure that the pending /// dimensions are applied. pub fn needsConfigure(self: Self) bool { const server_pending = &self.xdg_surface.role_data.toplevel.server_pending; const state = &self.view.pending; // Checking server_pending is sufficient here since it will be either in // sync with the current dimensions or be the dimensions sent with the // most recent configure. In both cases server_pending has the values we // want to check against. // Furthermore, we avoid a special case for newly mapped views which we // have not yet configured by setting server_pending.width/height to the // initial width/height of the view in handleMap(). return state.box.width != server_pending.width or state.box.height != server_pending.height; } /// Send a configure event, applying the pending state of the view. pub fn configure(self: *Self) void { const toplevel = self.xdg_surface.role_data.toplevel; const state = &self.view.pending; self.view.pending_serial = toplevel.setSize(state.box.width, state.box.height); self.acked_pending_serial = false; } /// Close the view. This will lead to the unmap and destroy events being sent pub fn close(self: Self) void { self.xdg_surface.role_data.toplevel.sendClose(); } pub fn setActivated(self: Self, activated: bool) void { _ = self.xdg_surface.role_data.toplevel.setActivated(activated); } pub fn setFullscreen(self: Self, fullscreen: bool) void { _ = self.xdg_surface.role_data.toplevel.setFullscreen(fullscreen); } pub fn setResizing(self: Self, resizing: bool) void { _ = self.xdg_surface.role_data.toplevel.setResizing(resizing); } /// Return the surface at output coordinates ox, oy and set sx, sy to the /// corresponding surface-relative coordinates, if there is a surface. pub fn surfaceAt(self: Self, ox: f64, oy: f64, sx: *f64, sy: *f64) ?*wlr.Surface { const view = self.view; return self.xdg_surface.surfaceAt( ox - @intToFloat(f64, view.current.box.x - view.surface_box.x), oy - @intToFloat(f64, view.current.box.y - view.surface_box.y), sx, sy, ); } /// Return the current title of the toplevel if any. pub fn getTitle(self: Self) ?[*:0]const u8 { return self.xdg_surface.role_data.toplevel.title; } /// Return the current app_id of the toplevel if any . pub fn getAppId(self: Self) ?[*:0]const u8 { return self.xdg_surface.role_data.toplevel.app_id; } /// Return bounds on the dimensions of the toplevel. pub fn getConstraints(self: Self) View.Constraints { const state = &self.xdg_surface.role_data.toplevel.current; return .{ .min_width = std.math.max(state.min_width, View.min_size), .max_width = if (state.max_width > 0) state.max_width else std.math.maxInt(u32), .min_height = std.math.max(state.min_height, View.min_size), .max_height = if (state.max_height > 0) state.max_height else std.math.maxInt(u32), }; } fn handleDestroy(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "destroy", listener); // Remove listeners that are active for the entire lifetime of the view self.destroy.link.remove(); self.map.link.remove(); self.unmap.link.remove(); self.new_popup.link.remove(); self.new_subsurface.link.remove(); Subsurface.destroySubsurfaces(self.xdg_surface.surface); XdgPopup.destroyPopups(self.xdg_surface); self.view.destroy(); } /// Called when the xdg surface is mapped, or ready to display on-screen. fn handleMap(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "map", listener); const view = self.view; const toplevel = self.xdg_surface.role_data.toplevel; // Add listeners that are only active while mapped self.xdg_surface.events.ack_configure.add(&self.ack_configure); self.xdg_surface.surface.events.commit.add(&self.commit); toplevel.events.request_fullscreen.add(&self.request_fullscreen); toplevel.events.request_move.add(&self.request_move); toplevel.events.request_resize.add(&self.request_resize); toplevel.events.set_title.add(&self.set_title); toplevel.events.set_app_id.add(&self.set_app_id); // Use the view's initial size centered on the output as the default // floating dimensions var initial_box: wlr.Box = undefined; self.xdg_surface.getGeometry(&initial_box); view.float_box.width = @intCast(u32, initial_box.width); view.float_box.height = @intCast(u32, initial_box.height); view.float_box.x = std.math.max(0, @divTrunc(@intCast(i32, view.output.usable_box.width) - @intCast(i32, view.float_box.width), 2)); view.float_box.y = std.math.max(0, @divTrunc(@intCast(i32, view.output.usable_box.height) - @intCast(i32, view.float_box.height), 2)); // We initialize these to avoid special-casing newly mapped views in // the check preformed in needsConfigure(). toplevel.server_pending.width = @intCast(u32, initial_box.width); toplevel.server_pending.height = @intCast(u32, initial_box.height); view.surface = self.xdg_surface.surface; view.surface_box = Box.fromWlrBox(initial_box); // Also use the view's "natural" size as the initial regular dimensions, // for the case that it does not get arranged by a lyaout. view.pending.box = view.float_box; const state = &toplevel.current; const has_fixed_size = state.min_width != 0 and state.min_height != 0 and (state.min_width == state.max_width or state.min_height == state.max_height); if (toplevel.parent != null or has_fixed_size) { // If the toplevel has a parent or has a fixed size make it float view.current.float = true; view.pending.float = true; view.pending.box = view.float_box; } else if (server.config.shouldFloat(view)) { view.current.float = true; view.pending.float = true; view.pending.box = view.float_box; } // If the view has an app_id or title which is not configured to use client // side decorations, inform it that it is tiled. if (server.config.csdAllowed(view)) { view.draw_borders = false; } else { _ = toplevel.setTiled(.{ .top = true, .bottom = true, .left = true, .right = true }); } view.map() catch { log.crit("out of memory", .{}); xdg_surface.resource.getClient().postNoMemory(); }; } /// Called when the surface is unmapped and will no longer be displayed. fn handleUnmap(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "unmap", listener); // Remove listeners that are only active while mapped self.ack_configure.link.remove(); self.commit.link.remove(); self.request_fullscreen.link.remove(); self.request_move.link.remove(); self.request_resize.link.remove(); self.set_title.link.remove(); self.set_app_id.link.remove(); self.view.unmap(); } fn handleAckConfigure( listener: *wl.Listener(*wlr.XdgSurface.Configure), acked_configure: *wlr.XdgSurface.Configure, ) void { const self = @fieldParentPtr(Self, "ack_configure", listener); if (self.view.pending_serial) |serial| { if (serial == acked_configure.serial) { self.acked_pending_serial = true; } } } fn handleCommit(listener: *wl.Listener(*wlr.Surface), surface: *wlr.Surface) void { const self = @fieldParentPtr(Self, "commit", listener); const view = self.view; var wlr_box: wlr.Box = undefined; self.xdg_surface.getGeometry(&wlr_box); const new_box = Box.fromWlrBox(wlr_box); // If we have sent a configure changing the size if (view.pending_serial != null) { // Update the stored dimensions of the surface view.surface_box = new_box; if (self.acked_pending_serial) { // If this commit is in response to our configure and the // transaction code is tracking this configure, notify it. // Otherwise, apply the pending state immediately. view.pending_serial = null; if (view.shouldTrackConfigure()) { server.root.notifyConfigured(); } else { const self_tags_changed = view.pending.tags != view.current.tags; const urgent_tags_dirty = view.pending.urgent != view.current.urgent or (view.pending.urgent and self_tags_changed); view.current = view.pending; if (self_tags_changed) view.output.sendViewTags(); if (urgent_tags_dirty) view.output.sendUrgentTags(); // This is necessary if this view was part of a transaction that didn't get completed // before some change occured that caused shouldTrackConfigure() to return false. view.dropSavedBuffers(); view.output.damage.addWhole(); server.input_manager.updateCursorState(); } } else { // If the client has not yet acked our configure, we need to send a // frame done event so that it commits another buffer. These // buffers won't be rendered since we are still rendering our // stashed buffer from when the transaction started. view.sendFrameDone(); } } else { view.output.damage.addWhole(); const size_changed = !std.meta.eql(view.surface_box, new_box); view.surface_box = new_box; // If the client has decided to resize itself and the view is floating, // then respect that resize. if ((self.view.pending.float or self.view.output.pending.layout == null) and size_changed) { view.pending.box.width = new_box.width; view.pending.box.height = new_box.height; view.applyPending(); } } } fn handleNewPopup(listener: *wl.Listener(*wlr.XdgPopup), wlr_xdg_popup: *wlr.XdgPopup) void { const self = @fieldParentPtr(Self, "new_popup", listener); XdgPopup.create(wlr_xdg_popup, .{ .xdg_toplevel = self }); } fn handleNewSubsurface(listener: *wl.Listener(*wlr.Subsurface), new_wlr_subsurface: *wlr.Subsurface) void { const self = @fieldParentPtr(Self, "new_subsurface", listener); Subsurface.create(new_wlr_subsurface, .{ .xdg_toplevel = self }); } /// Called when the client asks to be fullscreened. We always honor the request /// for now, perhaps it should be denied in some cases in the future. fn handleRequestFullscreen( listener: *wl.Listener(*wlr.XdgToplevel.event.SetFullscreen), event: *wlr.XdgToplevel.event.SetFullscreen, ) void { const self = @fieldParentPtr(Self, "request_fullscreen", listener); self.view.pending.fullscreen = event.fullscreen; self.view.applyPending(); } /// Called when the client asks to be moved via the cursor, for example when the /// user drags CSD titlebars. fn handleRequestMove( listener: *wl.Listener(*wlr.XdgToplevel.event.Move), event: *wlr.XdgToplevel.event.Move, ) void { const self = @fieldParentPtr(Self, "request_move", listener); const seat = @intToPtr(*Seat, event.seat.seat.data); if ((self.view.pending.float or self.view.output.pending.layout == null) and !self.view.pending.fullscreen) seat.cursor.enterMode(.move, self.view); } /// Called when the client asks to be resized via the cursor. fn handleRequestResize(listener: *wl.Listener(*wlr.XdgToplevel.event.Resize), event: *wlr.XdgToplevel.event.Resize) void { const self = @fieldParentPtr(Self, "request_resize", listener); const seat = @intToPtr(*Seat, event.seat.seat.data); if ((self.view.pending.float or self.view.output.pending.layout == null) and !self.view.pending.fullscreen) seat.cursor.enterMode(.resize, self.view); } /// Called when the client sets / updates its title fn handleSetTitle(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "set_title", listener); self.view.notifyTitle(); } /// Called when the client sets / updates its app_id fn handleSetAppId(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "set_app_id", listener); self.view.notifyAppId(); }
source/river-0.1.0/river/XdgToplevel.zig
const std = @import("std"); const builtin = @import("builtin"); const vtable = @import("vtable.zig"); const testing = std.testing; const math = std.math; const debug = std.debug; const mem = @This(); const TypeInfo = builtin.TypeInfo; pub const AllocError = error{OutOfMemory}; pub const Allocator = struct { const VTable = struct { pub const Impl = @OpaqueType(); /// Allocate byte_count bytes and return them in a slice, with the /// slice's pointer aligned at least to alignment bytes. /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 alloc: fn (allocator: *Impl, byte_count: usize, alignment: u29) AllocError![]u8, /// If `new_byte_count > old_mem.len`: /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn. /// * alignment >= alignment of old_mem.ptr /// /// If `new_byte_count <= old_mem.len`: /// * this function must return successfully. /// * alignment <= alignment of old_mem.ptr /// /// When `reallocFn` returns, /// `return_value[0..min(old_mem.len, new_byte_count)]` must be the same /// as `old_mem` was when `reallocFn` is called. The bytes of /// `return_value[old_mem.len..]` have undefined values. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 realloc: fn (allocator: *Impl, old_mem: []u8, new_byte_count: usize, alignment: u29) AllocError![]u8, /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn` free: fn (allocator: *Impl, old_mem: []u8) void, }; vtable: *const VTable, impl: *VTable.Impl, pub fn init(allocator: var) Allocator { const T = @TypeOf(allocator).Child; return Allocator{ .vtable = comptime vtable.populate(VTable, T, T), .impl = @ptrCast(*VTable.Impl, allocator), }; } pub fn alloc(allocator: Allocator, n: usize, alignment: u29) AllocError![]u8 { return allocator.vtable.alloc(allocator.impl, n, alignment); } pub fn realloc(allocator: Allocator, old_mem: []u8, new_size: usize, alignment: u29) AllocError![]u8 { return allocator.vtable.realloc(allocator.impl, old_mem, new_size, alignment); } pub fn free(allocator: Allocator, bytes: []u8) void { return allocator.vtable.free(allocator.impl, bytes); } }; test "mem.Allocator" { var buf: [1024]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; const allocator = Allocator.init(&fba); var t = try mem.alloc(allocator, u8, 10); testing.expectEqual(@as(usize, 10), t.len); testing.expectEqual(@as(usize, 10), fba.end_index); t = try mem.realloc(allocator, u8, t, 5); testing.expectEqual(@as(usize, 5), t.len); testing.expectEqual(@as(usize, 10), fba.end_index); t = try mem.realloc(allocator, u8, t, 20); testing.expectEqual(@as(usize, 20), t.len); testing.expectEqual(@as(usize, 30), fba.end_index); mem.free(allocator, t); testing.expectEqual(@as(usize, 20), t.len); testing.expectEqual(@as(usize, 30), fba.end_index); } pub const FixedBufferAllocator = struct { buffer: []u8, end_index: usize = 0, pub fn alloc(allocator: *FixedBufferAllocator, n: usize, alignment: u29) AllocError![]u8 { const addr = @ptrToInt(allocator.buffer.ptr) + allocator.end_index; const rem = @rem(addr, alignment); const march_forward_bytes = if (rem == 0) 0 else (alignment - rem); const adjusted_index = allocator.end_index + march_forward_bytes; const new_end_index = adjusted_index + n; if (new_end_index > allocator.buffer.len) return error.OutOfMemory; const result = allocator.buffer[adjusted_index..new_end_index]; allocator.end_index = new_end_index; return result; } pub fn realloc(allocator: *FixedBufferAllocator, old_mem: []u8, new_size: usize, alignment: u29) AllocError![]u8 { debug.assert(old_mem.len <= allocator.end_index); if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else if (old_mem.ptr == allocator.buffer.ptr + allocator.end_index - old_mem.len) { const start_index = allocator.end_index - old_mem.len; const new_end_index = start_index + new_size; if (new_end_index > allocator.buffer.len) return error.OutOfMemory; const result = allocator.buffer[start_index..new_end_index]; allocator.end_index = new_end_index; return result; } else { const result = try alloc(allocator, new_size, alignment); std.mem.copy(u8, result, old_mem); return result; } } pub fn free(allocator: *FixedBufferAllocator, bytes: []u8) void {} }; test "mem.FixedBufferAllocator" { var buf: [1024]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; var t = try fba.alloc(10, 1); testing.expectEqual(@as(usize, 10), t.len); testing.expectEqual(@as(usize, 10), fba.end_index); t = try fba.realloc(t, 5, 1); testing.expectEqual(@as(usize, 5), t.len); testing.expectEqual(@as(usize, 10), fba.end_index); t = try fba.realloc(t, 20, 1); testing.expectEqual(@as(usize, 20), t.len); testing.expectEqual(@as(usize, 30), fba.end_index); fba.free(t); testing.expectEqual(@as(usize, 20), t.len); testing.expectEqual(@as(usize, 30), fba.end_index); } pub fn create(allocator: var, init: var) AllocError!*@TypeOf(init) { const T = @TypeOf(init); if (@sizeOf(T) == 0) return &(T{}); const slice = try mem.alloc(allocator, T, 1); slice[0] = init; return &slice[0]; } test "mem.create" { var buf: [@sizeOf(u16)]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; testing.expectEqual(@as(u16, 99), (try mem.create(&fba, @as(u16, 99))).*); testing.expectError(AllocError.OutOfMemory, mem.create(&fba, @as(u16, 100))); } pub fn alloc(allocator: var, comptime T: type, n: usize) AllocError![]T { return mem.alignedAlloc(allocator, T, @alignOf(T), n); } test "mem.alloc" { var buf: [@sizeOf(u16) * 4]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; const t = try mem.alloc(&fba, u16, 4); testing.expectEqual(@as(usize, 4), t.len); testing.expectError(AllocError.OutOfMemory, mem.alloc(&fba, u8, 1)); } pub fn alignedAlloc(allocator: var, comptime T: type, comptime alignment: u29, n: usize) AllocError![]align(alignment) T { if (n == 0) return &[_]T{}; const byte_count = math.mul(usize, @sizeOf(T), n) catch return AllocError.OutOfMemory; const byte_slice = try allocator.alloc(byte_count, alignment); debug.assert(byte_slice.len == byte_count); // This loop gets optimized out in ReleaseFast mode for (byte_slice) |*byte| byte.* = undefined; return std.mem.bytesAsSlice(T, @alignCast(alignment, byte_slice)); } pub fn realloc(allocator: var, comptime T: type, old_mem: []T, n: usize) AllocError![]T { return mem.alignedRealloc(allocator, T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } test "mem.realloc" { var buf: [@sizeOf(u16) * 4]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; var t = try mem.alloc(&fba, u8, 4); testing.expectEqual(@as(usize, 4), t.len); t = try mem.realloc(&fba, u8, t, 2); testing.expectEqual(@as(usize, 2), t.len); testing.expectError(AllocError.OutOfMemory, mem.realloc(&fba, u8, t, 5)); } pub fn alignedRealloc(allocator: var, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) AllocError![]align(alignment) T { if (old_mem.len == 0) return mem.alignedAlloc(allocator, T, alignment, n); if (n == 0) { mem.free(allocator, old_mem); return &[_]T{}; } const old_byte_slice = std.mem.sliceAsBytes(old_mem); const byte_count = math.mul(usize, @sizeOf(T), n) catch return AllocError.OutOfMemory; const byte_slice = try allocator.realloc(old_byte_slice, byte_count, alignment); debug.assert(byte_slice.len == byte_count); if (n > old_mem.len) { // This loop gets optimized out in ReleaseFast mode for (byte_slice[old_byte_slice.len..]) |*byte| byte.* = undefined; } return std.mem.bytesAsSlice(T, @alignCast(alignment, byte_slice)); } /// Reallocate, but `n` must be less than or equal to `old_mem.len`. /// Unlike `realloc`, this function cannot fail. /// Shrinking to 0 is the same as calling `free`. pub fn shrink(allocator: var, comptime T: type, old_mem: []T, n: usize) []T { return mem.alignedShrink(allocator, T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } test "mem.shrink" { var buf: [@sizeOf(u16) * 4]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; var t = try mem.alloc(&fba, u16, 4); testing.expectEqual(@as(usize, 4), t.len); t = mem.shrink(&fba, u16, t, 2); testing.expectEqual(@as(usize, 2), t.len); } pub fn alignedShrink(allocator: var, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T { if (n == 0) { mem.free(allocator, old_mem); return old_mem[0..0]; } debug.assert(n <= old_mem.len); // Here we skip the overflow checking on the multiplication because // n <= old_mem.len and the multiplication didn't overflow for that operation. const byte_count = @sizeOf(T) * n; const byte_slice = allocator.realloc(std.mem.sliceAsBytes(old_mem), byte_count, alignment) catch unreachable; debug.assert(byte_slice.len == byte_count); return std.mem.bytesAsSlice(T, @alignCast(alignment, byte_slice)); } pub fn free(allocator: var, memory: var) void { const bytes = std.mem.sliceAsBytes(memory); if (bytes.len == 0) return; const non_const_ptr = @ptrCast([*]u8, bytes.ptr); allocator.free(non_const_ptr[0..bytes.len]); } test "mem.free" { var buf: [@sizeOf(u16) * 4]u8 = undefined; var fba = FixedBufferAllocator{ .buffer = buf[0..] }; var t = try mem.alloc(&fba, u16, 4); testing.expectEqual(@as(usize, 4), t.len); mem.free(&fba, t); }
src/mem.zig
const std = @import("std"); const gen2 = @import("../../gen2/data.zig"); const assert = std.debug.assert; const Type = gen2.Type; pub const Move = enum(u8) { None, Pound, KarateChop, DoubleSlap, CometPunch, MegaPunch, PayDay, FirePunch, IcePunch, ThunderPunch, Scratch, ViseGrip, Guillotine, RazorWind, SwordsDance, Cut, Gust, WingAttack, Whirlwind, Fly, Bind, Slam, VineWhip, Stomp, DoubleKick, MegaKick, JumpKick, RollingKick, SandAttack, Headbutt, HornAttack, FuryAttack, HornDrill, Tackle, BodySlam, Wrap, TakeDown, Thrash, DoubleEdge, TailWhip, PoisonSting, Twineedle, PinMissile, Leer, Bite, Growl, Roar, Sing, Supersonic, SonicBoom, Disable, Acid, Ember, Flamethrower, Mist, WaterGun, HydroPump, Surf, IceBeam, Blizzard, Psybeam, BubbleBeam, AuroraBeam, HyperBeam, Peck, DrillPeck, Submission, LowKick, Counter, SeismicToss, Strength, Absorb, MegaDrain, LeechSeed, Growth, RazorLeaf, SolarBeam, PoisonPowder, StunSpore, SleepPowder, PetalDance, StringShot, DragonRage, FireSpin, ThunderShock, Thunderbolt, ThunderWave, Thunder, RockThrow, Earthquake, Fissure, Dig, Toxic, Confusion, Psychic, Hypnosis, Meditate, Agility, QuickAttack, Rage, Teleport, NightShade, Mimic, Screech, DoubleTeam, Recover, Harden, Minimize, Smokescreen, ConfuseRay, Withdraw, DefenseCurl, Barrier, LightScreen, Haze, Reflect, FocusEnergy, Bide, Metronome, MirrorMove, SelfDestruct, EggBomb, Lick, Smog, Sludge, BoneClub, FireBlast, Waterfall, Clamp, Swift, SkullBash, SpikeCannon, Constrict, Amnesia, Kinesis, SoftBoiled, HighJumpKick, Glare, DreamEater, PoisonGas, Barrage, LeechLife, LovelyKiss, SkyAttack, Transform, Bubble, DizzyPunch, Spore, Flash, Psywave, Splash, AcidArmor, Crabhammer, Explosion, FurySwipes, Bonemerang, Rest, RockSlide, HyperFang, Sharpen, Conversion, TriAttack, SuperFang, Slash, Substitute, Struggle, Sketch, TripleKick, Thief, SpiderWeb, MindReader, Nightmare, FlameWheel, Snore, Curse, Flail, Conversion2, Aeroblast, CottonSpore, Reversal, Spite, PowderSnow, Protect, MachPunch, ScaryFace, FeintAttack, SweetKiss, BellyDrum, SludgeBomb, MudSlap, Octazooka, Spikes, ZapCannon, Foresight, DestinyBond, PerishSong, IcyWind, Detect, BoneRush, LockOn, Outrage, Sandstorm, GigaDrain, Endure, Charm, Rollout, FalseSwipe, Swagger, MilkDrink, Spark, FuryCutter, SteelWing, MeanLook, Attract, SleepTalk, HealBell, Return, Present, Frustration, Safeguard, PainSplit, SacredFire, Magnitude, DynamicPunch, Megahorn, DragonBreath, BatonPass, Encore, Pursuit, RapidSpin, SweetScent, IronTail, MetalClaw, VitalThrow, MorningSun, Synthesis, Moonlight, HiddenPower, CrossChop, Twister, RainDance, SunnyDay, Crunch, MirrorCoat, PsychUp, ExtremeSpeed, AncientPower, ShadowBall, FutureSight, RockSmash, Whirlpool, BeatUp, pub const Data = packed struct { effect: Effect, bp: u8, type: Type, pp: u4, // pp / 5 acc: u4, // accuracy / 5 - 6 target: Target, chance: u4 = 0, // chance / 10 comptime { assert(@sizeOf(Data) == 5); } pub inline fn accuracy(self: Data) u8 { return (@as(u8, self.acc) + 6) * 5; } }; const DATA = [_]Data{ // Pound .{ .effect = .None, .bp = 40, .type = .Normal, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, }, // KarateChop .{ .effect = .HighCritical, .bp = 50, .type = .Fighting, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, }, // DoubleSlap .{ .effect = .MultiHit, .bp = 15, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 11, // 85% .target = .Other, }, // CometPunch .{ .effect = .MultiHit, .bp = 18, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 11, // 85% .target = .Other, }, // MegaPunch .{ .effect = .None, .bp = 80, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // PayDay .{ .effect = .PayDay, .bp = 40, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // FirePunch .{ .effect = .BurnChance, .bp = 75, .type = .Fire, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // IcePunch .{ .effect = .FreezeChance, .bp = 75, .type = .Ice, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // ThunderPunch .{ .effect = .ParalyzeChance, .bp = 75, .type = .Electric, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Scratch .{ .effect = .None, .bp = 40, .type = .Normal, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, }, // ViseGrip .{ .effect = .None, .bp = 55, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, }, // Guillotine .{ .effect = .OHKO, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 0, // 30% .target = .Other, }, // RazorWind .{ .effect = .RazorWind, .bp = 80, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 9, // 75% .target = .Foes, }, // SwordsDance .{ .effect = .AttackUp2, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // Cut .{ .effect = .None, .bp = 50, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 13, // 95% .target = .Other, }, // Gust .{ .effect = .Gust, .bp = 40, .type = .Flying, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, }, // WingAttack .{ .effect = .None, .bp = 60, .type = .Flying, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, }, // Whirlwind .{ .effect = .ForceSwitch, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Fly .{ .effect = .Fly, .bp = 70, .type = .Flying, .pp = 3, // * 5 = 15 .acc = 13, // 95% .target = .Other, }, // Bind .{ .effect = .Trapping, .bp = 15, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 9, // 75% .target = .Other, }, // Slam .{ .effect = .None, .bp = 80, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 9, // 75% .target = .Other, }, // VineWhip .{ .effect = .None, .bp = 35, .type = .Grass, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Stomp .{ .effect = .Stomp, .bp = 65, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // DoubleKick .{ .effect = .DoubleHit, .bp = 30, .type = .Fighting, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, }, // MegaKick .{ .effect = .None, .bp = 120, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 9, // 75% .target = .Other, }, // JumpKick .{ .effect = .JumpKick, .bp = 70, .type = .Fighting, .pp = 5, // * 5 = 25 .acc = 13, // 95% .target = .Other, }, // RollingKick .{ .effect = .FlinchChance, .bp = 60, .type = .Fighting, .pp = 3, // * 5 = 15 .acc = 11, // 85% .target = .Other, .chance = 3, // * 10 = 30 }, // SandAttack .{ .effect = .AccuracyDown1, .bp = 0, .type = .Ground, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Headbutt .{ .effect = .FlinchChance, .bp = 70, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // HornAttack .{ .effect = .None, .bp = 65, .type = .Normal, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, }, // FuryAttack .{ .effect = .MultiHit, .bp = 15, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // HornDrill .{ .effect = .OHKO, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 0, // 30% .target = .Other, }, // Tackle .{ .effect = .None, .bp = 35, .type = .Normal, .pp = 7, // * 5 = 35 .acc = 13, // 95% .target = .Other, }, // BodySlam .{ .effect = .ParalyzeChance, .bp = 85, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // Wrap .{ .effect = .Trapping, .bp = 15, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // TakeDown .{ .effect = .RecoilHit, .bp = 90, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // Thrash .{ .effect = .Thrashing, .bp = 90, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .RandomFoe, }, // DoubleEdge .{ .effect = .RecoilHit, .bp = 120, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // TailWhip .{ .effect = .DefenseDown1, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Foes, }, // PoisonSting .{ .effect = .PoisonChance, .bp = 15, .type = .Poison, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // Twineedle .{ .effect = .Twineedle, .bp = 25, .type = .Bug, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 2, // * 10 = 20 }, // PinMissile .{ .effect = .MultiHit, .bp = 14, .type = .Bug, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // Leer .{ .effect = .DefenseDown1, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Foes, }, // Bite .{ .effect = .FlinchChance, .bp = 60, .type = .Dark, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // Growl .{ .effect = .AttackDown1, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Foes, }, // Roar .{ .effect = .ForceSwitch, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Sing .{ .effect = .Sleep, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 5, // 55% .target = .Other, }, // Supersonic .{ .effect = .Confusion, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 5, // 55% .target = .Other, }, // SonicBoom .{ .effect = .StaticDamage, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 12, // 90% .target = .Other, }, // Disable .{ .effect = .Disable, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 5, // 55% .target = .Other, }, // Acid .{ .effect = .DefenseDownChance, .bp = 40, .type = .Poison, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Foes, .chance = 1, // * 10 = 10 }, // Ember .{ .effect = .BurnChance, .bp = 40, .type = .Fire, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Flamethrower .{ .effect = .BurnChance, .bp = 95, .type = .Fire, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Mist .{ .effect = .Mist, .bp = 0, .type = .Ice, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // WaterGun .{ .effect = .None, .bp = 40, .type = .Water, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, }, // HydroPump .{ .effect = .None, .bp = 120, .type = .Water, .pp = 1, // * 5 = 5 .acc = 10, // 80% .target = .Other, }, // Surf .{ .effect = .None, .bp = 95, .type = .Water, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Foes, }, // IceBeam .{ .effect = .FreezeChance, .bp = 95, .type = .Ice, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Blizzard .{ .effect = .FreezeChance, .bp = 120, .type = .Ice, .pp = 1, // * 5 = 5 .acc = 8, // 70% .target = .Foes, .chance = 1, // * 10 = 10 }, // Psybeam .{ .effect = .ConfusionChance, .bp = 65, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // BubbleBeam .{ .effect = .SpeedDownChance, .bp = 65, .type = .Water, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // AuroraBeam .{ .effect = .AttackDownChance, .bp = 65, .type = .Ice, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // HyperBeam .{ .effect = .HyperBeam, .bp = 150, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 12, // 90% .target = .Other, }, // Peck .{ .effect = .None, .bp = 35, .type = .Flying, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, }, // DrillPeck .{ .effect = .None, .bp = 80, .type = .Flying, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Submission .{ .effect = .RecoilHit, .bp = 80, .type = .Fighting, .pp = 5, // * 5 = 25 .acc = 10, // 80% .target = .Other, }, // LowKick .{ .effect = .FlinchChance, .bp = 50, .type = .Fighting, .pp = 4, // * 5 = 20 .acc = 12, // 90% .target = .Other, .chance = 3, // * 10 = 30 }, // Counter .{ .effect = .Counter, .bp = 0, .type = .Fighting, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Depends, }, // SeismicToss .{ .effect = .LevelDamage, .bp = 0, .type = .Fighting, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Strength .{ .effect = .None, .bp = 80, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Absorb .{ .effect = .DrainHP, .bp = 20, .type = .Grass, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // MegaDrain .{ .effect = .DrainHP, .bp = 40, .type = .Grass, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // LeechSeed .{ .effect = .LeechSeed, .bp = 0, .type = .Grass, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Other, }, // Growth .{ .effect = .SpAtkUp1, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // RazorLeaf .{ .effect = .HighCritical, .bp = 55, .type = .Grass, .pp = 5, // * 5 = 25 .acc = 13, // 95% .target = .Foes, }, // SolarBeam .{ .effect = .Solarbeam, .bp = 120, .type = .Grass, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // PoisonPowder .{ .effect = .Poison, .bp = 0, .type = .Poison, .pp = 7, // * 5 = 35 .acc = 9, // 75% .target = .Other, }, // StunSpore .{ .effect = .Paralyze, .bp = 0, .type = .Grass, .pp = 6, // * 5 = 30 .acc = 9, // 75% .target = .Other, }, // SleepPowder .{ .effect = .Sleep, .bp = 0, .type = .Grass, .pp = 3, // * 5 = 15 .acc = 9, // 75% .target = .Other, }, // PetalDance .{ .effect = .Thrashing, .bp = 70, .type = .Grass, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .RandomFoe, }, // StringShot .{ .effect = .SpeedDown1, .bp = 0, .type = .Bug, .pp = 8, // * 5 = 40 .acc = 13, // 95% .target = .Foes, }, // DragonRage .{ .effect = .StaticDamage, .bp = 0, .type = .Dragon, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // FireSpin .{ .effect = .Trapping, .bp = 15, .type = .Fire, .pp = 3, // * 5 = 15 .acc = 8, // 70% .target = .Other, }, // ThunderShock .{ .effect = .ParalyzeChance, .bp = 40, .type = .Electric, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Thunderbolt .{ .effect = .ParalyzeChance, .bp = 95, .type = .Electric, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // ThunderWave .{ .effect = .Paralyze, .bp = 0, .type = .Electric, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Thunder .{ .effect = .Thunder, .bp = 120, .type = .Electric, .pp = 2, // * 5 = 10 .acc = 8, // 70% .target = .Other, .chance = 3, // * 10 = 30 }, // RockThrow .{ .effect = .None, .bp = 50, .type = .Rock, .pp = 3, // * 5 = 15 .acc = 12, // 90% .target = .Other, }, // Earthquake .{ .effect = .Earthquake, .bp = 100, .type = .Ground, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .AllOthers, }, // Fissure .{ .effect = .OHKO, .bp = 0, .type = .Ground, .pp = 1, // * 5 = 5 .acc = 0, // 30% .target = .Other, }, // Dig .{ .effect = .Fly, .bp = 60, .type = .Ground, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Toxic .{ .effect = .Toxic, .bp = 0, .type = .Poison, .pp = 2, // * 5 = 10 .acc = 11, // 85% .target = .Other, }, // Confusion .{ .effect = .ConfusionChance, .bp = 50, .type = .Psychic, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Psychic .{ .effect = .SpDefDownChance, .bp = 90, .type = .Psychic, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Hypnosis .{ .effect = .Sleep, .bp = 0, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 6, // 60% .target = .Other, }, // Meditate .{ .effect = .AttackUp1, .bp = 0, .type = .Psychic, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // Agility .{ .effect = .SpeedUp2, .bp = 0, .type = .Psychic, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // QuickAttack .{ .effect = .Priority, .bp = 40, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, }, // Rage .{ .effect = .Rage, .bp = 20, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Teleport .{ .effect = .Teleport, .bp = 0, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Self, }, // NightShade .{ .effect = .LevelDamage, .bp = 0, .type = .Ghost, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Mimic .{ .effect = .Mimic, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Screech .{ .effect = .DefenseDown2, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 11, // 85% .target = .Other, }, // DoubleTeam .{ .effect = .EvasionUp1, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Self, }, // Recover .{ .effect = .Heal, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Self, }, // Harden .{ .effect = .DefenseUp1, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // Minimize .{ .effect = .EvasionUp1, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Self, }, // Smokescreen .{ .effect = .AccuracyDown1, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // ConfuseRay .{ .effect = .Confusion, .bp = 0, .type = .Ghost, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Withdraw .{ .effect = .DefenseUp1, .bp = 0, .type = .Water, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // DefenseCurl .{ .effect = .DefenseCurl, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // Barrier .{ .effect = .DefenseUp2, .bp = 0, .type = .Psychic, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // LightScreen .{ .effect = .LightScreen, .bp = 0, .type = .Psychic, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .AllySide, }, // Haze .{ .effect = .ResetStats, .bp = 0, .type = .Ice, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .All, }, // Reflect .{ .effect = .Reflect, .bp = 0, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .AllySide, }, // FocusEnergy .{ .effect = .FocusEnergy, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // Bide .{ .effect = .Bide, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // Metronome .{ .effect = .Metronome, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // MirrorMove .{ .effect = .MirrorMove, .bp = 0, .type = .Flying, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Self, }, // SelfDestruct .{ .effect = .Selfdestruct, .bp = 200, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .AllOthers, }, // EggBomb .{ .effect = .None, .bp = 100, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 9, // 75% .target = .Other, }, // Lick .{ .effect = .ParalyzeChance, .bp = 20, .type = .Ghost, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // Smog .{ .effect = .PoisonChance, .bp = 20, .type = .Poison, .pp = 4, // * 5 = 20 .acc = 8, // 70% .target = .Other, .chance = 4, // * 10 = 40 }, // Sludge .{ .effect = .PoisonChance, .bp = 65, .type = .Poison, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // BoneClub .{ .effect = .FlinchChance, .bp = 65, .type = .Ground, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, .chance = 1, // * 10 = 10 }, // FireBlast .{ .effect = .BurnChance, .bp = 120, .type = .Fire, .pp = 1, // * 5 = 5 .acc = 11, // 85% .target = .Other, .chance = 1, // * 10 = 10 }, // Waterfall .{ .effect = .None, .bp = 80, .type = .Water, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Clamp .{ .effect = .Trapping, .bp = 35, .type = .Water, .pp = 2, // * 5 = 10 .acc = 9, // 75% .target = .Other, }, // Swift .{ .effect = .AlwaysHit, .bp = 60, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Foes, }, // SkullBash .{ .effect = .SkullBash, .bp = 100, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // SpikeCannon .{ .effect = .MultiHit, .bp = 20, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Constrict .{ .effect = .SpeedDownChance, .bp = 10, .type = .Normal, .pp = 7, // * 5 = 35 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Amnesia .{ .effect = .SpDefUp2, .bp = 0, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Self, }, // Kinesis .{ .effect = .AccuracyDown1, .bp = 0, .type = .Psychic, .pp = 3, // * 5 = 15 .acc = 10, // 80% .target = .Other, }, // SoftBoiled .{ .effect = .Heal, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // HighJumpKick .{ .effect = .JumpKick, .bp = 85, .type = .Fighting, .pp = 4, // * 5 = 20 .acc = 12, // 90% .target = .Other, }, // Glare .{ .effect = .Paralyze, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 9, // 75% .target = .Other, }, // DreamEater .{ .effect = .DreamEater, .bp = 100, .type = .Psychic, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // PoisonGas .{ .effect = .Poison, .bp = 0, .type = .Poison, .pp = 8, // * 5 = 40 .acc = 5, // 55% .target = .Other, }, // Barrage .{ .effect = .MultiHit, .bp = 15, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 11, // 85% .target = .Other, }, // LeechLife .{ .effect = .DrainHP, .bp = 20, .type = .Bug, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // LovelyKiss .{ .effect = .Sleep, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 9, // 75% .target = .Other, }, // SkyAttack .{ .effect = .SkyAttack, .bp = 140, .type = .Flying, .pp = 1, // * 5 = 5 .acc = 12, // 90% .target = .Other, }, // Transform .{ .effect = .Transform, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Bubble .{ .effect = .SpeedDownChance, .bp = 20, .type = .Water, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Foes, .chance = 1, // * 10 = 10 }, // DizzyPunch .{ .effect = .ConfusionChance, .bp = 70, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 2, // * 10 = 20 }, // Spore .{ .effect = .Sleep, .bp = 0, .type = .Grass, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Flash .{ .effect = .AccuracyDown1, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 8, // 70% .target = .Other, }, // Psywave .{ .effect = .Psywave, .bp = 0, .type = .Psychic, .pp = 3, // * 5 = 15 .acc = 10, // 80% .target = .Other, }, // Splash .{ .effect = .Splash, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // AcidArmor .{ .effect = .DefenseUp2, .bp = 0, .type = .Poison, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // Crabhammer .{ .effect = .HighCritical, .bp = 90, .type = .Water, .pp = 2, // * 5 = 10 .acc = 11, // 85% .target = .Other, }, // Explosion .{ .effect = .Selfdestruct, .bp = 250, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .AllOthers, }, // FurySwipes .{ .effect = .MultiHit, .bp = 18, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 10, // 80% .target = .Other, }, // Bonemerang .{ .effect = .DoubleHit, .bp = 50, .type = .Ground, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Other, }, // Rest .{ .effect = .Heal, .bp = 0, .type = .Psychic, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // RockSlide .{ .effect = .FlinchChance, .bp = 75, .type = .Rock, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Foes, .chance = 3, // * 10 = 30 }, // HyperFang .{ .effect = .FlinchChance, .bp = 80, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 12, // 90% .target = .Other, .chance = 1, // * 10 = 10 }, // Sharpen .{ .effect = .AttackUp1, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // Conversion .{ .effect = .Conversion, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Self, }, // TriAttack .{ .effect = .TriAttack, .bp = 80, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 2, // * 10 = 20 }, // SuperFang .{ .effect = .SuperFang, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Other, }, // Slash .{ .effect = .HighCritical, .bp = 70, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Substitute .{ .effect = .Substitute, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // Struggle .{ .effect = .RecoilHit, .bp = 50, .type = .Normal, .pp = 0, // = 1 .acc = 14, // 100% .target = .RandomFoe, }, // Sketch .{ .effect = .Sketch, .bp = 0, .type = .Normal, .pp = 0, // = 1 .acc = 14, // 100% .target = .Other, }, // TripleKick .{ .effect = .TripleKick, .bp = 10, .type = .Fighting, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Other, }, // Thief .{ .effect = .Thief, .bp = 40, .type = .Dark, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 10, // * 10 = 100 }, // SpiderWeb .{ .effect = .MeanLook, .bp = 0, .type = .Bug, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // MindReader .{ .effect = .LockOn, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // Nightmare .{ .effect = .Nightmare, .bp = 0, .type = .Ghost, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // FlameWheel .{ .effect = .FlameWheel, .bp = 60, .type = .Fire, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // Snore .{ .effect = .Snore, .bp = 40, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // Curse .{ .effect = .Curse, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // Flail .{ .effect = .Reversal, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Conversion2 .{ .effect = .Conversion2, .bp = 0, .type = .Normal, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, }, // Aeroblast .{ .effect = .HighCritical, .bp = 100, .type = .Flying, .pp = 1, // * 5 = 5 .acc = 13, // 95% .target = .Other, }, // CottonSpore .{ .effect = .SpeedDown2, .bp = 0, .type = .Grass, .pp = 8, // * 5 = 40 .acc = 11, // 85% .target = .Other, }, // Reversal .{ .effect = .Reversal, .bp = 0, .type = .Fighting, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // Spite .{ .effect = .Spite, .bp = 0, .type = .Ghost, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // PowderSnow .{ .effect = .FreezeChance, .bp = 40, .type = .Ice, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .Foes, .chance = 1, // * 10 = 10 }, // Protect .{ .effect = .Protect, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // MachPunch .{ .effect = .Priority, .bp = 40, .type = .Fighting, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .Other, }, // ScaryFace .{ .effect = .SpeedDown2, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 12, // 90% .target = .Other, }, // FeintAttack .{ .effect = .AlwaysHit, .bp = 60, .type = .Dark, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // SweetKiss .{ .effect = .Confusion, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 9, // 75% .target = .Other, }, // BellyDrum .{ .effect = .BellyDrum, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // SludgeBomb .{ .effect = .PoisonChance, .bp = 90, .type = .Poison, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // MudSlap .{ .effect = .AccuracyDownChance, .bp = 20, .type = .Ground, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, .chance = 10, // * 10 = 100 }, // Octazooka .{ .effect = .AccuracyDownChance, .bp = 65, .type = .Water, .pp = 2, // * 5 = 10 .acc = 11, // 85% .target = .Other, .chance = 5, // * 10 = 50 }, // Spikes .{ .effect = .Spikes, .bp = 0, .type = .Ground, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .FoeSide, }, // ZapCannon .{ .effect = .ParalyzeChance, .bp = 100, .type = .Electric, .pp = 1, // * 5 = 5 .acc = 4, // 50% .target = .Other, .chance = 10, // * 10 = 100 }, // Foresight .{ .effect = .Foresight, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Other, }, // DestinyBond .{ .effect = .DestinyBond, .bp = 0, .type = .Ghost, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // PerishSong .{ .effect = .PerishSong, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .All, }, // IcyWind .{ .effect = .SpeedDownChance, .bp = 55, .type = .Ice, .pp = 3, // * 5 = 15 .acc = 13, // 95% .target = .Foes, .chance = 10, // * 10 = 100 }, // Detect .{ .effect = .Protect, .bp = 0, .type = .Fighting, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // BoneRush .{ .effect = .MultiHit, .bp = 25, .type = .Ground, .pp = 2, // * 5 = 10 .acc = 10, // 80% .target = .Other, }, // LockOn .{ .effect = .LockOn, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // Outrage .{ .effect = .Thrashing, .bp = 90, .type = .Dragon, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .RandomFoe, }, // Sandstorm .{ .effect = .Sandstorm, .bp = 0, .type = .Rock, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .All, }, // GigaDrain .{ .effect = .DrainHP, .bp = 60, .type = .Grass, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // Endure .{ .effect = .Endure, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // Charm .{ .effect = .AttackDown2, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Rollout .{ .effect = .Rollout, .bp = 30, .type = .Rock, .pp = 4, // * 5 = 20 .acc = 12, // 90% .target = .Other, }, // FalseSwipe .{ .effect = .FalseSwipe, .bp = 40, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Other, }, // Swagger .{ .effect = .Swagger, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 12, // 90% .target = .Other, }, // MilkDrink .{ .effect = .Heal, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // Spark .{ .effect = .ParalyzeChance, .bp = 65, .type = .Electric, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // FuryCutter .{ .effect = .FuryCutter, .bp = 10, .type = .Bug, .pp = 4, // * 5 = 20 .acc = 13, // 95% .target = .Other, }, // SteelWing .{ .effect = .DefenseUpChance, .bp = 70, .type = .Steel, .pp = 5, // * 5 = 25 .acc = 12, // 90% .target = .Other, .chance = 1, // * 10 = 10 }, // MeanLook .{ .effect = .MeanLook, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // Attract .{ .effect = .Attract, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // SleepTalk .{ .effect = .SleepTalk, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Self, }, // HealBell .{ .effect = .HealBell, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // Return .{ .effect = .Return, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Present .{ .effect = .Present, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 12, // 90% .target = .Other, }, // Frustration .{ .effect = .Frustration, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // Safeguard .{ .effect = .Safeguard, .bp = 0, .type = .Normal, .pp = 5, // * 5 = 25 .acc = 14, // 100% .target = .AllySide, }, // PainSplit .{ .effect = .PainSplit, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // SacredFire .{ .effect = .SacredFire, .bp = 100, .type = .Fire, .pp = 1, // * 5 = 5 .acc = 13, // 95% .target = .Other, .chance = 5, // * 10 = 50 }, // Magnitude .{ .effect = .Magnitude, .bp = 0, .type = .Ground, .pp = 6, // * 5 = 30 .acc = 14, // 100% .target = .AllOthers, }, // DynamicPunch .{ .effect = .ConfusionChance, .bp = 100, .type = .Fighting, .pp = 1, // * 5 = 5 .acc = 4, // 50% .target = .Other, .chance = 10, // * 10 = 100 }, // Megahorn .{ .effect = .None, .bp = 120, .type = .Bug, .pp = 2, // * 5 = 10 .acc = 11, // 85% .target = .Other, }, // DragonBreath .{ .effect = .ParalyzeChance, .bp = 60, .type = .Dragon, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, .chance = 3, // * 10 = 30 }, // BatonPass .{ .effect = .BatonPass, .bp = 0, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Self, }, // Encore .{ .effect = .Encore, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // Pursuit .{ .effect = .Pursuit, .bp = 40, .type = .Dark, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Other, }, // RapidSpin .{ .effect = .RapidSpin, .bp = 20, .type = .Normal, .pp = 8, // * 5 = 40 .acc = 14, // 100% .target = .Other, }, // SweetScent .{ .effect = .EvasionDown1, .bp = 0, .type = .Normal, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Foes, }, // IronTail .{ .effect = .DefenseDownChance, .bp = 100, .type = .Steel, .pp = 3, // * 5 = 15 .acc = 9, // 75% .target = .Other, .chance = 3, // * 10 = 30 }, // MetalClaw .{ .effect = .AttackDownChance, .bp = 50, .type = .Steel, .pp = 7, // * 5 = 35 .acc = 13, // 95% .target = .Other, .chance = 1, // * 10 = 10 }, // VitalThrow .{ .effect = .AlwaysHit, .bp = 70, .type = .Fighting, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // MorningSun .{ .effect = .MorningSun, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // Synthesis .{ .effect = .Synthesis, .bp = 0, .type = .Grass, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // Moonlight .{ .effect = .Moonlight, .bp = 0, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Self, }, // HiddenPower .{ .effect = .HiddenPower, .bp = 0, .type = .Normal, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, }, // CrossChop .{ .effect = .HighCritical, .bp = 100, .type = .Fighting, .pp = 1, // * 5 = 5 .acc = 10, // 80% .target = .Other, }, // Twister .{ .effect = .Twister, .bp = 40, .type = .Dragon, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Foes, .chance = 2, // * 10 = 20 }, // RainDance .{ .effect = .RainDance, .bp = 0, .type = .Water, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .All, }, // SunnyDay .{ .effect = .SunnyDay, .bp = 0, .type = .Fire, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .All, }, // Crunch .{ .effect = .SpDefDownChance, .bp = 80, .type = .Dark, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 2, // * 10 = 20 }, // MirrorCoat .{ .effect = .MirrorCoat, .bp = 0, .type = .Psychic, .pp = 4, // * 5 = 20 .acc = 14, // 100% .target = .Depends, }, // PsychUp .{ .effect = .PsychUp, .bp = 0, .type = .Normal, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, // ExtremeSpeed .{ .effect = .Priority, .bp = 80, .type = .Normal, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, }, // AncientPower .{ .effect = .BoostAllChance, .bp = 60, .type = .Rock, .pp = 1, // * 5 = 5 .acc = 14, // 100% .target = .Other, .chance = 1, // * 10 = 10 }, // ShadowBall .{ .effect = .SpDefDownChance, .bp = 80, .type = .Ghost, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 2, // * 10 = 20 }, // FutureSight .{ .effect = .FutureSight, .bp = 80, .type = .Psychic, .pp = 3, // * 5 = 15 .acc = 12, // 90% .target = .Other, }, // RockSmash .{ .effect = .DefenseDownChance, .bp = 20, .type = .Fighting, .pp = 3, // * 5 = 15 .acc = 14, // 100% .target = .Other, .chance = 5, // * 10 = 50 }, // Whirlpool .{ .effect = .Trapping, .bp = 15, .type = .Water, .pp = 3, // * 5 = 15 .acc = 8, // 70% .target = .Other, }, // BeatUp .{ .effect = .BeatUp, .bp = 10, .type = .Dark, .pp = 2, // * 5 = 10 .acc = 14, // 100% .target = .Other, }, }; pub const Effect = enum(u8) { None, AccuracyDown1, AccuracyDownChance, AlwaysHit, AttackDown1, AttackDown2, AttackDownChance, AttackUp1, AttackUp2, Attract, BatonPass, BeatUp, BellyDrum, Bide, BoostAllChance, BurnChance, Confusion, ConfusionChance, Conversion, Conversion2, Counter, Curse, DefenseCurl, DefenseDown1, DefenseDown2, DefenseDownChance, DefenseUp1, DefenseUp2, DefenseUpChance, DestinyBond, Disable, DoubleHit, DrainHP, DreamEater, Earthquake, Encore, Endure, EvasionDown1, EvasionUp1, FalseSwipe, FlameWheel, FlinchChance, Fly, FocusEnergy, ForceSwitch, Foresight, FreezeChance, Frustration, FuryCutter, FutureSight, Gust, Heal, HealBell, HiddenPower, HighCritical, HyperBeam, JumpKick, LeechSeed, LevelDamage, LightScreen, LockOn, Magnitude, MeanLook, Metronome, Mimic, MirrorCoat, MirrorMove, Mist, Moonlight, MorningSun, MultiHit, Nightmare, OHKO, PainSplit, Paralyze, ParalyzeChance, PayDay, PerishSong, Poison, PoisonChance, Present, Priority, Protect, PsychUp, Psywave, Pursuit, Rage, RainDance, RapidSpin, RazorWind, RecoilHit, Reflect, ResetStats, Return, Reversal, Rollout, SacredFire, Safeguard, Sandstorm, Selfdestruct, Sketch, SkullBash, SkyAttack, Sleep, SleepTalk, Snore, Solarbeam, SpAtkUp1, SpDefDownChance, SpDefUp2, SpeedDown1, SpeedDown2, SpeedDownChance, SpeedUp2, Spikes, Spite, Splash, StaticDamage, Stomp, Substitute, SunnyDay, SuperFang, Swagger, Synthesis, Teleport, Thief, Thrashing, Thunder, Toxic, Transform, Trapping, TriAttack, TripleKick, Twineedle, Twister, comptime { assert(@sizeOf(Effect) == 1); } }; const Target = enum(u4) { // none All, AllySide, Field, Self, // resolve AllOthers, Depends, Other, // TODO: resolve or resolve + run? Allies, Ally, AllyOrSelf, Foe, // resolve + run Foes, FoeSide, RandomFoe, pub inline fn resolves(target: Target) bool { return @enumToInt(target) >= @enumToInt(Target.AllOthers); } pub inline fn runs(target: Target) bool { return @enumToInt(target) >= @enumToInt(Target.Foes); } }; comptime { assert(@sizeOf(Move) == 1); assert(@sizeOf(@TypeOf(DATA)) == 1255); } pub inline fn get(id: Move) Data { assert(id != .None); return DATA[@enumToInt(id) - 1]; } const Event = enum { resolve, run }; pub inline fn frames(id: Move, event: Event) u8 { return @as(u8, @boolToInt(switch (event) { .resolve => switch (id) { .Counter, .MirrorCoat, .Pursuit => 2, else => get(id).target.resolves(), }, .run => get(id).target.runs(), })); } // @test-only pub fn pp(id: Move) u8 { return Move.get(id).pp * 5; } };
src/lib/gen2/data/moves.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 = enum(u8) { alpha8 = c.NK_FONT_ATLAS_ALPHA8, rgba32 = c.NK_FONT_ATLAS_RGBA32, }; 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 w: c_int = undefined; var h: c_int = undefined; const data = c.nk_font_atlas_bake( atlas, &w, &h, @intToEnum(c.enum_nk_font_atlas_format, @enumToInt(format)), ) orelse return error.OutOfMemory; return Baked{ .data = @ptrCast([*]const u8, data), .w = @intCast(usize, w), .h = @intCast(usize, h), }; } 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: usize, h: usize, }; test { testing.refAllDecls(@This()); }
src/atlas.zig
const fmath = @import("index.zig"); pub fn expm1(x: var) -> @typeOf(x) { const T = @typeOf(x); switch (T) { f32 => @inlineCall(expm1f, x), f64 => @inlineCall(expm1d, x), else => @compileError("exp1m not implemented for " ++ @typeName(T)), } } fn expm1f(x_: f32) -> f32 { const o_threshold: f32 = 8.8721679688e+01; const ln2_hi: f32 = 6.9313812256e-01; const ln2_lo: f32 = 9.0580006145e-06; const invln2: f32 = 1.4426950216e+00; const Q1: f32 = -3.3333212137e-2; const Q2: f32 = 1.5807170421e-3; var x = x_; const ux = @bitCast(u32, x); const hx = ux & 0x7FFFFFFF; const sign = hx >> 31; // |x| >= 27 * ln2 if (hx >= 0x4195B844) { // nan if (hx > 0x7F800000) { return x; } if (sign != 0) { return -1; } if (x > o_threshold) { x *= 0x1.0p127; return x; } } var hi: f32 = undefined; var lo: f32 = undefined; var c: f32 = undefined; var k: i32 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3EB17218) { // |x| < 1.5 * ln2 if (hx < 0x3F851592) { if (sign == 0) { hi = x - ln2_hi; lo = ln2_lo; k = 1; } else { hi = x + ln2_hi; lo = -ln2_lo; k = -1; } } else { var kf = invln2 * x; if (sign != 0) { kf -= 0.5; } else { kf += 0.5; } k = i32(kf); const t = f32(k); hi = x - t * ln2_hi; lo = t * ln2_lo; } x = hi - lo; c = (hi - x) - lo; } // |x| < 2^(-25) else if (hx < 0x33000000) { if (hx < 0x00800000) { fmath.forceEval(x * x); } return x; } else { k = 0; } const hfx = 0.5 * x; const hxs = x * hfx; const r1 = 1.0 + hxs * (Q1 + hxs * Q2); const t = 3.0 - r1 * hfx; var e = hxs * ((r1 - t) / (6.0 - x * t)); // c is 0 if (k == 0) { return x - (x * e - hxs); } e = x * (e - c) - c; e -= hxs; // exp(x) ~ 2^k (x_reduced - e + 1) if (k == -1) { return 0.5 * (x - e) - 0.5; } if (k == 1) { if (x < -0.25) { return -2.0 * (e - (x + 0.5)); } else { return 1.0 + 2.0 * (x - e); } } const twopk = @bitCast(f32, u32(0x7F + k) << 23); if (k < 0 or k > 56) { var y = x - e + 1.0; if (k == 128) { y = y * 2.0 * 0x1.0p127; } else { y = y * twopk; } return y - 1.0; } const uf = @bitCast(f32, u32(0x7F - k) << 23); if (k < 23) { return (x - e + (1 - uf)) * twopk; } else { return (x - (e + uf) + 1) * twopk; } } fn expm1d(x_: f64) -> f64 { const o_threshold: f64 = 7.09782712893383973096e+02; const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const invln2: f64 = 1.44269504088896338700e+00; const Q1: f64 = -3.33333333333331316428e-02; const Q2: f64 = 1.58730158725481460165e-03; const Q3: f64 = -7.93650757867487942473e-05; const Q4: f64 = 4.00821782732936239552e-06; const Q5: f64 = -2.01099218183624371326e-07; var x = x_; const ux = @bitCast(u64, x); const hx = u32(ux >> 32) & 0x7FFFFFFF; const sign = hx >> 63; // |x| >= 56 * ln2 if (hx >= 0x4043687A) { // exp1md(nan) = nan if (hx > 0x7FF00000) { return x; } // exp1md(-ve) = -1 if (sign != 0) { return -1; } if (x > o_threshold) { fmath.raiseOverflow(); return fmath.nan(f64); } } var hi: f64 = undefined; var lo: f64 = undefined; var c: f64 = undefined; var k: i32 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3FD62E42) { // |x| < 1.5 * ln2 if (hx < 0x3FF0A2B2) { if (sign == 0) { hi = x - ln2_hi; lo = ln2_lo; k = 1; } else { hi = x + ln2_hi; lo = -ln2_lo; k = -1; } } else { var kf = invln2 * x; if (sign != 0) { kf -= 0.5; } else { kf += 0.5; } k = i32(kf); const t = f64(k); hi = x - t * ln2_hi; lo = t * ln2_lo; } x = hi - lo; c = (hi - x) - lo; } // |x| < 2^(-54) else if (hx < 0x3C900000) { if (hx < 0x00100000) { fmath.forceEval(f32(x)); } return x; } else { k = 0; } const hfx = 0.5 * x; const hxs = x * hfx; const r1 = 1.0 + hxs * (Q1 + hxs * (Q2 + hxs * (Q3 + hxs * (Q4 + hxs * Q5)))); const t = 3.0 - r1 * hfx; var e = hxs * ((r1 - t) / (6.0 - x * t)); // c is 0 if (k == 0) { return x - (x * e - hxs); } e = x * (e - c) - c; e -= hxs; // exp(x) ~ 2^k (x_reduced - e + 1) if (k == -1) { return 0.5 * (x - e) - 0.5; } if (k == 1) { if (x < -0.25) { return -2.0 * (e - (x + 0.5)); } else { return 1.0 + 2.0 * (x - e); } } const twopk = @bitCast(f64, u64(0x3FF + k) << 52); if (k < 0 or k > 56) { var y = x - e + 1.0; if (k == 1024) { y = y * 2.0; // TODO: * 0x1.0p1023; } else { y = y * twopk; } return y - 1.0; } const uf = @bitCast(f64, u64(0x3FF - k) << 52); if (k < 20) { return (x - e + (1 - uf)) * twopk; } else { return (x - (e + uf) + 1) * twopk; } } test "exp1m" { fmath.assert(expm1(f32(0.0)) == expm1f(0.0)); fmath.assert(expm1(f64(0.0)) == expm1d(0.0)); } test "expm1f" { const epsilon = 0.000001; fmath.assert(expm1f(0.0) == 0.0); fmath.assert(fmath.approxEq(f32, expm1f(0.0), 0.0, epsilon)); fmath.assert(fmath.approxEq(f32, expm1f(0.2), 0.221403, epsilon)); fmath.assert(fmath.approxEq(f32, expm1f(0.8923), 1.440737, epsilon)); fmath.assert(fmath.approxEq(f32, expm1f(1.5), 3.481689, epsilon)); } test "expm1d" { const epsilon = 0.000001; fmath.assert(expm1d(0.0) == 0.0); fmath.assert(fmath.approxEq(f64, expm1d(0.0), 0.0, epsilon)); fmath.assert(fmath.approxEq(f64, expm1d(0.2), 0.221403, epsilon)); fmath.assert(fmath.approxEq(f64, expm1d(0.8923), 1.440737, epsilon)); fmath.assert(fmath.approxEq(f64, expm1d(1.5), 3.481689, epsilon)); }
src/expm1.zig
//-------------------------------------------------------------------------------- // Section: Types (7) //-------------------------------------------------------------------------------- const IID_IPrinting3DManagerInterop_Value = Guid.initString("9ca31010-1484-4587-b26b-dddf9f9caecd"); pub const IID_IPrinting3DManagerInterop = &IID_IPrinting3DManagerInterop_Value; pub const IPrinting3DManagerInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, GetForWindow: fn( self: *const IPrinting3DManagerInterop, appWindow: ?HWND, riid: ?*const Guid, printManager: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowPrintUIForWindowAsync: fn( self: *const IPrinting3DManagerInterop, appWindow: ?HWND, riid: ?*const Guid, asyncOperation: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinting3DManagerInterop_GetForWindow(self: *const T, appWindow: ?HWND, riid: ?*const Guid, printManager: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinting3DManagerInterop.VTable, self.vtable).GetForWindow(@ptrCast(*const IPrinting3DManagerInterop, self), appWindow, riid, printManager); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinting3DManagerInterop_ShowPrintUIForWindowAsync(self: *const T, appWindow: ?HWND, riid: ?*const Guid, asyncOperation: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinting3DManagerInterop.VTable, self.vtable).ShowPrintUIForWindowAsync(@ptrCast(*const IPrinting3DManagerInterop, self), appWindow, riid, asyncOperation); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IPrintManagerInterop_Value = Guid.initString("c5435a42-8d43-4e7b-a68a-ef311e392087"); pub const IID_IPrintManagerInterop = &IID_IPrintManagerInterop_Value; pub const IPrintManagerInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, GetForWindow: fn( self: *const IPrintManagerInterop, appWindow: ?HWND, riid: ?*const Guid, printManager: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowPrintUIForWindowAsync: fn( self: *const IPrintManagerInterop, appWindow: ?HWND, riid: ?*const Guid, asyncOperation: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintManagerInterop_GetForWindow(self: *const T, appWindow: ?HWND, riid: ?*const Guid, printManager: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintManagerInterop.VTable, self.vtable).GetForWindow(@ptrCast(*const IPrintManagerInterop, self), appWindow, riid, printManager); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintManagerInterop_ShowPrintUIForWindowAsync(self: *const T, appWindow: ?HWND, riid: ?*const Guid, asyncOperation: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintManagerInterop.VTable, self.vtable).ShowPrintUIForWindowAsync(@ptrCast(*const IPrintManagerInterop, self), appWindow, riid, asyncOperation); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintWorkflowXpsReceiver_Value = Guid.initString("04097374-77b8-47f6-8167-aae29d4cf84b"); pub const IID_IPrintWorkflowXpsReceiver = &IID_IPrintWorkflowXpsReceiver_Value; pub const IPrintWorkflowXpsReceiver = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetDocumentSequencePrintTicket: fn( self: *const IPrintWorkflowXpsReceiver, documentSequencePrintTicket: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDocumentSequenceUri: fn( self: *const IPrintWorkflowXpsReceiver, documentSequenceUri: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDocumentData: fn( self: *const IPrintWorkflowXpsReceiver, documentId: u32, documentPrintTicket: ?*IStream, documentUri: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPage: fn( self: *const IPrintWorkflowXpsReceiver, documentId: u32, pageId: u32, pageReference: ?*IXpsOMPageReference, pageUri: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IPrintWorkflowXpsReceiver, ) 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 IPrintWorkflowXpsReceiver_SetDocumentSequencePrintTicket(self: *const T, documentSequencePrintTicket: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver.VTable, self.vtable).SetDocumentSequencePrintTicket(@ptrCast(*const IPrintWorkflowXpsReceiver, self), documentSequencePrintTicket); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowXpsReceiver_SetDocumentSequenceUri(self: *const T, documentSequenceUri: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver.VTable, self.vtable).SetDocumentSequenceUri(@ptrCast(*const IPrintWorkflowXpsReceiver, self), documentSequenceUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowXpsReceiver_AddDocumentData(self: *const T, documentId: u32, documentPrintTicket: ?*IStream, documentUri: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver.VTable, self.vtable).AddDocumentData(@ptrCast(*const IPrintWorkflowXpsReceiver, self), documentId, documentPrintTicket, documentUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowXpsReceiver_AddPage(self: *const T, documentId: u32, pageId: u32, pageReference: ?*IXpsOMPageReference, pageUri: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver.VTable, self.vtable).AddPage(@ptrCast(*const IPrintWorkflowXpsReceiver, self), documentId, pageId, pageReference, pageUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowXpsReceiver_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver.VTable, self.vtable).Close(@ptrCast(*const IPrintWorkflowXpsReceiver, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintWorkflowXpsReceiver2_Value = Guid.initString("023bcc0c-dfab-4a61-b074-490c6995580d"); pub const IID_IPrintWorkflowXpsReceiver2 = &IID_IPrintWorkflowXpsReceiver2_Value; pub const IPrintWorkflowXpsReceiver2 = extern struct { pub const VTable = extern struct { base: IPrintWorkflowXpsReceiver.VTable, Failed: fn( self: *const IPrintWorkflowXpsReceiver2, XpsError: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintWorkflowXpsReceiver.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowXpsReceiver2_Failed(self: *const T, XpsError: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsReceiver2.VTable, self.vtable).Failed(@ptrCast(*const IPrintWorkflowXpsReceiver2, self), XpsError); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintWorkflowObjectModelSourceFileContentNative_Value = Guid.initString("68c9e477-993e-4052-8ac6-454eff58db9d"); pub const IID_IPrintWorkflowObjectModelSourceFileContentNative = &IID_IPrintWorkflowObjectModelSourceFileContentNative_Value; pub const IPrintWorkflowObjectModelSourceFileContentNative = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartXpsOMGeneration: fn( self: *const IPrintWorkflowObjectModelSourceFileContentNative, receiver: ?*IPrintWorkflowXpsReceiver, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectFactory: fn( self: *const IPrintWorkflowObjectModelSourceFileContentNative, value: ?*?*IXpsOMObjectFactory1, ) 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 IPrintWorkflowObjectModelSourceFileContentNative_StartXpsOMGeneration(self: *const T, receiver: ?*IPrintWorkflowXpsReceiver) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowObjectModelSourceFileContentNative.VTable, self.vtable).StartXpsOMGeneration(@ptrCast(*const IPrintWorkflowObjectModelSourceFileContentNative, self), receiver); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowObjectModelSourceFileContentNative_get_ObjectFactory(self: *const T, value: ?*?*IXpsOMObjectFactory1) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowObjectModelSourceFileContentNative.VTable, self.vtable).get_ObjectFactory(@ptrCast(*const IPrintWorkflowObjectModelSourceFileContentNative, self), value); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintWorkflowXpsObjectModelTargetPackageNative_Value = Guid.initString("7d96bc74-9b54-4ca1-ad3a-979c3d44ddac"); pub const IID_IPrintWorkflowXpsObjectModelTargetPackageNative = &IID_IPrintWorkflowXpsObjectModelTargetPackageNative_Value; pub const IPrintWorkflowXpsObjectModelTargetPackageNative = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DocumentPackageTarget: fn( self: *const IPrintWorkflowXpsObjectModelTargetPackageNative, value: ?*?*IXpsDocumentPackageTarget, ) 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 IPrintWorkflowXpsObjectModelTargetPackageNative_get_DocumentPackageTarget(self: *const T, value: ?*?*IXpsDocumentPackageTarget) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowXpsObjectModelTargetPackageNative.VTable, self.vtable).get_DocumentPackageTarget(@ptrCast(*const IPrintWorkflowXpsObjectModelTargetPackageNative, self), value); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintWorkflowConfigurationNative_Value = Guid.initString("c056be0a-9ee2-450a-9823-964f0006f2bb"); pub const IID_IPrintWorkflowConfigurationNative = &IID_IPrintWorkflowConfigurationNative_Value; pub const IPrintWorkflowConfigurationNative = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrinterQueue: fn( self: *const IPrintWorkflowConfigurationNative, value: ?*?*IPrinterQueue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DriverProperties: fn( self: *const IPrintWorkflowConfigurationNative, value: ?*?*IPrinterPropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserProperties: fn( self: *const IPrintWorkflowConfigurationNative, value: ?*?*IPrinterPropertyBag, ) 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 IPrintWorkflowConfigurationNative_get_PrinterQueue(self: *const T, value: ?*?*IPrinterQueue) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowConfigurationNative.VTable, self.vtable).get_PrinterQueue(@ptrCast(*const IPrintWorkflowConfigurationNative, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowConfigurationNative_get_DriverProperties(self: *const T, value: ?*?*IPrinterPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowConfigurationNative.VTable, self.vtable).get_DriverProperties(@ptrCast(*const IPrintWorkflowConfigurationNative, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintWorkflowConfigurationNative_get_UserProperties(self: *const T, value: ?*?*IPrinterPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintWorkflowConfigurationNative.VTable, self.vtable).get_UserProperties(@ptrCast(*const IPrintWorkflowConfigurationNative, self), value); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // 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 (12) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const IInspectable = @import("../../system/win_rt.zig").IInspectable; const IPrinterPropertyBag = @import("../../graphics/printing.zig").IPrinterPropertyBag; const IPrinterQueue = @import("../../graphics/printing.zig").IPrinterQueue; const IStream = @import("../../system/com.zig").IStream; const IUnknown = @import("../../system/com.zig").IUnknown; const IXpsDocumentPackageTarget = @import("../../storage/xps.zig").IXpsDocumentPackageTarget; const IXpsOMObjectFactory1 = @import("../../storage/xps.zig").IXpsOMObjectFactory1; const IXpsOMPageReference = @import("../../storage/xps.zig").IXpsOMPageReference; const PWSTR = @import("../../foundation.zig").PWSTR; 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/system/win_rt/printing.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day7.txt", limit); defer allocator.free(text); const Node = struct { parent: []const u8, weight: u32, weigth_rec: u32, childs: [8][]const u8, len: usize, }; var nodes = std.StringHashMap(Node).init(allocator); defer nodes.deinit(); { var it = std.mem.split(u8, text, "\n"); while (it.next()) |line0| { const line = std.mem.trim(u8, line0, " \n\t\r"); if (line.len == 0) continue; var node: Node = undefined; var it2 = std.mem.tokenize(u8, line, "()->, \t"); const name = it2.next() orelse unreachable; node.weight = std.fmt.parseInt(u32, it2.next() orelse unreachable, 10) catch unreachable; node.weigth_rec = node.weight; node.len = 0; node.parent = ""; while (it2.next()) |child| { node.childs[node.len] = child; node.len += 1; } _ = try nodes.put(name, node); trace("node: {} ({}) -> {}\n", .{ name, node.weight, node.len }); } var it3 = nodes.iterator(); while (it3.next()) |KV| { const node = &KV.value; const name = KV.key; for (node.childs[0..node.len]) |child| { const c = nodes.get(child) orelse unreachable; c.value.parent = name; } } var it4 = nodes.iterator(); while (it4.next()) |KV| { const node = &KV.value; var parent = node; while (true) { if (parent.parent.len == 0) break; const p = nodes.get(parent.parent) orelse unreachable; parent = &p.value; parent.weigth_rec += node.weight; } } } var root = blk: { var it = nodes.iterator(); while (it.next()) |KV| { const node = &KV.value; const name = KV.key; if (node.parent.len == 0) break :blk name; } unreachable; }; try stdout.print("root={}\n", .{root}); const Local = struct { fn find_unbalanced(_nodes: anytype, name: []const u8) void { const KV = _nodes.get(name) orelse unreachable; const n = &KV.value; var wsr: [16]u32 = undefined; var ws0: [16]u32 = undefined; var unbalanced = false; for (n.childs[0..n.len]) |child, i| { find_unbalanced(_nodes, child); const c = _nodes.get(child) orelse unreachable; wsr[i] = c.value.weigth_rec; ws0[i] = c.value.weight; if (i > 0 and wsr[i] != wsr[0]) { unbalanced = true; } } if (unbalanced) { trace("name:{}, ", .{name}); for (wsr[0..n.len]) |w, i| { trace("{} ({}+...), ", .{ w, ws0[i] }); } trace("\n", .{}); } } }; Local.find_unbalanced(&nodes, root); // return error.SolutionNotFound; }
2017/day7.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const assert = std.debug.assert; pub const main = tools.defaultMain("2021/day20.txt", run); const Map = tools.Map(u8, 256, 256, true); const Vec2 = tools.Vec2; pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { // var arena_alloc = std.heap.ArenaAllocator.init(gpa); // defer arena_alloc.deinit(); // const arena = arena_alloc.allocator(); var map = Map{ .default_tile = '.' }; var it0 = std.mem.tokenize(u8, input, "\n"); const dico = it0.next().?; assert(dico.len == 512); // assert(dico[0] == '.'); ahahahahaahahah assert(dico[0] == '.' or dico[511] == '.'); var p = Vec2{ -50, -50 }; while (it0.next()) |line| : (p += Vec2{ 0, 1 }) { map.setLine(p, line); } const ans = ans: { if (with_trace) { var buf: [15000]u8 = undefined; trace("gen {}:\n{s}", .{ 0, map.printToBuf(&buf, .{}) }); } var map2 = Map{ .default_tile = '.' }; const flipflop = [_]*Map{ &map, &map2 }; var population: [50]u32 = undefined; for (population) |*pop, gen| { const cur = flipflop[gen % 2]; const next = flipflop[1 - gen % 2]; next.bbox = tools.BBox.empty; cur.default_tile = if (gen % 2 == 0) '.' else dico[0]; next.default_tile = if (1 - gen % 2 == 0) '.' else dico[0]; // extend bbox: cur.set(cur.bbox.min + Vec2{ -1, -1 }, cur.default_tile); cur.set(cur.bbox.max + Vec2{ 1, 1 }, cur.default_tile); var it = cur.iter(null); var popcount: u32 = 0; while (it.nextEx()) |sq| { const key = 0 // | @as(u9, @boolToInt((sq.up_left orelse cur.default_tile) != '.')) << 8 // | @as(u9, @boolToInt((sq.up orelse cur.default_tile) != '.')) << 7 // | @as(u9, @boolToInt((sq.up_right orelse cur.default_tile) != '.')) << 6 // // | @as(u9, @boolToInt((sq.left orelse cur.default_tile) != '.')) << 5 // | @as(u9, @boolToInt(sq.t.* != '.')) << 4 // | @as(u9, @boolToInt((sq.right orelse cur.default_tile) != '.')) << 3 // // | @as(u9, @boolToInt((sq.down_left orelse cur.default_tile) != '.')) << 2 // | @as(u9, @boolToInt((sq.down orelse cur.default_tile) != '.')) << 1 // | @as(u9, @boolToInt((sq.down_right orelse cur.default_tile) != '.')) << 0 // ; next.set(sq.p, dico[key]); popcount += @boolToInt(dico[key] != '.'); } if (gen % 2 == 1) { pop.* = popcount; } else { // undef, infinite. } if (with_trace) { var buf: [100000]u8 = undefined; trace("gen {}:\n{s}", .{ gen + 1, next.printToBuf(&buf, .{}) }); } } break :ans [2]u32{ population[1], population[49] }; }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans[0]}), try std.fmt.allocPrint(gpa, "{}", .{ans[1]}), }; } test { { const res = try run( \\..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#......#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.....####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.......##..####..#...#.#.#...##..#.#..###..#####........#..####......#..# \\ \\#..#. \\#.... \\##..# \\..#.. \\..### , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("35", res[0]); try std.testing.expectEqualStrings("3351", res[1]); } { const res = try run( \\#.#.##..#..#..###.#.#....#.########.#.##.#..#.###..###.##.#.##.#.#.....#..##.#.#..###.###.######..#.#..#######.#..#....####..###.####.###.#.#######.#...#...#.##.###..###..##.#.#.###........##.#.....#.##.#.####...#...#.#..###.#.#...#....#...####..#.########.#...#.####.#####..#.#.###......#.##...###..##..#.#..#....#..###.#.##.....##.#####..##.####.#.###....##.###...#.##....##.#..#.#..#..#.##...#.##..#####.####.#.##...##...##...#.##.#.#.####..##...#.....#......#.#......#..###..#..##..##.###..#####..#..##.#..#. \\ \\#..#. \\#.... \\##..# \\..#.. \\..### , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("37", res[0]); try std.testing.expectEqualStrings("4953", res[1]); } { // conway's game of life: const res = try run( \\.......#...#.##....#.###.######....#.##..##.#....######.###.#......#.##..##.#....######.###.#....##.#...#.......###.#...#..........#.##..##.#....######.###.#....##.#...#.......###.#...#........##.#...#.......###.#...#.......#...............#..................#.##..##.#....######.###.#....##.#...#.......###.#...#........##.#...#.......###.#...#.......#...............#................##.#...#.......###.#...#.......#...............#...............#...............#............................................... \\ \\#..#. \\#.... \\##..# \\..#.. \\..### , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("11", res[0]); try std.testing.expectEqualStrings("114", res[1]); } }
2021/day20.zig
const std = @import("std"); pub fn main() !void { const file = try std.fs.cwd().createFile("foo.tga", .{ .read = true }); defer file.close(); const width: u16 = 300; const height: u16 = 200; // https://stackoverflow.com/a/49658800/695615 // https://en.wikipedia.org/wiki/Truevision_TGA // http://paulbourke.net/dataformats/tga/ // Note that all multi-byte values are little-endian. const header: [18]u8 = .{ 0, // 1 - No ID field (length of 0) 0, // 2 - No color map 2, // 3 - Uncompressed true-color image 0, // 4 \ 0, // 5 | 0, // 6 | Color map information (none) 0, // 7 | 0, // 8 / 0, // 9 \ Origin X (16 bits) 0, // 10 / 0, // 11 \ Origin Y (16 bits) 0, // 12 / width & 255, // 13 \ Width (px) mask last 8 bits (width >> 8) & 255, // 14 / Width (px) right shift and mask to get first 8 bits height & 255, // 15 \ Height (px) last (height >> 8) & 255, // 16 / Height (px) first 24, // 17 - Bits per pixel (3 colors, 8 bits each) 0b00100000, // 18 - Image descriptor (Bits 4,5 are origin. Set to "top left".) }; try file.writeAll(&header); // Scale from image dimensions to color min and max. var w_scale: f32 = 255 / @as(f32, width); var h_scale: f32 = 255 / @as(f32, height); // Buffer one row's worth of pixels (makes a huge difference on huge images). var out_buffer: [3 * width]u8 = undefined; var w: u32 = 0; // Pixel counter per row (width) var h: u32 = 0; // Row counter (height) // For height's worth of rows... while (h < height) : (h += 1) { // Reset row pixel counter w = 0; // Fill row buffer while (w < width) : (w += 1) { // IMPORTANT: TGA stores in BGR order, not RGB. const pixel_r = w * 3 + 2; const pixel_g = w * 3 + 1; const pixel_b = w * 3; out_buffer[pixel_r] = @floatToInt(u8, @intToFloat(f32, w) * w_scale); // increase across out_buffer[pixel_g] = @floatToInt(u8, @intToFloat(f32, h) * h_scale); // increase down out_buffer[pixel_b] = @floatToInt(u8, @intToFloat(f32, width-w) * w_scale); // decrease across } // Write row try file.writeAll(&out_buffer); } }
tga.zig
const std = @import("std"); const io = std.io; const heap = std.heap; const mem = std.mem; const os = std.os; const net = std.net; usingnamespace @import("primitive_types.zig"); pub const PrimitiveReader = @import("primitive/reader.zig").PrimitiveReader; pub const PrimitiveWriter = @import("primitive/writer.zig").PrimitiveWriter; const testing = @import("testing.zig"); pub const FrameFlags = struct { pub const Compression: u8 = 0x01; pub const Tracing: u8 = 0x02; pub const CustomPayload: u8 = 0x04; pub const Warning: u8 = 0x08; pub const UseBeta: u8 = 0x10; }; pub const FrameHeader = packed struct { version: ProtocolVersion, flags: u8, stream: i16, opcode: Opcode, body_len: u32, pub fn init(comptime ReaderType: type, in: ReaderType) !FrameHeader { var buf: [@sizeOf(FrameHeader)]u8 = undefined; const read = try in.readAll(&buf); if (read != @sizeOf(FrameHeader)) { return error.UnexpectedEOF; } return FrameHeader{ .version = try ProtocolVersion.init(buf[0]), .flags = buf[1], .stream = mem.readIntBig(i16, @ptrCast(*[2]u8, buf[2..4])), .opcode = @intToEnum(Opcode, buf[4]), .body_len = mem.readIntBig(u32, @ptrCast(*[4]u8, buf[5..9])), }; } }; pub const RawFrame = struct { header: FrameHeader, body: []const u8, pub fn deinit(self: @This(), allocator: *mem.Allocator) void { allocator.free(self.body); } }; pub fn RawFrameReader(comptime ReaderType: type) type { return struct { const Self = @This(); reader: ReaderType, pub fn init(in: ReaderType) Self { return Self{ .reader = in, }; } pub fn read(self: *Self, allocator: *mem.Allocator) !RawFrame { var buf: [@sizeOf(FrameHeader)]u8 = undefined; const n_header_read = try self.reader.readAll(&buf); if (n_header_read != @sizeOf(FrameHeader)) { return error.UnexpectedEOF; } var header = FrameHeader{ .version = ProtocolVersion{ .version = buf[0] }, .flags = buf[1], .stream = mem.readIntBig(i16, @ptrCast(*[2]u8, buf[2..4])), .opcode = @intToEnum(Opcode, buf[4]), .body_len = mem.readIntBig(u32, @ptrCast(*[4]u8, buf[5..9])), }; const len = @as(usize, header.body_len); const body = try allocator.alloc(u8, len); const n_read = try self.reader.readAll(body); if (n_read != len) { return error.UnexpectedEOF; } return RawFrame{ .header = header, .body = body, }; } }; } pub fn RawFrameWriter(comptime WriterType: type) type { return struct { const Self = @This(); writer: WriterType, pub fn init(out: WriterType) Self { return Self{ .writer = out, }; } pub fn write(self: *Self, raw_frame: RawFrame) !void { var buf: [@sizeOf(FrameHeader)]u8 = undefined; buf[0] = raw_frame.header.version.version; buf[1] = raw_frame.header.flags; mem.writeIntBig(i16, @ptrCast(*[2]u8, buf[2..4]), raw_frame.header.stream); buf[4] = @enumToInt(raw_frame.header.opcode); mem.writeIntBig(u32, @ptrCast(*[4]u8, buf[5..9]), raw_frame.header.body_len); try self.writer.writeAll(&buf); try self.writer.writeAll(raw_frame.body); } }; } // TODO(vincent): do we want to keep these wrapper types ? /// ColumnData is a wrapper around a slice of bytes. pub const ColumnData = struct { slice: []const u8, }; /// RowData is a wrapper around a slice of ColumnData. pub const RowData = struct { slice: []const ColumnData, }; pub fn checkHeader(opcode: Opcode, data_len: usize, header: FrameHeader) void { // We can only use v4 for now testing.expect(header.version.is(4)); // Don't care about the flags here // Don't care about the stream testing.expectEqual(opcode, header.opcode); testing.expectEqual(@as(usize, header.body_len), data_len - @sizeOf(FrameHeader)); } test "frame header: read and write" { const exp = "\x04\x00\x00\xd7\x05\x00\x00\x00\x00"; var fbs = io.fixedBufferStream(exp); // deserialize the header var reader = fbs.reader(); const header = try FrameHeader.init(@TypeOf(reader), fbs.reader()); testing.expect(header.version.is(4)); testing.expect(header.version.isRequest()); testing.expectEqual(@as(u8, 0), header.flags); testing.expectEqual(@as(i16, 215), header.stream); testing.expectEqual(Opcode.Options, header.opcode); testing.expectEqual(@as(u32, 0), header.body_len); testing.expectEqual(@as(usize, 0), exp.len - @sizeOf(FrameHeader)); } test "" { _ = @import("frames/error.zig"); _ = @import("frames/startup.zig"); _ = @import("frames/ready.zig"); _ = @import("frames/auth.zig"); _ = @import("frames/options.zig"); _ = @import("frames/supported.zig"); _ = @import("frames/query.zig"); _ = @import("frames/result.zig"); _ = @import("frames/prepare.zig"); _ = @import("frames/execute.zig"); _ = @import("frames/register.zig"); _ = @import("frames/event.zig"); _ = @import("frames/batch.zig"); _ = @import("primitive/reader.zig"); _ = @import("primitive/writer.zig"); }
src/frame.zig
const std = @import("std"); const Arena = std.heap.ArenaAllocator; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const yeti = @import("yeti"); const initCodebase = yeti.initCodebase; const tokenize = yeti.tokenize; const parse = yeti.parse; const analyzeSemantics = yeti.analyzeSemantics; const codegen = yeti.codegen; const printWasm = yeti.printWasm; const components = yeti.components; const literalOf = yeti.query.literalOf; const typeOf = yeti.query.typeOf; const parentType = yeti.query.parentType; const valueType = yeti.query.valueType; const MockFileSystem = yeti.FileSystem; test "parse pointer" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start(ptr: *i32) i32 { \\ 0 \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const start = top_level.findString("start"); const overloads = start.get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const overload = overloads[0]; const parameters = overload.get(components.Parameters).slice(); try expectEqual(parameters.len, 1); const ptr = parameters[0]; try expectEqualStrings(literalOf(ptr), "ptr"); const type_of = ptr.get(components.TypeAst).entity; try expectEqual(type_of.get(components.AstKind), .pointer); try expectEqualStrings(literalOf(type_of.get(components.Value).entity), "i32"); const body = overload.get(components.Body).slice(); try expectEqual(body.len, 1); const zero = body[0]; try expectEqual(zero.get(components.AstKind), .int); try expectEqualStrings(literalOf(zero), "0"); } test "parse pointer load" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start(ptr: *i32) i32 { \\ *ptr \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const start = top_level.findString("start"); const overloads = start.get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const overload = overloads[0]; const parameters = overload.get(components.Parameters).slice(); try expectEqual(parameters.len, 1); const ptr = parameters[0]; try expectEqualStrings(literalOf(ptr), "ptr"); const type_of = ptr.get(components.TypeAst).entity; try expectEqual(type_of.get(components.AstKind), .pointer); try expectEqualStrings(literalOf(type_of.get(components.Value).entity), "i32"); const body = overload.get(components.Body).slice(); try expectEqual(body.len, 1); const load = body[0]; try expectEqual(load.get(components.AstKind), .pointer); const value = load.get(components.Value).entity; try expectEqual(value.get(components.AstKind), .symbol); try expectEqualStrings(literalOf(value), "ptr"); } test "parse pointer load after new line" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start() i32 { \\ ptr = cast(*i32, 0) \\ *ptr \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const start = top_level.findString("start"); const overloads = start.get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const overload = overloads[0]; const parameters = overload.get(components.Parameters).slice(); try expectEqual(parameters.len, 0); const body = overload.get(components.Body).slice(); try expectEqual(body.len, 2); const load = body[1]; try expectEqual(load.get(components.AstKind), .pointer); const value = load.get(components.Value).entity; try expectEqual(value.get(components.AstKind), .symbol); try expectEqualStrings(literalOf(value), "ptr"); } test "analyze semantics of casting int literal to *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ cast(*i64, 0) \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqualStrings(literalOf(return_type), "*i64"); try expectEqual(parentType(return_type), builtins.Ptr); try expectEqualStrings(literalOf(valueType(return_type)), "i64"); try expectEqual(valueType(return_type), builtins.I64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 1); const cast = body[0]; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); } test "analyze semantics of casting i32 to *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ i: i32 = 0 \\ cast(*i64, i) \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqualStrings(literalOf(return_type), "*i64"); try expectEqual(parentType(return_type), builtins.Ptr); try expectEqualStrings(literalOf(valueType(return_type)), "i64"); try expectEqual(valueType(return_type), builtins.I64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); const i = blk: { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); try expectEqualStrings(literalOf(define.get(components.Value).entity), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "i"); try expectEqual(typeOf(local), builtins.I32); break :blk local; }; const cast = body[1]; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); try expectEqual(cast.get(components.Value).entity, i); } test "analyze semantics of pointer store" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() void { \\ ptr = cast(*i64, 0) \\ *ptr = 10 \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); try expectEqual(start.get(components.ReturnType).entity, builtins.Void); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); const ptr = blk: { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const cast = define.get(components.Value).entity; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); try expectEqual(typeOf(local), pointer_type); break :blk local; }; const store = body[1]; try expectEqual(store.get(components.AstKind), .intrinsic); try expectEqual(store.get(components.Intrinsic), .store); try expectEqual(typeOf(store), builtins.Void); const arguments = store.get(components.Arguments).slice(); try expectEqual(arguments.len, 2); try expectEqual(arguments[0], ptr); const rhs = arguments[1]; try expectEqual(rhs.get(components.AstKind), .int); try expectEqual(typeOf(rhs), builtins.I64); try expectEqualStrings(literalOf(rhs), "10"); } test "analyze semantics of pointer load" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() i64 { \\ ptr = cast(*i64, 0) \\ *ptr \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); try expectEqual(start.get(components.ReturnType).entity, builtins.I64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); const ptr = blk: { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const cast = define.get(components.Value).entity; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); try expectEqual(typeOf(local), pointer_type); break :blk local; }; const load = body[1]; try expectEqual(load.get(components.AstKind), .intrinsic); try expectEqual(load.get(components.Intrinsic), .load); try expectEqual(typeOf(load), builtins.I64); const arguments = load.get(components.Arguments).slice(); try expectEqual(arguments.len, 1); try expectEqual(arguments[0], ptr); } test "analyze semantics of adding *i64 and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ ptr = cast(*i64, 0) \\ ptr + 1 \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqual(valueType(return_type), builtins.I64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const cast = define.get(components.Value).entity; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); try expectEqual(typeOf(local), pointer_type); } const add = body[1]; try expectEqual(add.get(components.AstKind), .intrinsic); try expectEqual(add.get(components.Intrinsic), .add_ptr_i32); try expectEqual(typeOf(add), return_type); } test "analyze semantics of subtracting *i64 and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ ptr = cast(*i64, 0) \\ ptr - 1 \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqual(valueType(return_type), builtins.I64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const cast = define.get(components.Value).entity; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); try expectEqual(typeOf(local), pointer_type); } const add = body[1]; try expectEqual(add.get(components.AstKind), .intrinsic); try expectEqual(add.get(components.Intrinsic), .subtract_ptr_i32); try expectEqual(typeOf(add), return_type); } test "analyze semantics of comparing two *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() i32 { \\ ptr = cast(*i64, 0) \\ ptr == ptr \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqual(return_type, builtins.I32); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); { const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const cast = define.get(components.Value).entity; try expectEqual(cast.get(components.AstKind), .cast); const pointer_type = typeOf(cast); try expectEqual(parentType(pointer_type), builtins.Ptr); try expectEqual(valueType(pointer_type), builtins.I64); const zero = cast.get(components.Value).entity; try expectEqual(zero.get(components.AstKind), .int); try expectEqual(typeOf(zero), builtins.I32); try expectEqualStrings(literalOf(zero), "0"); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); try expectEqual(typeOf(local), pointer_type); } const equal = body[1]; try expectEqual(equal.get(components.AstKind), .intrinsic); try expectEqual(equal.get(components.Intrinsic), .equal); try expectEqual(typeOf(equal), builtins.I32); } test "codegen of casting int literal to *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ cast(*i64, 0) \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 1); const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } test "codegen of storing through pointer" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() void { \\ ptr = cast(*i64, 0) \\ *ptr = 10 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 5); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const constant = wasm_instructions[3]; try expectEqual(constant.get(components.WasmInstructionKind), .i64_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "10"); } { try expectEqual(wasm_instructions[4].get(components.WasmInstructionKind), .i64_store); } } test "codegen of loading through pointer" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() i64 { \\ ptr = cast(*i64, 0) \\ *ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 4); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } try expectEqual(wasm_instructions[3].get(components.WasmInstructionKind), .i64_load); } test "codegen of adding pointer and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ ptr = cast(*i64, 0) \\ ptr + 1 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 5); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const constant = wasm_instructions[3]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "8"); } try expectEqual(wasm_instructions[4].get(components.WasmInstructionKind), .i32_add); } test "codegen of subtracting pointer and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ ptr = cast(*i64, 0) \\ ptr - 1 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 5); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const constant = wasm_instructions[3]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "8"); } try expectEqual(wasm_instructions[4].get(components.WasmInstructionKind), .i32_sub); } test "codegen of comparing two *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const op_strings = [_][]const u8{ "==", "!=", ">=", ">", "<=", "<" }; const ops = [_]components.WasmInstructionKind{ .i32_eq, .i32_ne, .i32_ge, .i32_gt, .i32_le, .i32_lt }; for (op_strings) |op_string, i| { var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(), \\start() i32 {{ \\ ptr = cast(*i64, 0) \\ ptr {s} ptr \\}} , .{op_string})); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 5); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[3]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } try expectEqual(wasm_instructions[4].get(components.WasmInstructionKind), ops[i]); } } test "codegen of subtracting two *i64" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() i32 { \\ ptr = cast(*i64, 0) \\ ptr - ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 7); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const local_set = wasm_instructions[1]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); const local = local_set.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[2]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } { const local_get = wasm_instructions[3]; try expectEqual(local_get.get(components.WasmInstructionKind), .local_get); const local = local_get.get(components.Local).entity; try expectEqualStrings(literalOf(local.get(components.Name).entity), "ptr"); } try expectEqual(wasm_instructions[4].get(components.WasmInstructionKind), .i32_sub); { const constant = wasm_instructions[5]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "8"); } try expectEqual(wasm_instructions[6].get(components.WasmInstructionKind), .i32_div); } test "print wasm pointer" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() *i64 { \\ cast(*i64, 0) \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (i32.const 0)) \\ \\ (export "_start" (func $foo/start))) ); } test "print wasm pointer store" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() void { \\ ptr = cast(*i64, 0) \\ *ptr = 10 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start \\ (local $ptr i32) \\ (i32.const 0) \\ (local.set $ptr) \\ (local.get $ptr) \\ (i64.const 10) \\ i64.store) \\ \\ (export "_start" (func $foo/start)) \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm pointer load" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() i64 { \\ ptr = cast(*i64, 0) \\ *ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i64) \\ (local $ptr i32) \\ (i32.const 0) \\ (local.set $ptr) \\ (local.get $ptr) \\ i64.load) \\ \\ (export "_start" (func $foo/start)) \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm pointer load u8" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ ptr = cast(*u8, 0) \\ *ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (local $ptr i32) \\ (i32.const 0) \\ (local.set $ptr) \\ (local.get $ptr) \\ i32.load8_u) \\ \\ (export "_start" (func $foo/start)) \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm pointer as parameter" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\@export \\f(ptr: *i32) i32 { \\ 0 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/f..ptr.ptr.i32 (param $ptr i32) (result i32) \\ (i32.const 0)) \\ \\ (export "f" (func $foo/f..ptr.ptr.i32))) ); } test "print wasm adding pointer and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\@export \\f(ptr: *i64) *i64 { \\ ptr + 1 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/f..ptr.ptr.i64 (param $ptr i32) (result i32) \\ (local.get $ptr) \\ (i32.const 8) \\ i32.add) \\ \\ (export "f" (func $foo/f..ptr.ptr.i64))) ); } test "print wasm subtracting pointer and int literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\@export \\f(ptr: *i64) *i64 { \\ ptr - 1 \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/f..ptr.ptr.i64 (param $ptr i32) (result i32) \\ (local.get $ptr) \\ (i32.const 8) \\ i32.sub) \\ \\ (export "f" (func $foo/f..ptr.ptr.i64))) ); } test "print wasm adding pointer and i32" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\@export \\f(ptr: *i64, len: i32) *i64 { \\ ptr + len \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/f..ptr.ptr.i64..len.i32 (param $ptr i32) (param $len i32) (result i32) \\ (local.get $ptr) \\ (local.get $len) \\ (i32.const 8) \\ i32.mul \\ i32.add) \\ \\ (export "f" (func $foo/f..ptr.ptr.i64..len.i32))) ); }
src/tests/test_pointer.zig
const std = @import("std"); const c = @cImport({ @cInclude("binding.h"); }); pub const PropertyAttribute = struct { pub const None = c.None; pub const ReadOnly = c.ReadOnly; }; pub const PromiseRejectEvent = struct { pub const kPromiseRejectWithNoHandler = c.kPromiseRejectWithNoHandler; pub const kPromiseHandlerAddedAfterReject = c.kPromiseHandlerAddedAfterReject; pub const kPromiseRejectAfterResolved = c.kPromiseRejectAfterResolved; pub const kPromiseResolveAfterResolved = c.kPromiseResolveAfterResolved; }; pub const MessageErrorLevel = struct { pub const kMessageLog = c.kMessageLog; pub const kMessageDebug = c.kMessageDebug; pub const kMessageInfo = c.kMessageInfo; pub const kMessageError = c.kMessageError; pub const kMessageWarning = c.kMessageWarning; pub const kMessageAll = c.kMessageAll; }; /// [V8] /// Policy for running microtasks: /// - explicit: microtasks are invoked with the /// Isolate::PerformMicrotaskCheckpoint() method; /// - scoped: microtasks invocation is controlled by MicrotasksScope objects; /// - auto: microtasks are invoked when the script call depth decrements to zero. pub const MicrotasksPolicy = struct { pub const kExplicit = c.kExplicit; pub const kScoped = c.kScoped; pub const kAuto = c.kAuto; }; // Currently, user callback functions passed into FunctionTemplate will need to have this declared as a param and then // converted to FunctionCallbackInfo to get a nicer interface. pub const C_FunctionCallbackInfo = c.FunctionCallbackInfo; pub const C_PropertyCallbackInfo = c.PropertyCallbackInfo; pub const C_WeakCallbackInfo = c.WeakCallbackInfo; pub const C_PromiseRejectMessage = c.PromiseRejectMessage; pub const C_Message = c.Message; pub const C_Value = c.Value; pub const C_Context = c.Context; pub const C_Data = c.Data; pub const C_FixedArray = c.FixedArray; pub const C_Module = c.Module; pub const C_InternalAddress = c.InternalAddress; pub const MessageCallback = c.MessageCallback; pub const FunctionCallback = c.FunctionCallback; pub const AccessorNameGetterCallback = c.AccessorNameGetterCallback; pub const AccessorNameSetterCallback = c.AccessorNameSetterCallback; pub const CreateParams = c.CreateParams; pub const Name = c.Name; pub const SharedPtr = c.SharedPtr; const Root = @This(); pub const Platform = struct { const Self = @This(); handle: *c.Platform, /// Must be called first before initV8Platform and initV8 /// Returns a new instance of the default v8::Platform implementation. /// /// |thread_pool_size| is the number of worker threads to allocate for /// background jobs. If a value of zero is passed, a suitable default /// based on the current number of processors online will be chosen. /// If |idle_task_support| is enabled then the platform will accept idle /// tasks (IdleTasksEnabled will return true) and will rely on the embedder /// calling v8::platform::RunIdleTasks to process the idle tasks. pub fn initDefault(thread_pool_size: u32, idle_task_support: bool) Self { // Verify struct sizes. const assert = std.debug.assert; assert(@sizeOf(c.CreateParams) == c.v8__Isolate__CreateParams__SIZEOF()); assert(@sizeOf(c.TryCatch) == c.v8__TryCatch__SIZEOF()); assert(@sizeOf(c.PromiseRejectMessage) == c.v8__PromiseRejectMessage__SIZEOF()); assert(@sizeOf(c.ScriptCompilerSource) == c.v8__ScriptCompiler__Source__SIZEOF()); assert(@sizeOf(c.ScriptCompilerCachedData) == c.v8__ScriptCompiler__CachedData__SIZEOF()); assert(@sizeOf(c.HeapStatistics) == c.v8__HeapStatistics__SIZEOF()); return .{ .handle = c.v8__Platform__NewDefaultPlatform(@intCast(c_int, thread_pool_size), if (idle_task_support) 1 else 0).?, }; } pub fn deinit(self: Self) void { c.v8__Platform__DELETE(self.handle); } /// [V8] /// Pumps the message loop for the given isolate. /// /// The caller has to make sure that this is called from the right thread. /// Returns true if a task was executed, and false otherwise. If the call to /// PumpMessageLoop is nested within another call to PumpMessageLoop, only /// nestable tasks may run. Otherwise, any task may run. Unless requested through /// the |behavior| parameter, this call does not block if no task is pending. The /// |platform| has to be created using |NewDefaultPlatform|. pub fn pumpMessageLoop(self: Self, isolate: Isolate, wait_for_work: bool) bool { return c.v8__Platform__PumpMessageLoop(self.handle, isolate.handle, wait_for_work); } }; pub fn getVersion() []const u8 { const str = c.v8__V8__GetVersion(); const idx = std.mem.indexOfSentinel(u8, 0, str); return str[0..idx]; } /// [v8] /// Sets the v8::Platform to use. This should be invoked before V8 is /// initialized. pub fn initV8Platform(platform: Platform) void { c.v8__V8__InitializePlatform(platform.handle); } /// [v8] /// Initializes V8. This function needs to be called before the first Isolate /// is created. It always returns true. pub fn initV8() void { c.v8__V8__Initialize(); } /// [v8] /// Releases any resources used by v8 and stops any utility thread /// that may be running. Note that disposing v8 is permanent, it /// cannot be reinitialized. /// /// It should generally not be necessary to dispose v8 before exiting /// a process, this should happen automatically. It is only necessary /// to use if the process needs the resources taken up by v8. pub fn deinitV8() bool { return c.v8__V8__Dispose() == 1; } /// [v8] /// Clears all references to the v8::Platform. This should be invoked after /// V8 was disposed. pub fn deinitV8Platform() void { c.v8__V8__DisposePlatform(); } pub fn initCreateParams() c.CreateParams { var params: c.CreateParams = undefined; c.v8__Isolate__CreateParams__CONSTRUCT(&params); return params; } pub fn createDefaultArrayBufferAllocator() *c.ArrayBufferAllocator { return c.v8__ArrayBuffer__Allocator__NewDefaultAllocator().?; } pub fn destroyArrayBufferAllocator(alloc: *c.ArrayBufferAllocator) void { c.v8__ArrayBuffer__Allocator__DELETE(alloc); } pub const Exception = struct { pub fn initError(msg: String) Value { return .{ .handle = c.v8__Exception__Error(msg.handle).?, }; } pub fn initMessage(iso: Isolate, exception: Value) Message { return .{ .handle = c.v8__Exception__CreateMessage(iso.handle, exception.handle).?, }; } /// [v8] /// Returns the original stack trace that was captured at the creation time /// of a given exception, or an empty handle if not available. pub fn getStackTrace(exception: Value) ?StackTrace { if (c.v8__Exception__GetStackTrace(exception.handle)) |handle| { return StackTrace{ .handle = handle, }; } else return null; } }; /// Contains Isolate related methods and convenience methods for creating js values. pub const Isolate = struct { const Self = @This(); handle: *c.Isolate, pub fn init(params: *const c.CreateParams) Self { const ptr = @intToPtr(*c.CreateParams, @ptrToInt(params)); return .{ .handle = c.v8__Isolate__New(ptr).?, }; } /// [V8] /// Disposes the isolate. The isolate must not be entered by any /// thread to be disposable. pub fn deinit(self: Self) void { c.v8__Isolate__Dispose(self.handle); } /// [V8] /// Sets this isolate as the entered one for the current thread. /// Saves the previously entered one (if any), so that it can be /// restored when exiting. Re-entering an isolate is allowed. /// [Notes] /// This is equivalent to initing an Isolate Scope. pub fn enter(self: *Self) void { c.v8__Isolate__Enter(self.handle); } /// [V8] /// Exits this isolate by restoring the previously entered one in the /// current thread. The isolate may still stay the same, if it was /// entered more than once. /// /// Requires: this == Isolate::GetCurrent(). /// [Notes] /// This is equivalent to deiniting an Isolate Scope. pub fn exit(self: *Self) void { c.v8__Isolate__Exit(self.handle); } pub fn getCurrentContext(self: Self) Context { return .{ .handle = c.v8__Isolate__GetCurrentContext(self.handle).?, }; } /// It seems stack trace is only captured if the value is wrapped in an Exception.initError. pub fn throwException(self: Self, value: anytype) Value { return .{ .handle = c.v8__Isolate__ThrowException(self.handle, getValueHandle(value)).?, }; } /// [V8] /// Set callback to notify about promise reject with no handler, or /// revocation of such a previous notification once the handler is added. pub fn setPromiseRejectCallback(self: Self, callback: c.PromiseRejectCallback) void { c.v8__Isolate__SetPromiseRejectCallback(self.handle, callback); } pub fn getMicrotasksPolicy(self: Self) c.MicrotasksPolicy { return c.v8__Isolate__GetMicrotasksPolicy(self.handle); } pub fn setMicrotasksPolicy(self: Self, policy: c.MicrotasksPolicy) void { c.v8__Isolate__SetMicrotasksPolicy(self.handle, policy); } pub fn performMicrotasksCheckpoint(self: Self) void { c.v8__Isolate__PerformMicrotaskCheckpoint(self.handle); } pub fn addMessageListener(self: Self, callback: c.MessageCallback) bool { return c.v8__Isolate__AddMessageListener(self.handle, callback); } pub fn addMessageListenerWithErrorLevel(self: Self, callback: c.MessageCallback, message_levels: c_int, value: Value) bool { return c.v8__Isolate__AddMessageListenerWithErrorLevel(self.handle, callback, message_levels, value.handle); } /// [v8] /// Tells V8 to capture current stack trace when uncaught exception occurs /// and report it to the message listeners. The option is off by default. pub fn setCaptureStackTraceForUncaughtExceptions(self: Self, capture: bool, frame_limit: u32) void { c.v8__Isolate__SetCaptureStackTraceForUncaughtExceptions(self.handle, capture, @intCast(c_int, frame_limit)); } /// This does not terminate the current script immediately. V8 will mark it for termination at a later time. This was intended to end long running loops. pub fn terminateExecution(self: Self) void { c.v8__Isolate__TerminateExecution(self.handle); } pub fn isExecutionTerminating(self: Self) bool { return c.v8__Isolate__IsExecutionTerminating(self.handle); } pub fn cancelTerminateExecution(self: Self) void { c.v8__Isolate__CancelTerminateExecution(self.handle); } pub fn lowMemoryNotification(self: Self) void { c.v8__Isolate__LowMemoryNotification(self.handle); } pub fn getHeapStatistics(self: Self) c.HeapStatistics { var res: c.HeapStatistics = undefined; c.v8__Isolate__GetHeapStatistics(self.handle, &res); return res; } pub fn initNumber(self: Self, val: f64) Number { return Number.init(self, val); } pub fn initNumberBitCastedU64(self: Self, val: u64) Number { return Number.initBitCastedU64(self, val); } pub fn initBoolean(self: Self, val: bool) Boolean { return Boolean.init(self, val); } pub fn initIntegerI32(self: Self, val: i32) Integer { return Integer.initI32(self, val); } pub fn initIntegerU32(self: Self, val: u32) Integer { return Integer.initU32(self, val); } pub fn initBigIntI64(self: Self, val: i64) BigInt { return BigInt.initI64(self, val); } pub fn initBigIntU64(self: Self, val: u64) BigInt { return BigInt.initU64(self, val); } pub fn initStringUtf8(self: Self, val: []const u8) String { return String.initUtf8(self, val); } pub fn initPersistent(self: Self, comptime T: type, val: T) Persistent(T) { return Persistent(T).init(self, val); } pub fn initFunctionTemplateDefault(self: Self) FunctionTemplate { return FunctionTemplate.initDefault(self); } pub fn initFunctionTemplateCallback(self: Self, callback: c.FunctionCallback) FunctionTemplate { return FunctionTemplate.initCallback(self, callback); } pub fn initFunctionTemplateCallbackData(self: Self, callback: c.FunctionCallback, data_value: anytype) FunctionTemplate { return FunctionTemplate.initCallbackData(self, callback, data_value); } pub fn initObjectTemplateDefault(self: Self) ObjectTemplate { return ObjectTemplate.initDefault(self); } pub fn initObjectTemplate(self: Self, constructor: FunctionTemplate) ObjectTemplate { return ObjectTemplate.init(self, constructor); } pub fn initObject(self: Self) Object { return Object.init(self); } pub fn initArray(self: Self, len: u32) Array { return Array.init(self, len); } pub fn initArrayElements(self: Self, elems: []const Value) Array { return Array.initElements(self, elems); } pub fn initUndefined(self: Self) Primitive { return Root.initUndefined(self); } pub fn initNull(self: Self) Primitive { return Root.initNull(self); } pub fn initTrue(self: Self) Boolean { return Root.initTrue(self); } pub fn initFalse(self: Self) Boolean { return Root.initFalse(self); } pub fn initContext(self: Self, global_tmpl: ?ObjectTemplate, global_obj: ?*c.Value) Context { return Context.init(self, global_tmpl, global_obj); } pub fn initExternal(self: Self, val: ?*anyopaque) External { return External.init(self, val); } }; pub const HandleScope = struct { const Self = @This(); inner: c.HandleScope, /// [Notes] /// This starts a new stack frame to record local objects created. /// Since deinit depends on the inner pointer being the same, init should construct in place. pub fn init(self: *Self, isolate: Isolate) void { c.v8__HandleScope__CONSTRUCT(&self.inner, isolate.handle); } /// [Notes] /// This pops the scope frame and allows V8 to mark/free local objects created since HandleScope.init. /// In C++ code, this would happen automatically when the HandleScope var leaves the current scope. pub fn deinit(self: *Self) void { c.v8__HandleScope__DESTRUCT(&self.inner); } }; pub const Context = struct { const Self = @This(); handle: *const c.Context, /// [V8] /// Creates a new context and returns a handle to the newly allocated /// context. /// /// \param isolate The isolate in which to create the context. /// /// \param extensions An optional extension configuration containing /// the extensions to be installed in the newly created context. /// /// \param global_template An optional object template from which the /// global object for the newly created context will be created. /// /// \param global_object An optional global object to be reused for /// the newly created context. This global object must have been /// created by a previous call to Context::New with the same global /// template. The state of the global object will be completely reset /// and only object identify will remain. pub fn init(isolate: Isolate, global_tmpl: ?ObjectTemplate, global_obj: ?*c.Value) Self { return .{ .handle = c.v8__Context__New(isolate.handle, if (global_tmpl != null) global_tmpl.?.handle else null, global_obj).?, }; } /// [V8] /// Enter this context. After entering a context, all code compiled /// and run is compiled and run in this context. If another context /// is already entered, this old context is saved so it can be /// restored when the new context is exited. pub fn enter(self: Self) void { c.v8__Context__Enter(self.handle); } /// [V8] /// Exit this context. Exiting the current context restores the /// context that was in place when entering the current context. pub fn exit(self: Self) void { c.v8__Context__Exit(self.handle); } /// [V8] /// Returns the isolate associated with a current context. pub fn getIsolate(self: Self) Isolate { return Isolate{ .handle = c.v8__Context__GetIsolate(self.handle).?, }; } pub fn getGlobal(self: Self) Object { return .{ .handle = c.v8__Context__Global(self.handle).?, }; } pub fn getEmbedderData(self: Self, idx: u32) Value { return .{ .handle = c.v8__Context__GetEmbedderData(self.handle, @intCast(c_int, idx)).?, }; } pub fn setEmbedderData(self: Self, idx: u32, val: anytype) void { c.v8__Context__SetEmbedderData(self.handle, @intCast(c_int, idx), getValueHandle(val)); } }; pub const PropertyCallbackInfo = struct { const Self = @This(); handle: *const c.PropertyCallbackInfo, pub fn initFromV8(val: ?*const c.PropertyCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__PropertyCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getReturnValue(self: Self) ReturnValue { var res: c.ReturnValue = undefined; c.v8__PropertyCallbackInfo__GetReturnValue(self.handle, &res); return .{ .inner = res, }; } pub fn getThis(self: Self) Object { return .{ .handle = c.v8__PropertyCallbackInfo__This(self.handle).?, }; } pub fn getData(self: Self) Value { return .{ .handle = c.v8__PropertyCallbackInfo__Data(self.handle).?, }; } pub fn getExternalValue(self: Self) ?*anyopaque { return self.getData().castTo(External).get(); } }; pub const WeakCallbackInfo = struct { const Self = @This(); handle: *const c.WeakCallbackInfo, pub fn initFromC(val: ?*const c.WeakCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__WeakCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getParameter(self: Self) *anyopaque { return c.v8__WeakCallbackInfo__GetParameter(self.handle).?; } pub fn getInternalField(self: Self, idx: u32) ?*anyopaque { return c.v8__WeakCallbackInfo__GetInternalField(self.handle, @intCast(c_int, idx)); } }; pub const PromiseRejectMessage = struct { const Self = @This(); inner: c.PromiseRejectMessage, pub fn initFromC(val: c.PromiseRejectMessage) Self { return .{ .inner = val, }; } pub fn getEvent(self: Self) c.PromiseRejectEvent { return c.v8__PromiseRejectMessage__GetEvent(&self.inner); } pub fn getPromise(self: Self) Promise { return .{ .handle = c.v8__PromiseRejectMessage__GetPromise(&self.inner).?, }; } pub fn getValue(self: Self) Value { return .{ .handle = c.v8__PromiseRejectMessage__GetValue(&self.inner).?, }; } }; pub const FunctionCallbackInfo = struct { const Self = @This(); handle: *const c.FunctionCallbackInfo, pub fn initFromV8(val: ?*const c.FunctionCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn length(self: Self) u32 { return @intCast(u32, c.v8__FunctionCallbackInfo__Length(self.handle)); } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__FunctionCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getArg(self: Self, i: u32) Value { return .{ .handle = c.v8__FunctionCallbackInfo__INDEX(self.handle, @intCast(c_int, i)).?, }; } pub fn getReturnValue(self: Self) ReturnValue { var res: c.ReturnValue = undefined; c.v8__FunctionCallbackInfo__GetReturnValue(self.handle, &res); return .{ .inner = res, }; } pub fn getThis(self: Self) Object { return .{ .handle = c.v8__FunctionCallbackInfo__This(self.handle).?, }; } pub fn getData(self: Self) Value { return .{ .handle = c.v8__FunctionCallbackInfo__Data(self.handle).?, }; } pub fn getExternalValue(self: Self) ?*anyopaque { return self.getData().castTo(External).get(); } }; pub const ReturnValue = struct { const Self = @This(); inner: c.ReturnValue, pub fn set(self: Self, value: anytype) void { c.v8__ReturnValue__Set(self.inner, getValueHandle(value)); } pub fn setValueHandle(self: Self, ptr: *const c.Value) void { c.v8__ReturnValue__Set(self.inner, ptr); } pub fn get(self: Self) Value { return .{ .handle = c.v8__ReturnValue__Get(self.inner).?, }; } }; pub const FunctionTemplate = struct { const Self = @This(); handle: *const c.FunctionTemplate, pub fn initDefault(isolate: Isolate) Self { return .{ .handle = c.v8__FunctionTemplate__New__DEFAULT(isolate.handle).?, }; } pub fn initCallback(isolate: Isolate, callback: c.FunctionCallback) Self { return .{ .handle = c.v8__FunctionTemplate__New__DEFAULT2(isolate.handle, callback).?, }; } pub fn initCallbackData(isolate: Isolate, callback: c.FunctionCallback, data_val: anytype) Self { return .{ .handle = c.v8__FunctionTemplate__New__DEFAULT3(isolate.handle, callback, getValueHandle(data_val)).?, }; } /// This is typically used to set class fields. pub fn getInstanceTemplate(self: Self) ObjectTemplate { return .{ .handle = c.v8__FunctionTemplate__InstanceTemplate(self.handle).?, }; } /// This is typically used to set class methods. pub fn getPrototypeTemplate(self: Self) ObjectTemplate { return .{ .handle = c.v8__FunctionTemplate__PrototypeTemplate(self.handle).?, }; } /// There is only one unique function for a FunctionTemplate in a given context. /// The Function can then be used to invoke NewInstance which is equivalent to doing js "new". pub fn getFunction(self: Self, ctx: Context) Function { return .{ .handle = c.v8__FunctionTemplate__GetFunction(self.handle, ctx.handle).?, }; } /// Sets static property on the template. pub fn set(self: Self, key: anytype, value: anytype, attr: c.PropertyAttribute) void { c.v8__Template__Set(getTemplateHandle(self), getNameHandle(key), getDataHandle(value), attr); } pub fn setGetter(self: Self, name: anytype, getter: FunctionTemplate) void { c.v8__Template__SetAccessorProperty__DEFAULT(getTemplateHandle(self), getNameHandle(name), getter.handle); } pub fn setClassName(self: Self, name: String) void { c.v8__FunctionTemplate__SetClassName(self.handle, name.handle); } pub fn setReadOnlyPrototype(self: Self) void { c.v8__FunctionTemplate__ReadOnlyPrototype(self.handle); } }; pub const Function = struct { const Self = @This(); handle: *const c.Function, /// Internally, this will create a temporary FunctionTemplate to get a new Function instance. pub fn initDefault(ctx: Context, callback: c.FunctionCallback) Self { return .{ .handle = c.v8__Function__New__DEFAULT(ctx.handle, callback).?, }; } pub fn initWithData(ctx: Context, callback: c.FunctionCallback, data_val: anytype) Self { return .{ .handle = c.v8__Function__New__DEFAULT2(ctx.handle, callback, getValueHandle(data_val)).?, }; } /// receiver_val is "this" in the function context. This is equivalent to calling fn.apply(receiver, args) in JS. /// Returns null if there was an error. pub fn call(self: Self, ctx: Context, receiver_val: anytype, args: []const Value) ?Value { const c_args = @ptrCast(?[*]const ?*c.Value, args.ptr); if (c.v8__Function__Call(self.handle, ctx.handle, getValueHandle(receiver_val), @intCast(c_int, args.len), c_args)) |ret| { return Value{ .handle = ret, }; } else return null; } // Equavalent to js "new". pub fn initInstance(self: Self, ctx: Context, args: []const Value) ?Object { const c_args = @ptrCast(?[*]const ?*c.Value, args.ptr); if (c.v8__Function__NewInstance(self.handle, ctx.handle, @intCast(c_int, args.len), c_args)) |ret| { return Object{ .handle = ret, }; } else return null; } pub fn toObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } pub fn getName(self: Self) Value { return .{ .handle = c.v8__Function__GetName(self.handle).?, }; } pub fn setName(self: Self, name: String) void { c.v8__Function__SetName(self.handle, name.handle); } }; pub fn Persistent(comptime T: type) type { return struct { const Self = @This(); inner: T, /// A new value is created that references the original value. /// A Persistent handle is a pointer just like any other value handles, /// but when creating and operating on it, an indirect pointer is used to represent a c.Persistent struct (v8::Persistent<v8::Value> in C++). pub fn init(isolate: Isolate, data: T) Self { var handle: *c.Data = undefined; c.v8__Persistent__New(isolate.handle, getDataHandle(data), @ptrCast(*c.Persistent, &handle)); return .{ .inner = .{ .handle = @ptrCast(@TypeOf(data.handle), handle), }, }; } pub fn deinit(self: *Self) void { c.v8__Persistent__Reset(@ptrCast(*c.Persistent, &self.inner.handle)); } pub fn setWeak(self: *Self) void { c.v8__Persistent__SetWeak(@ptrCast(*c.Persistent, &self.inner.handle)); } /// An external pointer can be set when cb_type is kParameter or kInternalFields. /// When cb_type is kInternalFields, the object fields are expected to be set with setAlignedPointerInInternalField. /// The pointer value must be a multiple of 2 due to how v8 encodes the pointers. pub fn setWeakFinalizer(self: *Self, finalizer_ctx: *anyopaque, cb: c.WeakCallback, cb_type: WeakCallbackType) void { c.v8__Persistent__SetWeakFinalizer(@ptrCast(*c.Persistent, &self.inner.handle), finalizer_ctx, cb, @enumToInt(cb_type)); } /// Should only be called if you know the underlying type is a v8.Function. pub fn castToFunction(self: Self) Function { return .{ .handle = @ptrCast(*const c.Function, self.inner.handle), }; } /// Should only be called if you know the underlying type is a v8.Object. pub fn castToObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.inner.handle), }; } /// Should only be called if you know the underlying type is a v8.PromiseResolver. pub fn castToPromiseResolver(self: Self) PromiseResolver { return .{ .handle = @ptrCast(*const c.PromiseResolver, self.inner.handle), }; } pub fn toValue(self: Self) Value { return .{ .handle = self.inner.handle, }; } }; } /// [V8] /// kParameter will pass a void* parameter back to the callback, kInternalFields /// will pass the first two internal fields back to the callback, kFinalizer /// will pass a void* parameter back, but is invoked before the object is /// actually collected, so it can be resurrected. In the last case, it is not /// possible to request a second pass callback. pub const WeakCallbackType = enum(u32) { kParameter = c.kParameter, kInternalFields = c.kInternalFields, kFinalizer = c.kFinalizer, }; pub const ObjectTemplate = struct { const Self = @This(); handle: *const c.ObjectTemplate, pub fn initDefault(isolate: Isolate) Self { return .{ .handle = c.v8__ObjectTemplate__New__DEFAULT(isolate.handle).?, }; } pub fn init(isolate: Isolate, constructor: FunctionTemplate) Self { return .{ .handle = c.v8__ObjectTemplate__New(isolate.handle, constructor.handle).?, }; } pub fn initInstance(self: Self, ctx: Context) Object { return .{ .handle = c.v8__ObjectTemplate__NewInstance(self.handle, ctx.handle).?, }; } pub fn setGetter(self: Self, name: anytype, getter: c.AccessorNameGetterCallback) void { c.v8__ObjectTemplate__SetAccessor__DEFAULT(self.handle, getNameHandle(name), getter); } pub fn setGetterAndSetter(self: Self, name: anytype, getter: c.AccessorNameGetterCallback, setter: c.AccessorNameSetterCallback) void { c.v8__ObjectTemplate__SetAccessor__DEFAULT2(self.handle, getNameHandle(name), getter, setter); } pub fn set(self: Self, key: anytype, value: anytype, attr: c.PropertyAttribute) void { c.v8__Template__Set(getTemplateHandle(self), getNameHandle(key), getDataHandle(value), attr); } pub fn setInternalFieldCount(self: Self, count: u32) void { c.v8__ObjectTemplate__SetInternalFieldCount(self.handle, @intCast(c_int, count)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Array = struct { const Self = @This(); handle: *const c.Array, pub fn init(iso: Isolate, len: u32) Self { return .{ .handle = c.v8__Array__New(iso.handle, @intCast(c_int, len)).?, }; } pub fn initElements(iso: Isolate, elems: []const Value) Self { const c_elems = @ptrCast(?[*]const ?*c.Value, elems.ptr); return .{ .handle = c.v8__Array__New2(iso.handle, c_elems, elems.len).?, }; } pub fn length(self: Self) u32 { return c.v8__Array__Length(self.handle); } pub fn castTo(self: Self, comptime T: type) T { switch (T) { Object => { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; }, else => unreachable, } } }; pub const Object = struct { const Self = @This(); handle: *const c.Object, pub fn init(isolate: Isolate) Self { return .{ .handle = c.v8__Object__New(isolate.handle).?, }; } pub fn setInternalField(self: Self, idx: u32, value: anytype) void { c.v8__Object__SetInternalField(self.handle, @intCast(c_int, idx), getValueHandle(value)); } pub fn getInternalField(self: Self, idx: u32) Value { return .{ .handle = c.v8__Object__GetInternalField(self.handle, @intCast(c_int, idx)).?, }; } pub fn setAlignedPointerInInternalField(self: Self, idx: u32, ptr: ?*anyopaque) void { c.v8__Object__SetAlignedPointerInInternalField(self.handle, @intCast(c_int, idx), ptr); } // Returns true on success, false on fail. pub fn setValue(self: Self, ctx: Context, key: anytype, value: anytype) bool { var out: c.MaybeBool = undefined; c.v8__Object__Set(self.handle, ctx.handle, getValueHandle(key), getValueHandle(value), &out); // Set only returns empty for an error or true. return out.has_value == 1; } pub fn getValue(self: Self, ctx: Context, key: anytype) !Value { if (c.v8__Object__Get(self.handle, ctx.handle, getValueHandle(key))) |handle| { return Value{ .handle = handle, }; } else return error.JsException; } pub fn getAtIndex(self: Self, ctx: Context, idx: u32) !Value { if (c.v8__Object__GetIndex(self.handle, ctx.handle, idx)) |handle| { return Value{ .handle = handle, }; } else return error.JsException; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } pub fn defineOwnProperty(self: Self, ctx: Context, name: anytype, value: anytype, attr: c.PropertyAttribute) ?bool { var out: c.MaybeBool = undefined; c.v8__Object__DefineOwnProperty(self.handle, ctx.handle, getNameHandle(name), getValueHandle(value), attr, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__Object__GetIsolate(self.handle).?, }; } pub fn getCreationContext(self: Self) Context { return .{ .handle = c.v8__Object__GetCreationContext(self.handle).?, }; } pub fn getIdentityHash(self: Self) u32 { return @bitCast(u32, c.v8__Object__GetIdentityHash(self.handle)); } pub fn has(self: Self, ctx: Context, key: Value) bool { var out: c.MaybeBool = undefined; c.v8__Object__Has(self.handle, ctx.handle, key.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return false; } pub fn hasIndex(self: Self, ctx: Context, idx: u32) bool { var out: c.MaybeBool = undefined; c.v8__Object__Has(self.handle, ctx.handle, idx, &out); if (out.has_value == 1) { return out.value == 1; } else return false; } pub fn getOwnPropertyNames(self: Self, ctx: Context) Array { return .{ .handle = c.v8__Object__GetOwnPropertyNames(self.handle, ctx.handle).?, }; } pub fn getPropertyNames(self: Self, ctx: Context) Array { return .{ .handle = c.v8__Object__GetPropertyNames(self.handle, ctx.handle).?, }; } }; pub const External = struct { const Self = @This(); handle: *const c.External, pub fn init(isolate: Isolate, val: ?*anyopaque) Self { return .{ .handle = c.v8__External__New(isolate.handle, val).?, }; } pub fn get(self: Self) ?*anyopaque { return c.v8__External__Value(self.handle); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Number = struct { const Self = @This(); handle: *const c.Number, pub fn init(isolate: Isolate, val: f64) Self { return .{ .handle = c.v8__Number__New(isolate.handle, val).?, }; } pub fn initBitCastedU64(isolate: Isolate, val: u64) Self { return init(isolate, @bitCast(f64, val)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Integer = struct { const Self = @This(); handle: *const c.Integer, pub fn initI32(isolate: Isolate, val: i32) Self { return .{ .handle = c.v8__Integer__New(isolate.handle, val).?, }; } pub fn initU32(isolate: Isolate, val: u32) Self { return .{ .handle = c.v8__Integer__NewFromUnsigned(isolate.handle, val).?, }; } pub fn getValue(self: Self) u64 { return c.v8__Integer__Value(self.handle); } pub fn getValueU32(self: Self) u32 { return @intCast(u32, c.v8__Integer__Value(self.handle)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const BigInt = struct { const Self = @This(); handle: *const c.Integer, pub fn initI64(iso: Isolate, val: i64) Self { return .{ .handle = c.v8__BigInt__New(iso.handle, val).?, }; } pub fn initU64(iso: Isolate, val: u64) Self { return .{ .handle = c.v8__BigInt__NewFromUnsigned(iso.handle, val).?, }; } pub fn getUint64(self: Self) u64 { return c.v8__BigInt__Uint64Value(self.handle, null); } pub fn getInt64(self: Self) i64 { return c.v8__BigInt__Int64Value(self.handle, null); } }; pub inline fn getValue(val: anytype) Value { return .{ .handle = getValueHandle(val), }; } inline fn getValueHandle(val: anytype) *const c.Value { return @ptrCast(*const c.Value, comptime switch (@TypeOf(val)) { Object => val.handle, Value => val.handle, String => val.handle, Integer => val.handle, Primitive => val.handle, Number => val.handle, Function => val.handle, PromiseResolver => val.handle, External => val.handle, Array => val.handle, Uint8Array => val.handle, StackTrace => val.handle, ObjectTemplate => val.handle, Persistent(Object) => val.inner.handle, Persistent(Value) => val.inner.handle, Persistent(String) => val.inner.handle, Persistent(Integer) => val.inner.handle, Persistent(Primitive) => val.inner.handle, Persistent(Number) => val.inner.handle, Persistent(PromiseResolver) => val.inner.handle, Persistent(Array) => val.inner.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Value", .{@typeName(@TypeOf(val))})), }); } inline fn getNameHandle(val: anytype) *const c.Name { return @ptrCast(*const c.Name, comptime switch (@TypeOf(val)) { *const c.String => val, String => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Name", .{@typeName(@TypeOf(val))})), }); } inline fn getTemplateHandle(val: anytype) *const c.Template { return @ptrCast(*const c.Template, comptime switch (@TypeOf(val)) { FunctionTemplate => val.handle, ObjectTemplate => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Template", .{@typeName(@TypeOf(val))})), }); } inline fn getDataHandle(val: anytype) *const c.Data { return @ptrCast(*const c.Data, comptime switch (@TypeOf(val)) { FunctionTemplate => val.handle, ObjectTemplate => val.handle, Integer => val.handle, Function => val.handle, Context => val.handle, Object => val.handle, Value => val.handle, Module => val.handle, Promise => val.handle, PromiseResolver => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Data", .{@typeName(@TypeOf(val))})), }); } pub const Message = struct { const Self = @This(); handle: *const c.Message, pub fn getMessage(self: Self) String { return String{ .handle = c.v8__Message__Get(self.handle).?, }; } pub fn getSourceLine(self: Self, ctx: Context) ?String { if (c.v8__Message__GetSourceLine(self.handle, ctx.handle)) |string| { return String{ .handle = string, }; } else return null; } pub fn getScriptResourceName(self: Self) Value { return .{ .handle = c.v8__Message__GetScriptResourceName(self.handle).?, }; } pub fn getLineNumber(self: Self, ctx: Context) ?u32 { const res = c.v8__Message__GetLineNumber(self.handle, ctx.handle); if (res != -1) { return @intCast(u32, res); } else return null; } pub fn getStartColumn(self: Self) ?u32 { const res = c.v8__Message__GetStartColumn(self.handle); if (res != -1) { return @intCast(u32, res); } else return null; } pub fn getEndColumn(self: Self) ?u32 { const res = c.v8__Message__GetEndColumn(self.handle); if (res != -1) { return @intCast(u32, res); } else return null; } /// [v8] Exception stack trace. By default stack traces are not captured for /// uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows /// to change this option. pub fn getStackTrace(self: Self) ?StackTrace { if (c.v8__Message__GetStackTrace(self.handle)) |trace| { return StackTrace{ .handle = trace, }; } else return null; } }; pub const StackTrace = struct { const Self = @This(); handle: *const c.StackTrace, pub fn getFrameCount(self: Self) u32 { return @intCast(u32, c.v8__StackTrace__GetFrameCount(self.handle)); } pub fn getFrame(self: Self, iso: Isolate, idx: u32) StackFrame { return .{ .handle = c.v8__StackTrace__GetFrame(self.handle, iso.handle, idx).?, }; } pub fn getCurrentStackTrace(iso: Isolate, frame_limit: u32) StackTrace { return .{ .handle = c.v8__StackTrace__CurrentStackTrace__STATIC(iso.handle, @intCast(c_int, frame_limit)).?, }; } pub fn getCurrentScriptNameOrSourceUrl(iso: Isolate) String { return .{ .handle = c.v8__StackTrace__CurrentScriptNameOrSourceURL__STATIC(iso.handle).?, }; } }; pub const StackFrame = struct { const Self = @This(); handle: *const c.StackFrame, pub fn getLineNumber(self: Self) u32 { return @intCast(u32, c.v8__StackFrame__GetLineNumber(self.handle)); } pub fn getColumn(self: Self) u32 { return @intCast(u32, c.v8__StackFrame__GetColumn(self.handle)); } pub fn getScriptId(self: Self) u32 { return @intCast(u32, c.v8__StackFrame__GetScriptId(self.handle)); } pub fn getScriptName(self: Self) String { return .{ .handle = c.v8__StackFrame__GetScriptName(self.handle).?, }; } pub fn getScriptNameOrSourceUrl(self: Self) String { return .{ .handle = c.v8__StackFrame__GetScriptNameOrSourceURL(self.handle).?, }; } pub fn getFunctionName(self: Self) ?String { if (c.v8__StackFrame__GetFunctionName(self.handle)) |ptr| { return String{ .handle = ptr, }; } else return null; } pub fn isEval(self: Self) bool { return c.v8__StackFrame__IsEval(self.handle); } pub fn isConstructor(self: Self) bool { return c.v8__StackFrame__IsConstructor(self.handle); } pub fn isWasm(self: Self) bool { return c.v8__StackFrame__IsWasm(self.handle); } pub fn isUserJavascript(self: Self) bool { return c.v8__StackFrame__IsUserJavaScript(self.handle); } }; pub const TryCatch = struct { const Self = @This(); inner: c.TryCatch, // TryCatch is wrapped in a v8::Local so have to initialize in place. pub fn init(self: *Self, isolate: Isolate) void { c.v8__TryCatch__CONSTRUCT(&self.inner, isolate.handle); } pub fn deinit(self: *Self) void { c.v8__TryCatch__DESTRUCT(&self.inner); } pub fn hasCaught(self: Self) bool { return c.v8__TryCatch__HasCaught(&self.inner); } pub fn getException(self: Self) ?Value { if (c.v8__TryCatch__Exception(&self.inner)) |exception| { return Value{ .handle = exception, }; } else return null; } pub fn getStackTrace(self: Self, ctx: Context) ?Value { if (c.v8__TryCatch__StackTrace(&self.inner, ctx.handle)) |value| { return Value{ .handle = value, }; } else return null; } pub fn getMessage(self: Self) ?Message { if (c.v8__TryCatch__Message(&self.inner)) |message| { return Message{ .handle = message, }; } else return null; } pub fn isVerbose(self: Self) bool { return c.v8__TryCatch__IsVerbose(&self.inner); } pub fn setVerbose(self: *Self, verbose: bool) void { c.v8__TryCatch__SetVerbose(&self.inner, verbose); } pub fn rethrow(self: *Self) Value { return .{ .handle = c.v8__TryCatch__ReThrow(&self.inner).?, }; } }; pub const ScriptOrigin = struct { const Self = @This(); inner: c.ScriptOrigin, pub fn initDefault(isolate: Isolate, resource_name: Value) Self { var inner: c.ScriptOrigin = undefined; c.v8__ScriptOrigin__CONSTRUCT(&inner, isolate.handle, resource_name.handle); return .{ .inner = inner, }; } pub fn init( isolate: Isolate, resource_name: Value, resource_line_offset: i32, resource_column_offset: i32, resource_is_shared_cross_origin: bool, script_id: i32, source_map_url: ?Value, resource_is_opaque: bool, is_wasm: bool, is_module: bool, host_defined_options: ?Data, ) Self { var inner: c.ScriptOrigin = undefined; c.v8__ScriptOrigin__CONSTRUCT2( &inner, isolate.handle, resource_name.handle, resource_line_offset, resource_column_offset, resource_is_shared_cross_origin, script_id, if (source_map_url != null) source_map_url.?.handle else null, resource_is_opaque, is_wasm, is_module, if (host_defined_options != null) host_defined_options.?.handle else null, ); return .{ .inner = inner, }; } }; pub const Boolean = struct { const Self = @This(); handle: *const c.Boolean, pub fn init(isolate: Isolate, val: bool) Self { return .{ .handle = c.v8__Boolean__New(isolate.handle, val).?, }; } }; pub const String = struct { const Self = @This(); handle: *const c.String, pub fn initUtf8(isolate: Isolate, str: []const u8) Self { return .{ .handle = c.v8__String__NewFromUtf8(isolate.handle, str.ptr, c.kNormal, @intCast(c_int, str.len)).?, }; } pub fn lenUtf8(self: Self, isolate: Isolate) u32 { return @intCast(u32, c.v8__String__Utf8Length(self.handle, isolate.handle)); } pub fn writeUtf8(self: String, isolate: Isolate, buf: []const u8) u32 { const options = c.NO_NULL_TERMINATION | c.REPLACE_INVALID_UTF8; // num chars is how many utf8 characters are actually written and the function returns how many bytes were written. var nchars: c_int = 0; // TODO: Return num chars return @intCast(u32, c.v8__String__WriteUtf8(self.handle, isolate.handle, buf.ptr, @intCast(c_int, buf.len), &nchars, options)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const ScriptCompilerSource = struct { const Self = @This(); inner: c.ScriptCompilerSource, pub fn init(self: *Self, src: String, mb_origin: ?ScriptOrigin, cached_data: ?ScriptCompilerCachedData) void { const cached_data_ptr = if (cached_data != null) cached_data.?.handle else null; if (mb_origin) |origin| { c.v8__ScriptCompiler__Source__CONSTRUCT2(src.handle, &origin.inner, cached_data_ptr, &self.inner); } else { c.v8__ScriptCompiler__Source__CONSTRUCT(src.handle, cached_data_ptr, &self.inner); } } pub fn deinit(self: *Self) void { c.v8__ScriptCompiler__Source__DESTRUCT(&self.inner); } }; pub const ScriptCompilerCachedData = struct { const Self = @This(); handle: *c.ScriptCompilerCachedData, pub fn init(data: []const u8) Self { return .{ .handle = c.v8__ScriptCompiler__CachedData__NEW(data.ptr, @intCast(c_int, data.len)).?, }; } pub fn deinit(self: Self) void { c.v8__ScriptCompiler__CachedData__DELETE(self.handle); } }; pub const ScriptCompiler = struct { const CompileOptions = enum(u32) { kNoCompileOptions = c.kNoCompileOptions, kConsumeCodeCache = c.kConsumeCodeCache, kEagerCompile = c.kEagerCompile, }; const NoCacheReason = enum(u32) { kNoCacheNoReason = c.kNoCacheNoReason, kNoCacheBecauseCachingDisabled = c.kNoCacheBecauseCachingDisabled, kNoCacheBecauseNoResource = c.kNoCacheBecauseNoResource, kNoCacheBecauseInlineScript = c.kNoCacheBecauseInlineScript, kNoCacheBecauseModule = c.kNoCacheBecauseModule, kNoCacheBecauseStreamingSource = c.kNoCacheBecauseStreamingSource, kNoCacheBecauseInspector = c.kNoCacheBecauseInspector, kNoCacheBecauseScriptTooSmall = c.kNoCacheBecauseScriptTooSmall, kNoCacheBecauseCacheTooCold = c.kNoCacheBecauseCacheTooCold, kNoCacheBecauseV8Extension = c.kNoCacheBecauseV8Extension, kNoCacheBecauseExtensionModule = c.kNoCacheBecauseExtensionModule, kNoCacheBecausePacScript = c.kNoCacheBecausePacScript, kNoCacheBecauseInDocumentWrite = c.kNoCacheBecauseInDocumentWrite, kNoCacheBecauseResourceWithNoCacheHandler = c.kNoCacheBecauseResourceWithNoCacheHandler, kNoCacheBecauseDeferredProduceCodeCache = c.kNoCacheBecauseDeferredProduceCodeCache, }; /// [v8] /// Compile an ES module, returning a Module that encapsulates the compiled code. /// Corresponds to the ParseModule abstract operation in the ECMAScript specification. pub fn compileModule(iso: Isolate, src: *ScriptCompilerSource, options: ScriptCompiler.CompileOptions, reason: ScriptCompiler.NoCacheReason) !Module { const mb_res = c.v8__ScriptCompiler__CompileModule( iso.handle, &src.inner, @enumToInt(options), @enumToInt(reason), ); if (mb_res) |res| { return Module{ .handle = res, }; } else return error.JsException; } }; pub const Script = struct { const Self = @This(); handle: *const c.Script, /// [v8] /// A shorthand for ScriptCompiler::Compile(). pub fn compile(ctx: Context, src: String, origin: ?ScriptOrigin) !Self { if (c.v8__Script__Compile(ctx.handle, src.handle, if (origin != null) &origin.?.inner else null)) |handle| { return Self{ .handle = handle, }; } else return error.JsException; } pub fn run(self: Self, ctx: Context) !Value { if (c.v8__Script__Run(self.handle, ctx.handle)) |value| { return Value{ .handle = value, }; } else return error.JsException; } }; pub const Module = struct { const Self = @This(); const Status = enum(u32) { kUninstantiated = c.kUninstantiated, kInstantiating = c.kInstantiating, kInstantiated = c.kInstantiated, kEvaluating = c.kEvaluating, kEvaluated = c.kEvaluated, kErrored = c.kErrored, }; handle: *const c.Module, pub fn getStatus(self: Self) Status { return @intToEnum(Status, c.v8__Module__GetStatus(self.handle)); } pub fn getException(self: Self) Value { return .{ .handle = c.v8__Module__GetException(self.handle).?, }; } pub fn getModuleRequests(self: Self) FixedArray { return .{ .handle = c.v8__Module__GetModuleRequests(self.handle).?, }; } /// [v8] /// Instantiates the module and its dependencies. /// /// Returns an empty Maybe<bool> if an exception occurred during /// instantiation. (In the case where the callback throws an exception, that /// exception is propagated.) pub fn instantiate(self: Self, ctx: Context, cb: c.ResolveModuleCallback) !bool { var out: c.MaybeBool = undefined; c.v8__Module__InstantiateModule(self.handle, ctx.handle, cb, &out); if (out.has_value == 1) { return out.value == 1; } else return error.JsException; } /// Evaulates the module, assumes module has been instantiated. /// [v8] /// Evaluates the module and its dependencies. /// /// If status is kInstantiated, run the module's code and return a Promise /// object. On success, set status to kEvaluated and resolve the Promise with /// the completion value; on failure, set status to kErrored and reject the /// Promise with the error. /// /// If IsGraphAsync() is false, the returned Promise is settled. pub fn evaluate(self: Self, ctx: Context) !Value { if (c.v8__Module__Evaluate(self.handle, ctx.handle)) |res| { return Value{ .handle = res, }; } else return error.JsException; } pub fn getIdentityHash(self: Self) u32 { return @bitCast(u32, c.v8__Module__GetIdentityHash(self.handle)); } pub fn getScriptId(self: Self) u32 { return @intCast(u32, c.v8__Module__ScriptId(self.handle)); } }; pub const ModuleRequest = struct { const Self = @This(); handle: *const c.ModuleRequest, /// Returns the specifier of the import inside the double quotes pub fn getSpecifier(self: Self) String { return .{ .handle = c.v8__ModuleRequest__GetSpecifier(self.handle).?, }; } /// Returns the offset from the start of the source code. pub fn getSourceOffset(self: Self) u32 { return @intCast(u32, c.v8__ModuleRequest__GetSourceOffset(self.handle)); } }; pub const Data = struct { const Self = @This(); handle: *const c.Data, /// Should only be called if you know the underlying type. pub fn castTo(self: Self, comptime T: type) T { switch (T) { ModuleRequest => { return .{ .handle = self.handle, }; }, else => unreachable, } } }; pub const Value = struct { const Self = @This(); handle: *const c.Value, pub fn toString(self: Self, ctx: Context) !String { return String{ .handle = c.v8__Value__ToString(self.handle, ctx.handle) orelse return error.JsException, }; } pub fn toDetailString(self: Self, ctx: Context) !String { return String{ .handle = c.v8__Value__ToDetailString(self.handle, ctx.handle) orelse return error.JsException, }; } pub fn toBool(self: Self, isolate: Isolate) bool { return c.v8__Value__BooleanValue(self.handle, isolate.handle); } pub fn toI32(self: Self, ctx: Context) !i32 { var out: c.MaybeI32 = undefined; c.v8__Value__Int32Value(self.handle, ctx.handle, &out); if (out.has_value == 1) { return out.value; } else return error.JsException; } pub fn toU32(self: Self, ctx: Context) !u32 { var out: c.MaybeU32 = undefined; c.v8__Value__Uint32Value(self.handle, ctx.handle, &out); if (out.has_value == 1) { return out.value; } else return error.JsException; } pub fn toF32(self: Self, ctx: Context) !f32 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return @floatCast(f32, out.value); } else return error.JsException; } pub fn toF64(self: Self, ctx: Context) !f64 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return out.value; } else return error.JsException; } pub fn bitCastToU64(self: Self, ctx: Context) !u64 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return @bitCast(u64, out.value); } else return error.JsException; } pub fn instanceOf(self: Self, ctx: Context, obj: Object) !bool { var out: c.MaybeBool = undefined; c.v8__Value__InstanceOf(self.handle, ctx.handle, obj.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return error.JsException; } pub fn isObject(self: Self) bool { return c.v8__Value__IsObject(self.handle); } pub fn isString(self: Self) bool { return c.v8__Value__IsString(self.handle); } pub fn isFunction(self: Self) bool { return c.v8__Value__IsFunction(self.handle); } pub fn isAsyncFunction(self: Self) bool { return c.v8__Value__IsAsyncFunction(self.handle); } pub fn isArray(self: Self) bool { return c.v8__Value__IsArray(self.handle); } pub fn isArrayBuffer(self: Self) bool { return c.v8__Value__IsArrayBuffer(self.handle); } pub fn isArrayBufferView(self: Self) bool { return c.v8__Value__IsArrayBufferView(self.handle); } pub fn isUint8Array(self: Self) bool { return c.v8__Value__IsUint8Array(self.handle); } pub fn isExternal(self: Self) bool { return c.v8__Value__IsExternal(self.handle); } pub fn isTrue(self: Self) bool { return c.v8__Value__IsTrue(self.handle); } pub fn isFalse(self: Self) bool { return c.v8__Value__IsFalse(self.handle); } pub fn isUndefined(self: Self) bool { return c.v8__Value__IsUndefined(self.handle); } pub fn isNull(self: Self) bool { return c.v8__Value__IsNull(self.handle); } pub fn isNullOrUndefined(self: Self) bool { return c.v8__Value__IsNullOrUndefined(self.handle); } pub fn isNativeError(self: Self) bool { return c.v8__Value__IsNativeError(self.handle); } pub fn isBigInt(self: Self) bool { return c.v8__Value__IsBigInt(self.handle); } pub fn isBigIntObject(self: Self) bool { return c.v8__Value__IsBigIntObject(self.handle); } /// Should only be called if you know the underlying type. pub fn castTo(self: Self, comptime T: type) T { switch (T) { Object, Function, Array, Promise, External, Integer, ArrayBuffer, ArrayBufferView, Uint8Array, String => { return .{ .handle = self.handle, }; }, else => unreachable, } } }; pub const Primitive = struct { const Self = @This(); handle: *const c.Primitive, }; pub fn initUndefined(isolate: Isolate) Primitive { return .{ .handle = c.v8__Undefined(isolate.handle).?, }; } pub fn initNull(isolate: Isolate) Primitive { return .{ .handle = c.v8__Null(isolate.handle).?, }; } pub fn initTrue(isolate: Isolate) Boolean { return .{ .handle = c.v8__True(isolate.handle).?, }; } pub fn initFalse(isolate: Isolate) Boolean { return .{ .handle = c.v8__False(isolate.handle).?, }; } pub const Promise = struct { const Self = @This(); pub const State = enum(u32) { kPending = c.kPending, kFulfilled = c.kFulfilled, kRejected = c.kRejected, }; handle: *const c.Promise, /// [V8] /// Register a resolution/rejection handler with a promise. /// The handler is given the respective resolution/rejection value as /// an argument. If the promise is already resolved/rejected, the handler is /// invoked at the end of turn. pub fn onCatch(self: Self, ctx: Context, handler: Function) !Promise { if (c.v8__Promise__Catch(self.handle, ctx.handle, handler.handle)) |handle| { return Promise{ .handle = handle }; } else return error.JsException; } pub fn then(self: Self, ctx: Context, handler: Function) !Promise { if (c.v8__Promise__Then(self.handle, ctx.handle, handler.handle)) |handle| { return Promise{ .handle = handle }; } else return error.JsException; } pub fn thenAndCatch(self: Self, ctx: Context, on_fulfilled: Function, on_rejected: Function) !Promise { if (c.v8__Promise__Then2(self.handle, ctx.handle, on_fulfilled.handle, on_rejected.handle)) |handle| { return Promise{ .handle = handle }; } else return error.JsException; } pub fn getState(self: Self) State { return @intToEnum(State, c.v8__Promise__State(self.handle)); } /// [V8] /// Marks this promise as handled to avoid reporting unhandled rejections. pub fn markAsHandled(self: Self) void { c.v8__Promise__MarkAsHandled(self.handle); } pub fn toObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; } /// [V8] /// Returns the content of the [[PromiseResult]] field. The Promise must not be pending. pub fn getResult(self: Self) Value { return .{ .handle = c.v8__Promise__Result(self.handle).?, }; } }; pub const PromiseResolver = struct { const Self = @This(); handle: *const c.PromiseResolver, pub fn init(ctx: Context) Self { return .{ .handle = c.v8__Promise__Resolver__New(ctx.handle).?, }; } pub fn getPromise(self: Self) Promise { return .{ .handle = c.v8__Promise__Resolver__GetPromise(self.handle).?, }; } /// Resolve will continue execution of any yielding generators. pub fn resolve(self: Self, ctx: Context, val: Value) ?bool { var out: c.MaybeBool = undefined; c.v8__Promise__Resolver__Resolve(self.handle, ctx.handle, val.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } /// Reject will continue execution of any yielding generators. pub fn reject(self: Self, ctx: Context, val: Value) ?bool { var out: c.MaybeBool = undefined; c.v8__Promise__Resolver__Reject(self.handle, ctx.handle, val.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } }; pub const BackingStore = struct { const Self = @This(); handle: *c.BackingStore, /// Underlying handle is initially unmanaged. pub fn init(iso: Isolate, len: usize) Self { return .{ .handle = c.v8__ArrayBuffer__NewBackingStore(iso.handle, len).?, }; } /// Returns null if len is 0. pub fn getData(self: Self) ?*anyopaque { return c.v8__BackingStore__Data(self.handle); } pub fn getByteLength(self: Self) usize { return c.v8__BackingStore__ByteLength(self.handle); } pub fn isShared(self: Self) bool { return c.v8__BackingStore__IsShared(self.handle); } pub fn toSharedPtr(self: Self) SharedPtr { return c.v8__BackingStore__TO_SHARED_PTR(self.handle); } pub fn sharedPtrReset(ptr: *SharedPtr) void { c.std__shared_ptr__v8__BackingStore__reset(ptr); } pub fn sharedPtrGet(ptr: *const SharedPtr) Self { return .{ .handle = c.std__shared_ptr__v8__BackingStore__get(ptr).?, }; } pub fn sharedPtrUseCount(ptr: *const SharedPtr) u32 { return @intCast(u32, c.std__shared_ptr__v8__BackingStore__use_count(ptr)); } }; pub const ArrayBuffer = struct { const Self = @This(); handle: *const c.ArrayBuffer, pub fn init(iso: Isolate, len: usize) Self { return .{ .handle = c.v8__ArrayBuffer__New(iso.handle, len).?, }; } pub fn initWithBackingStore(iso: Isolate, store: *const SharedPtr) Self { return .{ .handle = c.v8__ArrayBuffer__New2(iso.handle, store).?, }; } pub fn getBackingStore(self: Self) SharedPtr { return c.v8__ArrayBuffer__GetBackingStore(self.handle); } }; pub const ArrayBufferView = struct { const Self = @This(); handle: *const c.ArrayBufferView, pub fn getBuffer(self: Self) ArrayBuffer { return .{ .handle = c.v8__ArrayBufferView__Buffer(self.handle).?, }; } pub fn castFrom(val: anytype) Self { switch (@TypeOf(val)) { Uint8Array => return .{ .handle = @ptrCast(*const c.ArrayBufferView, val.handle), }, else => unreachable, } } }; pub const FixedArray = struct { const Self = @This(); handle: *const c.FixedArray, pub fn length(self: Self) u32 { return @intCast(u32, c.v8__FixedArray__Length(self.handle)); } pub fn get(self: Self, ctx: Context, idx: u32) Data { return .{ .handle = c.v8__FixedArray__Get(self.handle, ctx.handle, @intCast(c_int, idx)).?, }; } }; pub const Uint8Array = struct { const Self = @This(); handle: *const c.Uint8Array, pub fn init(buf: ArrayBuffer, offset: usize, len: usize) Self { return .{ .handle = c.v8__Uint8Array__New(buf.handle, offset, len).?, }; } }; pub const Json = struct { pub fn parse(ctx: Context, json: String) !Value { return Value{ .handle = c.v8__JSON__Parse(ctx.handle, json.handle) orelse return error.JsException, }; } pub fn stringify(ctx: Context, val: Value, gap: ?String) !String { return String{ .handle = c.v8__JSON__Stringify(ctx.handle, val.handle, if (gap != null) gap.?.handle else null) orelse return error.JsException, }; } }; inline fn ptrCastAlign(comptime Ptr: type, ptr: anytype) Ptr { const alignment = @typeInfo(Ptr).Pointer.alignment; if (alignment == 0) { return @ptrCast(Ptr, ptr); } else { return @ptrCast(Ptr, @alignCast(alignment, ptr)); } } pub fn setDcheckFunction(func: fn (file: [*c]const u8, line: c_int, msg: [*c]const u8) callconv(.C) void) void { c.v8__base__SetDcheckFunction(func); }
src/v8.zig
const c = @cImport({ @cInclude("cfl_dialog.h"); }); pub const NativeFileDialogType = enum(i32) { /// Browse files BrowseFile = 0, /// Browse dir BrowseDir, /// Browse multiple files BrowseMultiFile, /// Browse multiple dirs BrowseMultiDir, /// Browse save file BrowseSaveFile, /// Browse save directory BrowseSaveDir, }; pub const NativeFileDialogOptions = enum(i32) { /// No options NoOptions = 0, /// Confirm on save as SaveAsConfirm = 1, /// New folder option NewFolder = 2, /// Enable preview Preview = 4, /// Use extension filter UseFilterExt = 8, }; pub const NativeFileDialog = struct { inner: ?*c.Fl_Native_File_Chooser, pub fn new(typ: NativeFileDialogType) NativeFileDialog { return NativeFileDialog{ .inner = c.Fl_Native_File_Chooser_new(@enumToInt(typ)), }; } pub fn setOptions(self: *NativeFileDialog, opt: NativeFileDialogOptions) void { c.Fl_Native_File_Chooser_set_option(self.inner, @enumToInt(opt)); } pub fn show(self: *NativeFileDialog) void { _ = c.Fl_Native_File_Chooser_show(self.inner); } pub fn filename(self: *const NativeFileDialog) [*c]const u8 { return c.Fl_Native_File_Chooser_filenames(self.inner, 0); } pub fn filenameAt(self: *const NativeFileDialog, idx: u32) [*c]const u8 { return c.Fl_Native_File_Chooser_filenames(self.inner, idx); } pub fn count(self: *const NativeFileDialog) u32 { return c.Fl_Native_File_Chooser_count(self.inner); } pub fn setDirectory(self: *NativeFileDialog, dir: [*c]const u8) void { c.Fl_Native_File_Chooser_set_directory(self.inner, dir); } pub fn directory(self: *const NativeFileDialog) [*c][]const u8 { return c.Fl_Native_File_Chooser_directory(self.inner); } /// Sets the filter for the dialog, can be: /// A single wildcard (eg. "*.txt") /// Multiple wildcards (eg. "*.{cxx,h,H}") /// A descriptive name followed by a "\t" and a wildcard (eg. "Text Files\t*.txt") /// A list of separate wildcards with a "\n" between each (eg. "*.{cxx,H}\n*.txt") /// A list of descriptive names and wildcards (eg. "C++ Files\t*.{cxx,H}\nTxt Files\t*.txt") pub fn setFilter(self: *NativeFileDialog, f: [*c]const u8) void { c.Fl_Native_File_Chooser_set_filter(self.inner, f); } /// Sets the preset filter for the dialog pub fn setPresetFile(self: *NativeFileDialog, f: [*c]const u8) void { c.Fl_Native_File_Chooser_set_preset_file(self.inner, f); } }; /// Displays an message box pub fn message(x: i32, y: i32, msg: [*c]const u8) void { c.Fl_message(x, y, msg); } /// Displays an alert box pub fn alert(x: i32, y: i32, txt: [*c]const u8) void { c.Fl_alert(x, y, txt); } /// Displays a choice box with upto three choices /// An empty choice will not be shown pub fn choice(x: i32, y: i32, txt: [*c]const u8, b0: [*c]const u8, b1: [*c]const u8, b2: [*c]const u8) u32 { c.Fl_choice(x, y, txt, b0, b1, b2); } /// Displays an input box, which returns the inputted string. /// Can be used for gui io pub fn input(x: i32, y: i32, txt: [*c]const u8, deflt: [*c]const u8) [*c]const u8 { return c.Fl_input(x, y, txt, deflt); } /// Shows an input box, but with hidden string pub fn password(x: i32, y: i32, txt: [*c]const u8, deflt: [*c]const u8) [*c]const u8 { return c.Fl_password(x, y, txt, deflt); } test "" { @import("std").testing.refAllDecls(@This()); }
src/dialog.zig
const concepts = @import("concepts"); const getty = @import("getty"); const std = @import("std"); pub const Deserializer = struct { allocator: ?std.mem.Allocator = null, tokens: std.json.TokenStream, const Self = @This(); const impl = @"impl Deserializer"; pub fn init(slice: []const u8) Self { return Self{ .tokens = std.json.TokenStream.init(slice), }; } pub fn withAllocator(allocator: std.mem.Allocator, slice: []const u8) Self { return Self{ .allocator = allocator, .tokens = std.json.TokenStream.init(slice), }; } /// Validates that the input data has been fully deserialized. /// /// This method should always be called after a value has been fully /// deserialized. pub fn end(self: *Self) impl.deserializer.Error!void { if (self.tokens.i < self.tokens.slice.len or !self.tokens.parser.complete) { return error.InvalidTopLevelTrailing; } } pub usingnamespace getty.Deserializer( *Self, impl.deserializer.Error, impl.deserializer.deserializeBool, impl.deserializer.deserializeEnum, impl.deserializer.deserializeFloat, impl.deserializer.deserializeInt, impl.deserializer.deserializeMap, impl.deserializer.deserializeOptional, impl.deserializer.deserializeSequence, impl.deserializer.deserializeString, impl.deserializer.deserializeStruct, impl.deserializer.deserializeVoid, ); }; const @"impl Deserializer" = struct { pub const deserializer = struct { pub const Error = getty.de.Error || std.json.TokenStream.Error || std.fmt.ParseIntError || std.fmt.ParseFloatError; /// Hint that the type being deserialized into is expecting a `bool` value. pub fn deserializeBool(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { switch (token) { .True => return try visitor.visitBool(Error, true), .False => return try visitor.visitBool(Error, false), else => {}, } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting an `enum` /// value. pub fn deserializeEnum(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { switch (token) { .Number => |num| { const slice = num.slice(self.tokens.slice, self.tokens.i - 1); if (num.is_integer) { return try switch (slice[0]) { '-' => visitor.visitInt(Error, try parseSigned(slice)), else => visitor.visitInt(Error, try parseUnsigned(slice)), }; } }, .String => |str| { const slice = str.slice(self.tokens.slice, self.tokens.i - 1); return try visitor.visitString(Error, try self.allocator.?.dupe(u8, slice)); }, else => {}, } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting a /// floating-point value. pub fn deserializeFloat(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { switch (token) { .Number => |num| { const slice = num.slice(self.tokens.slice, self.tokens.i - 1); return try visitor.visitFloat(Error, try std.fmt.parseFloat(f128, slice)); }, else => {}, } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting an /// integer value. pub fn deserializeInt(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { switch (token) { .Number => |num| { const slice = num.slice(self.tokens.slice, self.tokens.i - 1); switch (num.is_integer) { true => return try switch (slice[0]) { '-' => visitor.visitInt(Error, try parseSigned(slice)), else => visitor.visitInt(Error, try parseUnsigned(slice)), }, false => {}, } }, else => {}, } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting a map of /// key-value pairs. pub fn deserializeMap(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { if (token == .ObjectBegin) { var access = MapAccess{ .allocator = self.allocator, .deserializer = self }; return try visitor.visitMap(access.mapAccess()); } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting an optional /// value. pub fn deserializeOptional(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { const tokens = self.tokens; if (try self.tokens.next()) |token| { return try switch (token) { .Null => visitor.visitNull(Error), else => blk: { // Get back the token we just ate if it was an actual // value so that whenever the next deserialize method // is called by visitSome, it'll eat the token we just // saw instead of whatever comes after it. self.tokens = tokens; break :blk visitor.visitSome(self.deserializer()); }, }; } return error.InvalidType; } /// Hint that the type being deserialized into is expecting a sequence of /// values. pub fn deserializeSequence(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { if (token == .ArrayBegin) { var access = SeqAccess{ .allocator = self.allocator, .deserializer = self }; return try visitor.visitSequence(access.sequenceAccess()); } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting a string value. pub fn deserializeString(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { switch (token) { .String => |str| { const slice = str.slice(self.tokens.slice, self.tokens.i - 1); return visitor.visitString(Error, try self.allocator.?.dupe(u8, slice)); }, else => {}, } } return error.InvalidType; } /// Hint that the type being deserialized into is expecting a struct value. pub fn deserializeStruct(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { return try deserializeMap(self, visitor); } /// Hint that the type being deserialized into is expecting a `void` value. pub fn deserializeVoid(self: *Deserializer, visitor: anytype) Error!@TypeOf(visitor).Value { if (try self.tokens.next()) |token| { if (token == .Null) { return try visitor.visitVoid(Error); } } return error.InvalidType; } fn parseInt(comptime T: type, buf: []const u8) std.fmt.ParseIntError!T { comptime std.debug.assert(T == u128 or T == i128); if (buf.len == 0) return error.InvalidCharacter; var start = buf; var sign: enum { pos, neg } = .pos; switch (buf[0]) { '0'...'9' => {}, '+' => start = buf[1..], '-' => { sign = .neg; start = buf[1..]; }, else => return error.InvalidCharacter, } if (start[0] == '_' or start[start.len - 1] == '_') { return error.InvalidCharacter; } const radix: T = 10; var int: T = 0; for (start) |c| { if (c == '_') { continue; } const digit = try std.fmt.charToDigit(c, radix); if (int != 0) { // TODO: Does math.cast not accept comptime_int? int = try std.math.mul(T, int, try std.math.cast(T, radix)); } int = switch (sign) { .pos => try std.math.add(T, int, try std.math.cast(T, digit)), .neg => try std.math.sub(T, int, try std.math.cast(T, digit)), }; } return int; } fn parseSigned(buf: []const u8) Error!i128 { return try parseInt(i128, buf); } fn parseUnsigned(buf: []const u8) Error!u128 { return try parseInt(u128, buf); } }; }; const SeqAccess = struct { allocator: ?std.mem.Allocator, deserializer: *Deserializer, const Self = @This(); const impl = @"impl SeqAccess"; pub usingnamespace getty.de.SequenceAccess( *Self, impl.sequenceAccess.Error, impl.sequenceAccess.nextElementSeed, ); }; const @"impl SeqAccess" = struct { pub const sequenceAccess = struct { pub const Error = @"impl Deserializer".deserializer.Error; pub fn nextElementSeed(self: *SeqAccess, seed: anytype) Error!?@TypeOf(seed).Value { const element = seed.deserialize(self.allocator, self.deserializer.deserializer()) catch |err| { // Slice for the current token instead of looking at the // `token` field since the token isn't set for some reason. if (self.deserializer.tokens.i - 1 >= self.deserializer.tokens.slice.len) { return err; } return switch (self.deserializer.tokens.slice[self.deserializer.tokens.i - 1]) { ']' => null, else => err, }; }; return element; } }; }; const MapAccess = struct { allocator: ?std.mem.Allocator, deserializer: *Deserializer, const Self = @This(); const impl = @"impl MapAccess"; pub usingnamespace getty.de.MapAccess( *Self, impl.mapAccess.Error, impl.mapAccess.nextKeySeed, impl.mapAccess.nextValueSeed, ); }; const @"impl MapAccess" = struct { pub const mapAccess = struct { pub const Error = @"impl Deserializer".deserializer.Error; pub fn nextKeySeed(self: *MapAccess, seed: anytype) Error!?@TypeOf(seed).Value { comptime concepts.Concept("StringKey", "expected key type to be `[]const u8`")(.{ concepts.traits.isSame(@TypeOf(seed).Value, []const u8), }); if (try self.deserializer.tokens.next()) |token| { switch (token) { .ObjectEnd => return null, .String => |str| { const slice = str.slice(self.deserializer.tokens.slice, self.deserializer.tokens.i - 1); return try self.allocator.?.dupe(u8, slice); }, else => {}, } } return error.InvalidType; } pub fn nextValueSeed(self: *MapAccess, seed: anytype) Error!@TypeOf(seed).Value { return try seed.deserialize(self.allocator, self.deserializer.deserializer()); } }; };
src/de/deserializer.zig
const std = @import("std"); const stbi = @import("stb_image"); const common = @import("common.zig"); const TextureFormat = common.TextureFormat; const TextureHandle = common.TextureHandle; pub fn withBackend(comptime backend: anytype) type { return struct { pub const Texture2d = struct { handle: TextureHandle, format: TextureFormat, width: u32, height: u32, pub fn fromRawBytes( format: TextureFormat, width: u32, height: u32, bytes: []const u8, ) !Texture2d { const handle = try backend.createTexture2dWithBytes( bytes, width, height, format, ); return Texture2d{ .handle = handle, .format = format, .width = width, .height = height, }; } pub fn fromBytes(bytes: []const u8) !Texture2d { var width: u32 = undefined; var height: u32 = undefined; var channels: u32 = 1; const texture_bytes = stbi.stbi_load_from_memory( bytes.ptr, @intCast(c_int, bytes.len), @ptrCast(*c_int, &width), @ptrCast(*c_int, &height), @ptrCast(*c_int, &channels), 0, ); defer stbi.stbi_image_free(texture_bytes); if (texture_bytes == null) return error.FailedToLoadImage; const texture_bytes_size = width * height * channels * @sizeOf(u8); const format: TextureFormat = switch (channels) { 4 => .rgba_u8, else => unreachable, }; const handle = try backend.createTexture2dWithBytes( texture_bytes[0..texture_bytes_size], width, height, format, ); return Texture2d{ .handle = handle, .format = format, .width = width, .height = height, }; } pub fn fromPBM( allocator: std.mem.Allocator, pbm_bytes: []const u8, ) !Texture2d { return try pbm.parse(allocator, pbm_bytes); } const pbm = struct { pub fn parse( allocator: std.mem.Allocator, bytes: []const u8, ) !Texture2d { var parser = Parser{ .bytes = bytes, .cur = 0, }; return parser.parse(allocator); } pub const Parser = struct { bytes: []const u8, cur: usize, fn parse(self: *@This(), allocator: std.mem.Allocator) !Texture2d { const magic_number = try self.magicNumber(); self.whitespace(); const width = self.integer(); self.whitespace(); const height = self.integer(); self.whitespace(); var texture_rows = try allocator.alloc([]u8, height); defer allocator.free(texture_rows); for (texture_rows) |*row| { row.* = try allocator.alloc(u8, width); } defer { for (texture_rows) |*row| { allocator.free(row.*); } } var texture_bytes = try allocator.alloc(u8, width * height); defer allocator.free(texture_bytes); switch (magic_number) { .p1 => { const format = TextureFormat.uint8; var i: usize = 0; for (self.bytes[self.cur..]) |c| { if (isWhitespace(c)) continue; texture_bytes[i] = switch (c) { '1' => 255, else => 0, }; i += 1; } const handle = try backend.createTexture2dWithBytes( texture_bytes, width, height, format, ); return Texture2d{ .handle = handle, .format = format, .width = width, .height = height, }; }, .p4 => return error.Unimplemented, } } fn magicNumber(self: *@This()) !enum { p1, p4 } { if (self.bytes[self.cur] != 'P') return error.BadFormat; self.cur += 1; defer self.cur += 1; switch (self.bytes[self.cur]) { '1' => return .p1, '4' => return .p4, else => return error.BadFormat, } } fn whitespace(self: *@This()) void { while (isWhitespace(self.bytes[self.cur])) { self.cur += 1; } } inline fn isWhitespace(char: u8) bool { const whitespace_chars = " \t\n\r"; inline for (whitespace_chars) |wsc| if (wsc == char) return true; return false; } fn integer(self: *@This()) u32 { var res: u32 = 0; for (self.bytes[self.cur..]) |c| { self.cur += 1; if (isWhitespace(c)) break; res = (res << 3) +% (res << 1) +% (c -% '0'); } return res; } }; }; }; }; }
modules/graphics/src/textures.zig
const std = @import("std"); const stb = @import("stb_image"); const ImGuiImplementation = @import("imguiImplementation.zig"); const TimeManager = @import("timeManager.zig"); const zt = @import("../zt.zig"); const gl = @import("gl"); const glfw = @import("glfw"); const ig = @import("imgui"); var initialized: bool = false; pub fn App(comptime Data: type) type { return struct { const Self = @This(); pub const InputEvent = union(enum) { keyboard: struct { key: c_int, scan: c_int, action: c_int, mods: c_int, }, mouseWheel: struct { x: f64, y: f64, }, mouseButton: struct { key: c_int, action: c_int, mods: c_int, }, mousePosition: struct { x: f64, y: f64, }, character: struct { value: c_uint, }, }; pub const Settings = struct { energySaving: bool = true, imguiActive: bool = true, /// Do not edit, this simply tells you whether or not the vsync is on. To modify this state /// use `context.setVsync(true)` vsync: bool = true, }; pub const Context = struct { _updateSeconds: f32 = -1.0, allocator: std.mem.Allocator = undefined, data: Data = undefined, settings: Settings = .{}, window: ?*glfw.GLFWwindow = undefined, input: std.ArrayList(InputEvent) = undefined, time: TimeManager = undefined, open: bool = false, pub fn deinit(self: *Context) void { self.input.deinit(); ImGuiImplementation.Shutdown(); glfw.glfwTerminate(); self.allocator.destroy(self); } /// Ticks forward timer, clears OpenGL, enqueues events, and dictates to imgui /// that we are starting a new frame. Basically pub fn beginFrame(self: *Context) void { self.open = glfw.glfwWindowShouldClose(self.window) == 0; self.time.tick(); glfw.glfwPollEvents(); gl.glClear(gl.GL_COLOR_BUFFER_BIT); ig.igNewFrame(); } /// Draws all the imgui commands, and flips the buffer to display the drawn image pub fn endFrame(self: *Context) void { var io = ig.igGetIO(); // Render if (self.settings.imguiActive) { ig.igRender(); var dd = ig.igGetDrawData(); ImGuiImplementation.RenderDrawData(dd); } else { ig.igEndFrame(); } self.input.items.len = 0; glfw.glfwSwapBuffers(self.window); io.*.DeltaTime = self.time.dt; if (self.settings.energySaving) { if (self._updateSeconds > 0.0) { self._updateSeconds -= self.time.dt; } else { glfw.glfwWaitEvents(); } } } /// Changes the context window's position. In some operating systems I believe this is /// a no-op pub fn setWindowPosition(self: *Context, x: c_int, y: c_int) void { glfw.glfwSetWindowPos(self.window, x, y); } /// Changes the context window's size pub fn setWindowSize(self: *Context, width: c_int, height: c_int) void { glfw.glfwSetWindowSize(self.window, width, height); } /// Changes the context window's title(the text on the window's title bar, typically) pub fn setWindowTitle(self: *Context, string: []const u8) void { glfw.glfwSetWindowTitle(self.window, string.ptr); } /// If true, buffer swaps will happen each possible frame in line with your monitor hz, /// but if false, will buffer swap as fast as it can. pub fn setVsync(self: *Context, on: bool) void { if (on) { glfw.glfwSwapInterval(1); } else { glfw.glfwSwapInterval(0); } self.settings.vsync = on; } /// Give a path to a .png for the window icon. Note this does not affect the /// binary icon, and you would rather want to use post builds specific to /// each platform. pub fn setWindowIcon(self: *Context, path: []const u8) void { stb.stbi_set_flip_vertically_on_load(0); var image = glfw.GLFWimage{ .width = 0, .height = 0, .pixels = null }; image.pixels = stb.stbi_load(path.ptr, &image.width, &image.height, 0, 4); if (image.width > 0 and image.height > 0) { glfw.glfwSetWindowIcon(self.window, 1, &image); stb.stbi_image_free(image.pixels); } else { std.debug.print("Failed to load icon {s}\n", .{path}); } } /// Tells ZT to close the window pub fn close(self: *Context) void { glfw.glfwSetWindowShouldClose(self.window, 1); } /// If you have an animation that needs to play you can queue an amount of seconds that will ignore energy saving mode pub fn setAnimationFrames(self: *Context, seconds: f32) void { self._updateSeconds = seconds; } /// If you are using multithreading or anything that will require the UI to update from outside, this can force a redraw, /// if you are using energy saving mode pub fn forceUpdate(self: *Context) void { _ = self; glfw.glfwPostEmptyEvent(); } pub fn addFont(self: *Context, path: []const u8, pxSize: f32) *ig.ImFont { var io = ig.igGetIO(); var newFont: *ig.ImFont = ig.ImFontAtlas_AddFontFromFileTTF(io.*.Fonts, path.ptr, pxSize, null, ig.ImFontAtlas_GetGlyphRangesDefault(io.*.Fonts)); self.rebuildFont(); return newFont; } /// This will destroy and rebuild the font texture used for imgui. /// This is also called for you when you add and remove fonts pub fn rebuildFont(self: *Context) void { _ = self; var io = ig.igGetIO(); // Delete the old texture var texId = @intCast(c_uint, @ptrToInt(io.*.Fonts.*.TexID)); gl.glDeleteTextures(1, &texId); // Generate new texture var newTexId: c_uint = 0; var pixels: [*c]u8 = undefined; var fontTexWidth: i32 = undefined; var fontTexHeight: i32 = undefined; ig.ImFontAtlas_GetTexDataAsRGBA32(io.*.Fonts, &pixels, &fontTexWidth, &fontTexHeight, null); // Upload texture to graphics system gl.glGenTextures(1, &newTexId); gl.glBindTexture(gl.GL_TEXTURE_2D, newTexId); gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR); gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR); if (@hasDecl(gl, "GL_UNPACK_ROW_LENGTH")) gl.glPixelStorei(gl.GL_UNPACK_ROW_LENGTH, 0); gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, fontTexWidth, fontTexHeight, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, pixels); // Store our identifier io.*.Fonts.*.TexID = @intToPtr(*anyopaque, newTexId); ImGuiImplementation.g_FontTexture = newTexId; } }; /// If you need glfw to init before starting, use this to init glfw and /// other libraries without actually spinning up the context pub fn preInit() !void { if (!initialized) { if (glfw.glfwInit() < 0) { std.debug.panic("Failed to init GLFW", .{}); } glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3); glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3); glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE); initialized = true; } } /// Starts the entire application! Returns errors if anything along the pipeline fails. pub fn begin(applicationAllocator: std.mem.Allocator) !*Context { var self: *Context = try applicationAllocator.create(Context); self.* = .{}; if (Data != void) { self.data = .{}; } self.allocator = applicationAllocator; self.input = std.ArrayList(InputEvent).init(applicationAllocator); try preInit(); self.window = glfw.glfwCreateWindow(800, 600, "ZT Application", null, null).?; self.open = true; glfw.glfwMakeContextCurrent(self.window); if (gl.gladLoadGL() < 0) { return error.GladLoadError; } ImGuiImplementation.init("#version 330"); glfw.glfwSetWindowUserPointer(self.window, self); _ = glfw.glfwSetFramebufferSizeCallback(self.window, windowSizeChanged); _ = glfw.glfwSetKeyCallback(self.window, inputCallback); _ = glfw.glfwSetCharCallback(self.window, charCallback); _ = glfw.glfwSetMouseButtonCallback(self.window, mousebuttonCallback); _ = glfw.glfwSetCursorPosCallback(self.window, cursorCallback); _ = glfw.glfwSetScrollCallback(self.window, mouseWheelCallback); _ = glfw.glfwSetWindowMaximizeCallback(self.window, windowMaximizeChanged); gl.glClearColor(0.1, 0.1, 0.12, 1.0); var width: c_int = 0; var height: c_int = 0; glfw.glfwGetWindowSize(self.window, &width, &height); gl.glViewport(0, 0, width, height); var io = ig.igGetIO(); io.*.ConfigFlags |= ig.ImGuiConfigFlags_DockingEnable; io.*.DisplaySize = .{ .x = @intToFloat(f32, width), .y = @intToFloat(f32, height) }; self.time = TimeManager.init(); return self; } // Callbacks fn windowSizeChanged(win: ?*glfw.GLFWwindow, newWidth: c_int, newHeight: c_int) callconv(.C) void { _ = win; gl.glViewport(0, 0, newWidth, newHeight); var io = ig.igGetIO(); io.*.DisplaySize = .{ .x = @intToFloat(f32, newWidth), .y = @intToFloat(f32, newHeight) }; } fn windowMaximizeChanged(win: ?*glfw.GLFWwindow, maximized: c_int) callconv(.C) void { _ = maximized; var width: c_int = 0; var height: c_int = 0; glfw.glfwGetWindowSize(win, &width, &height); gl.glViewport(0, 0, width, height); var io = ig.igGetIO(); io.*.DisplaySize = .{ .x = @intToFloat(f32, width), .y = @intToFloat(f32, height) }; } fn inputCallback(win: ?*glfw.GLFWwindow, key: c_int, scan: c_int, action: c_int, mods: c_int) callconv(.C) void { var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(*Context), glfw.glfwGetWindowUserPointer(win).?)); var io = ig.igGetIO(); var pressed = false; if (action == glfw.GLFW_PRESS or action == glfw.GLFW_REPEAT) { pressed = true; } io.*.KeysDown[@intCast(usize, key)] = pressed; io.*.KeyShift = io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_LEFT_SHIFT)] or io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_RIGHT_SHIFT)]; io.*.KeyCtrl = io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_LEFT_CONTROL)] or io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_RIGHT_CONTROL)]; io.*.KeyAlt = io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_LEFT_ALT)] or io.*.KeysDown[@intCast(usize, glfw.GLFW_KEY_RIGHT_ALT)]; context.input.append(.{ .keyboard = .{ .key = key, .scan = scan, .action = action, .mods = mods, } }) catch unreachable; } fn mouseWheelCallback(win: ?*glfw.GLFWwindow, x: f64, y: f64) callconv(.C) void { var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(*Context), glfw.glfwGetWindowUserPointer(win).?)); var io = ig.igGetIO(); io.*.MouseWheel = @floatCast(f32, y); io.*.MouseWheelH = @floatCast(f32, x); context.input.append(.{ .mouseWheel = .{ .x = x, .y = y, } }) catch unreachable; } fn mousebuttonCallback(win: ?*glfw.GLFWwindow, key: c_int, action: c_int, mods: c_int) callconv(.C) void { var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(*Context), glfw.glfwGetWindowUserPointer(win).?)); var io = ig.igGetIO(); var pressed = false; if (action == glfw.GLFW_PRESS or action == glfw.GLFW_REPEAT) { pressed = true; } switch (key) { glfw.GLFW_MOUSE_BUTTON_LEFT => { io.*.MouseDown[ig.ImGuiMouseButton_Left] = pressed; }, glfw.GLFW_MOUSE_BUTTON_MIDDLE => { io.*.MouseDown[ig.ImGuiMouseButton_Middle] = pressed; }, glfw.GLFW_MOUSE_BUTTON_RIGHT => { io.*.MouseDown[ig.ImGuiMouseButton_Right] = pressed; }, else => {}, } context.input.append(.{ .mouseButton = .{ .key = key, .action = action, .mods = mods, } }) catch unreachable; } fn cursorCallback(win: ?*glfw.GLFWwindow, x: f64, y: f64) callconv(.C) void { var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(*Context), glfw.glfwGetWindowUserPointer(win).?)); var io = ig.igGetIO(); io.*.MousePos = .{ .x = @floatCast(f32, x), .y = @floatCast(f32, y) }; context.input.append(.{ .mousePosition = .{ .x = x, .y = y, } }) catch unreachable; } fn charCallback(win: ?*glfw.GLFWwindow, char: c_uint) callconv(.C) void { var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(*Context), glfw.glfwGetWindowUserPointer(win).?)); var io = ig.igGetIO(); ig.ImGuiIO_AddInputCharacter(io, char); context.input.append(.{ .character = .{ .value = char, } }) catch unreachable; } }; }
src/zt/app.zig
const root = @import("root"); const std = @import("std.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const uefi = std.os.uefi; const elf = std.elf; const tlcsprng = @import("crypto/tlcsprng.zig"); const native_arch = builtin.cpu.arch; const native_os = builtin.os.tag; var argc_argv_ptr: [*]usize = undefined; const start_sym_name = if (native_arch.isMIPS()) "__start" else "_start"; comptime { // No matter what, we import the root file, so that any export, test, comptime // decls there get run. _ = root; // The self-hosted compiler is not fully capable of handling all of this start.zig file. // Until then, we have simplified logic here for self-hosted. TODO remove this once // self-hosted is capable enough to handle all of the real start.zig logic. if (builtin.zig_backend != .stage1) { if (builtin.output_mode == .Exe) { if ((builtin.link_libc or builtin.object_format == .c) and @hasDecl(root, "main")) { if (@typeInfo(@TypeOf(root.main)).Fn.calling_convention != .C) { @export(main2, .{ .name = "main" }); } } else if (builtin.os.tag == .windows) { @export(wWinMainCRTStartup2, .{ .name = "wWinMainCRTStartup" }); } else if (builtin.os.tag == .wasi and @hasDecl(root, "main")) { @export(wasmMain2, .{ .name = "_start" }); } else { if (!@hasDecl(root, "_start")) { @export(_start2, .{ .name = "_start" }); } } } } else { if (builtin.output_mode == .Lib and builtin.link_mode == .Dynamic) { if (native_os == .windows and !@hasDecl(root, "_DllMainCRTStartup")) { @export(_DllMainCRTStartup, .{ .name = "_DllMainCRTStartup" }); } } else if (builtin.output_mode == .Exe or @hasDecl(root, "main")) { if (builtin.link_libc and @hasDecl(root, "main")) { if (native_arch.isWasm()) { @export(mainWithoutEnv, .{ .name = "main" }); } else if (@typeInfo(@TypeOf(root.main)).Fn.calling_convention != .C) { @export(main, .{ .name = "main" }); } } else if (native_os == .windows) { if (!@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup")) { @export(WinStartup, .{ .name = "wWinMainCRTStartup" }); } else if (@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup")) { @compileError("WinMain not supported; declare wWinMain or main instead"); } else if (@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup") and !@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup")) { @export(wWinMainCRTStartup, .{ .name = "wWinMainCRTStartup" }); } } else if (native_os == .uefi) { if (!@hasDecl(root, "EfiMain")) @export(EfiMain, .{ .name = "EfiMain" }); } else if (native_os == .wasi) { const wasm_start_sym = switch (builtin.wasi_exec_model) { .reactor => "_initialize", .command => "_start", }; if (!@hasDecl(root, wasm_start_sym)) { @export(wasi_start, .{ .name = wasm_start_sym }); } } else if (native_arch.isWasm() and native_os == .freestanding) { if (!@hasDecl(root, start_sym_name)) @export(wasm_freestanding_start, .{ .name = start_sym_name }); } else if (native_os != .other and native_os != .freestanding) { if (!@hasDecl(root, start_sym_name)) @export(_start, .{ .name = start_sym_name }); } } } } // Simplified start code for stage2 until it supports more language features /// fn main2() callconv(.C) c_int { root.main(); return 0; } fn _start2() callconv(.Naked) noreturn { callMain2(); } fn callMain2() noreturn { @setAlignStack(16); root.main(); exit2(0); } fn wasmMain2() u8 { switch (@typeInfo(@typeInfo(@TypeOf(root.main)).Fn.return_type.?)) { .Void => { root.main(); return 0; }, .Int => |info| { if (info.bits != 8 or info.signedness == .signed) { @compileError(bad_main_ret); } return root.main(); }, else => @compileError("Bad return type main"), } } fn wWinMainCRTStartup2() callconv(.C) noreturn { root.main(); exit2(0); } fn exit2(code: usize) noreturn { switch (native_os) { .linux => switch (builtin.stage2_arch) { .x86_64 => { asm volatile ("syscall" : : [number] "{rax}" (231), [arg1] "{rdi}" (code), : "rcx", "r11", "memory" ); }, .arm => { asm volatile ("svc #0" : : [number] "{r7}" (1), [arg1] "{r0}" (code), : "memory" ); }, .aarch64 => { asm volatile ("svc #0" : : [number] "{x8}" (93), [arg1] "{x0}" (code), : "memory", "cc" ); }, .riscv64 => { asm volatile ("ecall" : : [number] "{a7}" (94), [arg1] "{a0}" (0), : "rcx", "r11", "memory" ); }, else => @compileError("TODO"), }, // exits(0) .plan9 => switch (builtin.stage2_arch) { .x86_64 => { asm volatile ( \\push $0 \\push $0 \\syscall : : [syscall_number] "{rbp}" (8), : "rcx", "r11", "memory" ); }, // TODO once we get stack setting with assembly on // arm, exit with 0 instead of stack garbage .aarch64 => { asm volatile ("svc #0" : : [exit] "{x0}" (0x08), : "memory", "cc" ); }, else => @compileError("TODO"), }, .windows => { ExitProcess(@truncate(u32, code)); }, else => @compileError("TODO"), } unreachable; } extern "kernel32" fn ExitProcess(exit_code: u32) callconv(.C) noreturn; //////////////////////////////////////////////////////////////////////////////// fn _DllMainCRTStartup( hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, lpReserved: std.os.windows.LPVOID, ) callconv(std.os.windows.WINAPI) std.os.windows.BOOL { if (!builtin.single_threaded and !builtin.link_libc) { _ = @import("start_windows_tls.zig"); } if (@hasDecl(root, "DllMain")) { return root.DllMain(hinstDLL, fdwReason, lpReserved); } return std.os.windows.TRUE; } fn wasm_freestanding_start() callconv(.C) void { // This is marked inline because for some reason LLVM in // release mode fails to inline it, and we want fewer call frames in stack traces. _ = @call(.{ .modifier = .always_inline }, callMain, .{}); } fn wasi_start() callconv(.C) void { // The function call is marked inline because for some reason LLVM in // release mode fails to inline it, and we want fewer call frames in stack traces. switch (builtin.wasi_exec_model) { .reactor => _ = @call(.{ .modifier = .always_inline }, callMain, .{}), .command => std.os.wasi.proc_exit(@call(.{ .modifier = .always_inline }, callMain, .{})), } } fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.C) usize { uefi.handle = handle; uefi.system_table = system_table; switch (@typeInfo(@TypeOf(root.main)).Fn.return_type.?) { noreturn => { root.main(); }, void => { root.main(); return 0; }, usize => { return root.main(); }, uefi.Status => { return @enumToInt(root.main()); }, else => @compileError("expected return type of main to be 'void', 'noreturn', 'usize', or 'std.os.uefi.Status'"), } } fn _start() callconv(.Naked) noreturn { switch (native_arch) { .x86_64 => { argc_argv_ptr = asm volatile ( \\ xor %%rbp, %%rbp : [argc] "={rsp}" (-> [*]usize), ); }, .i386 => { argc_argv_ptr = asm volatile ( \\ xor %%ebp, %%ebp : [argc] "={esp}" (-> [*]usize), ); }, .aarch64, .aarch64_be, .arm, .armeb, .thumb => { argc_argv_ptr = asm volatile ( \\ mov fp, #0 \\ mov lr, #0 : [argc] "={sp}" (-> [*]usize), ); }, .riscv64 => { argc_argv_ptr = asm volatile ( \\ li s0, 0 \\ li ra, 0 : [argc] "={sp}" (-> [*]usize), ); }, .mips, .mipsel => { // The lr is already zeroed on entry, as specified by the ABI. argc_argv_ptr = asm volatile ( \\ move $fp, $0 : [argc] "={sp}" (-> [*]usize), ); }, .powerpc => { // Setup the initial stack frame and clear the back chain pointer. argc_argv_ptr = asm volatile ( \\ mr 4, 1 \\ li 0, 0 \\ stwu 1,-16(1) \\ stw 0, 0(1) \\ mtlr 0 : [argc] "={r4}" (-> [*]usize), : : "r0" ); }, .powerpc64le => { // Setup the initial stack frame and clear the back chain pointer. // TODO: Support powerpc64 (big endian) on ELFv2. argc_argv_ptr = asm volatile ( \\ mr 4, 1 \\ li 0, 0 \\ stdu 0, -32(1) \\ mtlr 0 : [argc] "={r4}" (-> [*]usize), : : "r0" ); }, .sparcv9 => { // argc is stored after a register window (16 registers) plus stack bias argc_argv_ptr = asm ( \\ mov %%g0, %%i6 \\ add %%o6, 2175, %[argc] : [argc] "=r" (-> [*]usize), ); }, else => @compileError("unsupported arch"), } // If LLVM inlines stack variables into _start, they will overwrite // the command line argument data. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{}); } fn WinStartup() callconv(std.os.windows.WINAPI) noreturn { @setAlignStack(16); if (!builtin.single_threaded and !builtin.link_libc) { _ = @import("start_windows_tls.zig"); } std.debug.maybeEnableSegfaultHandler(); std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain()); } fn wWinMainCRTStartup() callconv(std.os.windows.WINAPI) noreturn { @setAlignStack(16); if (!builtin.single_threaded and !builtin.link_libc) { _ = @import("start_windows_tls.zig"); } std.debug.maybeEnableSegfaultHandler(); const result: std.os.windows.INT = initEventLoopAndCallWinMain(); std.os.windows.kernel32.ExitProcess(@bitCast(std.os.windows.UINT, result)); } // TODO https://github.com/ziglang/zig/issues/265 fn posixCallMainAndExit() noreturn { @setAlignStack(16); const argc = argc_argv_ptr[0]; const argv = @ptrCast([*][*:0]u8, argc_argv_ptr + 1); const envp_optional = @ptrCast([*:null]?[*:0]u8, @alignCast(@alignOf(usize), argv + argc + 1)); var envp_count: usize = 0; while (envp_optional[envp_count]) |_| : (envp_count += 1) {} const envp = @ptrCast([*][*:0]u8, envp_optional)[0..envp_count]; if (native_os == .linux) { // Find the beginning of the auxiliary vector const auxv = @ptrCast([*]elf.Auxv, @alignCast(@alignOf(usize), envp.ptr + envp_count + 1)); std.os.linux.elf_aux_maybe = auxv; var at_hwcap: usize = 0; const phdrs = init: { var i: usize = 0; var at_phdr: usize = 0; var at_phnum: usize = 0; while (auxv[i].a_type != elf.AT_NULL) : (i += 1) { switch (auxv[i].a_type) { elf.AT_PHNUM => at_phnum = auxv[i].a_un.a_val, elf.AT_PHDR => at_phdr = auxv[i].a_un.a_val, elf.AT_HWCAP => at_hwcap = auxv[i].a_un.a_val, else => continue, } } break :init @intToPtr([*]elf.Phdr, at_phdr)[0..at_phnum]; }; // Apply the initial relocations as early as possible in the startup // process. if (builtin.position_independent_executable) { std.os.linux.pie.relocate(phdrs); } // ARMv6 targets (and earlier) have no support for TLS in hardware. // FIXME: Elide the check for targets >= ARMv7 when the target feature API // becomes less verbose (and more usable). if (comptime native_arch.isARM()) { if (at_hwcap & std.os.linux.HWCAP.TLS == 0) { // FIXME: Make __aeabi_read_tp call the kernel helper kuser_get_tls // For the time being use a simple abort instead of a @panic call to // keep the binary bloat under control. std.os.abort(); } } // Initialize the TLS area. std.os.linux.tls.initStaticTLS(phdrs); // The way Linux executables represent stack size is via the PT_GNU_STACK // program header. However the kernel does not recognize it; it always gives 8 MiB. // Here we look for the stack size in our program headers and use setrlimit // to ask for more stack space. expandStackSize(phdrs); } std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp })); } fn expandStackSize(phdrs: []elf.Phdr) void { for (phdrs) |*phdr| { switch (phdr.p_type) { elf.PT_GNU_STACK => { const wanted_stack_size = phdr.p_memsz; assert(wanted_stack_size % std.mem.page_size == 0); std.os.setrlimit(.STACK, .{ .cur = wanted_stack_size, .max = wanted_stack_size, }) catch { // Because we could not increase the stack size to the upper bound, // depending on what happens at runtime, a stack overflow may occur. // However it would cause a segmentation fault, thanks to stack probing, // so we do not have a memory safety issue here. // This is intentional silent failure. // This logic should be revisited when the following issues are addressed: // https://github.com/ziglang/zig/issues/157 // https://github.com/ziglang/zig/issues/1006 }; break; }, else => {}, } } } fn callMainWithArgs(argc: usize, argv: [*][*:0]u8, envp: [][*:0]u8) u8 { std.os.argv = argv[0..argc]; std.os.environ = envp; std.debug.maybeEnableSegfaultHandler(); return initEventLoopAndCallMain(); } fn main(c_argc: i32, c_argv: [*][*:0]u8, c_envp: [*:null]?[*:0]u8) callconv(.C) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @ptrCast([*][*:0]u8, c_envp)[0..env_count]; if (builtin.os.tag == .linux) { const at_phdr = std.c.getauxval(elf.AT_PHDR); const at_phnum = std.c.getauxval(elf.AT_PHNUM); const phdrs = (@intToPtr([*]elf.Phdr, at_phdr))[0..at_phnum]; expandStackSize(phdrs); } return @call(.{ .modifier = .always_inline }, callMainWithArgs, .{ @intCast(usize, c_argc), c_argv, envp }); } fn mainWithoutEnv(c_argc: i32, c_argv: [*][*:0]u8) callconv(.C) usize { std.os.argv = c_argv[0..@intCast(usize, c_argc)]; return @call(.{ .modifier = .always_inline }, callMain, .{}); } // General error message for a malformed return type const bad_main_ret = "expected return type of main to be 'void', '!void', 'noreturn', 'u8', or '!u8'"; // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. inline fn initEventLoopAndCallMain() u8 { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; defer loop.deinit(); var result: u8 = undefined; var frame: @Frame(callMainAsync) = undefined; _ = @asyncCall(&frame, &result, callMainAsync, .{loop}); loop.run(); return result; } } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. return @call(.{ .modifier = .always_inline }, callMain, .{}); } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. // TODO This function is duplicated from initEventLoopAndCallMain instead of using generics // because it is working around stage1 compiler bugs. inline fn initEventLoopAndCallWinMain() std.os.windows.INT { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; defer loop.deinit(); var result: u8 = undefined; var frame: @Frame(callMainAsync) = undefined; _ = @asyncCall(&frame, &result, callMainAsync, .{loop}); loop.run(); return result; } } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. return @call(.{ .modifier = .always_inline }, call_wWinMain, .{}); } fn callMainAsync(loop: *std.event.Loop) callconv(.Async) u8 { // This prevents the event loop from terminating at least until main() has returned. // TODO This shouldn't be needed here; it should be in the event loop code. loop.beginOneEvent(); defer loop.finishOneEvent(); return callMain(); } // This is not marked inline because it is called with @asyncCall when // there is an event loop. pub fn callMain() u8 { switch (@typeInfo(@typeInfo(@TypeOf(root.main)).Fn.return_type.?)) { .NoReturn => { root.main(); }, .Void => { root.main(); return 0; }, .Int => |info| { if (info.bits != 8 or info.signedness == .signed) { @compileError(bad_main_ret); } return root.main(); }, .ErrorUnion => { const result = root.main() catch |err| { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; switch (@typeInfo(@TypeOf(result))) { .Void => return 0, .Int => |info| { if (info.bits != 8 or info.signedness == .signed) { @compileError(bad_main_ret); } return result; }, else => @compileError(bad_main_ret), } }, else => @compileError(bad_main_ret), } } pub fn call_wWinMain() std.os.windows.INT { const MAIN_HINSTANCE = @typeInfo(@TypeOf(root.wWinMain)).Fn.args[0].arg_type.?; const hInstance = @ptrCast(MAIN_HINSTANCE, std.os.windows.kernel32.GetModuleHandleW(null).?); const lpCmdLine = std.os.windows.kernel32.GetCommandLineW(); // There's no (documented) way to get the nCmdShow parameter, so we're // using this fairly standard default. const nCmdShow = std.os.windows.user32.SW_SHOW; // second parameter hPrevInstance, MSDN: "This parameter is always NULL" return root.wWinMain(hInstance, null, lpCmdLine, nCmdShow); }
lib/std/start.zig
const Wasm = @This(); const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const fs = std.fs; const leb = std.leb; const log = std.log.scoped(.link); const wasm = std.wasm; const Atom = @import("Wasm/Atom.zig"); const Module = @import("../Module.zig"); const Compilation = @import("../Compilation.zig"); const CodeGen = @import("../arch/wasm/CodeGen.zig"); const link = @import("../link.zig"); const trace = @import("../tracy.zig").trace; const build_options = @import("build_options"); const wasi_libc = @import("../wasi_libc.zig"); const Cache = @import("../Cache.zig"); const Type = @import("../type.zig").Type; const LlvmObject = @import("../codegen/llvm.zig").Object; const Air = @import("../Air.zig"); const Liveness = @import("../Liveness.zig"); const Symbol = @import("Wasm/Symbol.zig"); const types = @import("Wasm/types.zig"); pub const base_tag = link.File.Tag.wasm; /// deprecated: Use `@import("Wasm/Atom.zig");` pub const DeclBlock = Atom; base: link.File, /// If this is not null, an object file is created by LLVM and linked with LLD afterwards. llvm_object: ?*LlvmObject = null, /// When importing objects from the host environment, a name must be supplied. /// LLVM uses "env" by default when none is given. This would be a good default for Zig /// to support existing code. /// TODO: Allow setting this through a flag? host_name: []const u8 = "env", /// List of all `Decl` that are currently alive. /// This is ment for bookkeeping so we can safely cleanup all codegen memory /// when calling `deinit` decls: std.AutoHashMapUnmanaged(*Module.Decl, void) = .{}, /// List of all symbols. symbols: std.ArrayListUnmanaged(Symbol) = .{}, /// List of symbol indexes which are free to be used. symbols_free_list: std.ArrayListUnmanaged(u32) = .{}, /// Maps atoms to their segment index atoms: std.AutoHashMapUnmanaged(u32, *Atom) = .{}, /// Represents the index into `segments` where the 'code' section /// lives. code_section_index: ?u32 = null, /// The count of imported functions. This number will be appended /// to the function indexes as their index starts at the lowest non-extern function. imported_functions_count: u32 = 0, /// Map of symbol indexes, represented by its `wasm.Import` imports: std.AutoHashMapUnmanaged(u32, wasm.Import) = .{}, /// Represents non-synthetic section entries. /// Used for code, data and custom sections. segments: std.ArrayListUnmanaged(Segment) = .{}, /// Maps a data segment key (such as .rodata) to the index into `segments`. data_segments: std.StringArrayHashMapUnmanaged(u32) = .{}, /// A list of `types.Segment` which provide meta data /// about a data symbol such as its name segment_info: std.ArrayListUnmanaged(types.Segment) = .{}, // Output sections /// Output type section func_types: std.ArrayListUnmanaged(wasm.Type) = .{}, /// Output function section functions: std.ArrayListUnmanaged(wasm.Func) = .{}, /// Output global section globals: std.ArrayListUnmanaged(wasm.Global) = .{}, /// Memory section memories: wasm.Memory = .{ .limits = .{ .min = 0, .max = null } }, /// Indirect function table, used to call function pointers /// When this is non-zero, we must emit a table entry, /// as well as an 'elements' section. /// /// Note: Key is symbol index, value represents the index into the table function_table: std.AutoHashMapUnmanaged(u32, u32) = .{}, pub const Segment = struct { alignment: u32, size: u32, offset: u32, }; pub const FnData = struct { type_index: u32, pub const empty: FnData = .{ .type_index = undefined, }; }; pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Wasm { assert(options.object_format == .wasm); if (build_options.have_llvm and options.use_llvm) { return createEmpty(allocator, options); } // TODO: read the file and keep valid parts instead of truncating const file = try options.emit.?.directory.handle.createFile(sub_path, .{ .truncate = true, .read = true }); errdefer file.close(); const wasm_bin = try createEmpty(allocator, options); errdefer wasm_bin.base.destroy(); wasm_bin.base.file = file; try file.writeAll(&(wasm.magic ++ wasm.version)); // As sym_index '0' is reserved, we use it for our stack pointer symbol const global = try wasm_bin.globals.addOne(allocator); global.* = .{ .global_type = .{ .valtype = .i32, .mutable = true, }, .init = .{ .i32_const = 0 }, }; const symbol = try wasm_bin.symbols.addOne(allocator); symbol.* = .{ .name = "__stack_pointer", .tag = .global, .flags = 0, .index = 0, }; return wasm_bin; } pub fn createEmpty(gpa: Allocator, options: link.Options) !*Wasm { const self = try gpa.create(Wasm); errdefer gpa.destroy(self); self.* = .{ .base = .{ .tag = .wasm, .options = options, .file = null, .allocator = gpa, }, }; const use_llvm = build_options.have_llvm and options.use_llvm; const use_stage1 = build_options.is_stage1 and options.use_stage1; if (use_llvm and !use_stage1) { self.llvm_object = try LlvmObject.create(gpa, options); } return self; } pub fn deinit(self: *Wasm) void { if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator); } var decl_it = self.decls.keyIterator(); while (decl_it.next()) |decl_ptr| { const decl = decl_ptr.*; decl.link.wasm.deinit(self.base.allocator); } for (self.func_types.items) |*func_type| { func_type.deinit(self.base.allocator); } for (self.segment_info.items) |segment_info| { self.base.allocator.free(segment_info.name); } self.decls.deinit(self.base.allocator); self.symbols.deinit(self.base.allocator); self.symbols_free_list.deinit(self.base.allocator); self.atoms.deinit(self.base.allocator); self.segments.deinit(self.base.allocator); self.data_segments.deinit(self.base.allocator); self.segment_info.deinit(self.base.allocator); // free output sections self.imports.deinit(self.base.allocator); self.func_types.deinit(self.base.allocator); self.functions.deinit(self.base.allocator); self.globals.deinit(self.base.allocator); self.function_table.deinit(self.base.allocator); } pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void { if (decl.link.wasm.sym_index != 0) return; try self.symbols.ensureUnusedCapacity(self.base.allocator, 1); try self.decls.putNoClobber(self.base.allocator, decl, {}); const atom = &decl.link.wasm; var symbol: Symbol = .{ .name = undefined, // will be set after updateDecl .flags = 0, .tag = undefined, // will be set after updateDecl .index = undefined, // will be set after updateDecl }; if (self.symbols_free_list.popOrNull()) |index| { atom.sym_index = index; self.symbols.items[index] = symbol; } else { atom.sym_index = @intCast(u32, self.symbols.items.len); self.symbols.appendAssumeCapacity(symbol); } } pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void { if (build_options.skip_non_native and builtin.object_format != .wasm) { @panic("Attempted to compile for object format that was disabled by build configuration"); } if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness); } const decl = func.owner_decl; assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes() decl.link.wasm.clear(); var codegen: CodeGen = .{ .gpa = self.base.allocator, .air = air, .liveness = liveness, .values = .{}, .code = std.ArrayList(u8).init(self.base.allocator), .decl = decl, .err_msg = undefined, .locals = .{}, .target = self.base.options.target, .bin_file = self, .module = module, }; defer codegen.deinit(); // generate the 'code' section for the function declaration codegen.genFunc() catch |err| switch (err) { error.CodegenFail => { decl.analysis = .codegen_failure; try module.failed_decls.put(module.gpa, decl, codegen.err_msg); return; }, else => |e| return e, }; return self.finishUpdateDecl(decl, codegen.code.items); } // Generate code for the Decl, storing it in memory to be later written to // the file on flush(). pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { if (build_options.skip_non_native and builtin.object_format != .wasm) { @panic("Attempted to compile for object format that was disabled by build configuration"); } if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl); } if (!decl.ty.hasRuntimeBits()) return; assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes() decl.link.wasm.clear(); var code_writer = std.ArrayList(u8).init(self.base.allocator); defer code_writer.deinit(); var decl_gen: CodeGen.DeclGen = .{ .gpa = self.base.allocator, .decl = decl, .symbol_index = decl.link.wasm.sym_index, .bin_file = self, .err_msg = undefined, .code = &code_writer, .module = module, }; // generate the 'code' section for the function declaration const result = decl_gen.genDecl() catch |err| switch (err) { error.CodegenFail => { decl.analysis = .codegen_failure; try module.failed_decls.put(module.gpa, decl, decl_gen.err_msg); return; }, else => |e| return e, }; const code = switch (result) { .externally_managed => |data| data, .appended => code_writer.items, }; return self.finishUpdateDecl(decl, code); } fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, code: []const u8) !void { if (decl.isExtern()) { try self.addOrUpdateImport(decl); return; } if (code.len == 0) return; const atom: *Atom = &decl.link.wasm; atom.size = @intCast(u32, code.len); atom.alignment = decl.ty.abiAlignment(self.base.options.target); self.symbols.items[atom.sym_index].name = decl.name; try atom.code.appendSlice(self.base.allocator, code); } /// Creates a new local symbol for a given type (and its bytes it's represented by) /// and then append it as a 'contained' atom onto the Decl. pub fn createLocalSymbol(self: *Wasm, decl: *Module.Decl, ty: Type) !u32 { assert(ty.zigTypeTag() != .Fn); // cannot create local symbols for functions var symbol: Symbol = .{ .name = "unnamed_local", .flags = 0, .tag = .data, .index = undefined, }; symbol.setFlag(.WASM_SYM_BINDING_LOCAL); symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN); var atom = Atom.empty; atom.alignment = ty.abiAlignment(self.base.options.target); try self.symbols.ensureUnusedCapacity(self.base.allocator, 1); if (self.symbols_free_list.popOrNull()) |index| { atom.sym_index = index; self.symbols.items[index] = symbol; } else { atom.sym_index = @intCast(u32, self.symbols.items.len); self.symbols.appendAssumeCapacity(symbol); } try decl.link.wasm.locals.append(self.base.allocator, atom); return atom.sym_index; } pub fn updateLocalSymbolCode(self: *Wasm, decl: *Module.Decl, symbol_index: u32, code: []const u8) !void { const atom = decl.link.wasm.symbolAtom(symbol_index); atom.size = @intCast(u32, code.len); try atom.code.appendSlice(self.base.allocator, code); } /// For a given decl, find the given symbol index's atom, and create a relocation for the type. /// Returns the given pointer address pub fn getDeclVAddr( self: *Wasm, decl: *Module.Decl, ty: Type, symbol_index: u32, target_symbol_index: u32, offset: u32, addend: u32, ) !u32 { const atom = decl.link.wasm.symbolAtom(symbol_index); const is_wasm32 = self.base.options.target.cpu.arch == .wasm32; if (ty.zigTypeTag() == .Fn) { std.debug.assert(addend == 0); // addend not allowed for function relocations // We found a function pointer, so add it to our table, // as function pointers are not allowed to be stored inside the data section. // They are instead stored in a function table which are called by index. try self.addTableFunction(target_symbol_index); try atom.relocs.append(self.base.allocator, .{ .index = target_symbol_index, .offset = offset, .relocation_type = if (is_wasm32) .R_WASM_TABLE_INDEX_I32 else .R_WASM_TABLE_INDEX_I64, }); } else { try atom.relocs.append(self.base.allocator, .{ .index = target_symbol_index, .offset = offset, .relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_I32 else .R_WASM_MEMORY_ADDR_I64, .addend = addend, }); } // we do not know the final address at this point, // as atom allocation will determine the address and relocations // will calculate and rewrite this. Therefore, we simply return the symbol index // that was targeted. return target_symbol_index; } pub fn updateDeclExports( self: *Wasm, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void { if (build_options.skip_non_native and builtin.object_format != .wasm) { @panic("Attempted to compile for object format that was disabled by build configuration"); } if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports); } } pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl); } const atom = &decl.link.wasm; self.symbols_free_list.append(self.base.allocator, atom.sym_index) catch {}; _ = self.decls.remove(decl); self.symbols.items[atom.sym_index].tag = .dead; // to ensure it does not end in the names section for (atom.locals.items) |local_atom| { self.symbols.items[local_atom.sym_index].tag = .dead; // also for any local symbol } atom.deinit(self.base.allocator); if (decl.isExtern()) { const import = self.imports.fetchRemove(decl.link.wasm.sym_index).?.value; switch (import.kind) { .function => self.imported_functions_count -= 1, else => unreachable, } } } /// Appends a new entry to the indirect function table pub fn addTableFunction(self: *Wasm, symbol_index: u32) !void { const index = @intCast(u32, self.function_table.count()); try self.function_table.put(self.base.allocator, symbol_index, index); } fn mapFunctionTable(self: *Wasm) void { var it = self.function_table.valueIterator(); var index: u32 = 0; while (it.next()) |value_ptr| : (index += 1) { value_ptr.* = index; } } fn addOrUpdateImport(self: *Wasm, decl: *Module.Decl) !void { const symbol_index = decl.link.wasm.sym_index; const symbol: *Symbol = &self.symbols.items[symbol_index]; symbol.name = decl.name; symbol.setUndefined(true); switch (decl.ty.zigTypeTag()) { .Fn => { const gop = try self.imports.getOrPut(self.base.allocator, symbol_index); if (!gop.found_existing) { self.imported_functions_count += 1; gop.value_ptr.* = .{ .module_name = self.host_name, .name = std.mem.span(symbol.name), .kind = .{ .function = decl.fn_link.wasm.type_index }, }; } }, else => @panic("TODO: Implement undefined symbols for non-function declarations"), } } const Kind = union(enum) { data: void, function: FnData, }; /// Parses an Atom and inserts its metadata into the corresponding sections. fn parseAtom(self: *Wasm, atom: *Atom, kind: Kind) !void { const symbol: *Symbol = &self.symbols.items[atom.sym_index]; const final_index: u32 = switch (kind) { .function => |fn_data| result: { const type_index = fn_data.type_index; const index = @intCast(u32, self.functions.items.len + self.imported_functions_count); try self.functions.append(self.base.allocator, .{ .type_index = type_index }); symbol.tag = .function; symbol.index = index; if (self.code_section_index == null) { self.code_section_index = @intCast(u32, self.segments.items.len); try self.segments.append(self.base.allocator, .{ .alignment = atom.alignment, .size = atom.size, .offset = 0, }); } break :result self.code_section_index.?; }, .data => result: { const gop = try self.data_segments.getOrPut(self.base.allocator, ".rodata"); const atom_index = if (gop.found_existing) blk: { self.segments.items[gop.value_ptr.*].size += atom.size; break :blk gop.value_ptr.*; } else blk: { const index = @intCast(u32, self.segments.items.len); try self.segments.append(self.base.allocator, .{ .alignment = atom.alignment, .size = 0, .offset = 0, }); gop.value_ptr.* = index; break :blk index; }; const info_index = @intCast(u32, self.segment_info.items.len); const segment_name = try std.mem.concat(self.base.allocator, u8, &.{ ".rodata.", std.mem.span(symbol.name), }); errdefer self.base.allocator.free(segment_name); try self.segment_info.append(self.base.allocator, .{ .name = segment_name, .alignment = atom.alignment, .flags = 0, }); symbol.tag = .data; symbol.index = info_index; break :result atom_index; }, }; const segment: *Segment = &self.segments.items[final_index]; segment.alignment = std.math.max(segment.alignment, atom.alignment); segment.size = std.mem.alignForwardGeneric( u32, std.mem.alignForwardGeneric(u32, segment.size, atom.alignment) + atom.size, segment.alignment, ); if (self.atoms.getPtr(final_index)) |last| { last.*.next = atom; atom.prev = last.*; last.* = atom; } else { try self.atoms.putNoClobber(self.base.allocator, final_index, atom); } } fn allocateAtoms(self: *Wasm) !void { var it = self.atoms.iterator(); while (it.next()) |entry| { var atom: *Atom = entry.value_ptr.*.getFirst(); var offset: u32 = 0; while (true) { offset = std.mem.alignForwardGeneric(u32, offset, atom.alignment); atom.offset = offset; log.debug("Atom '{s}' allocated from 0x{x:0>8} to 0x{x:0>8} size={d}", .{ self.symbols.items[atom.sym_index].name, offset, offset + atom.size, atom.size, }); offset += atom.size; atom = atom.next orelse break; } } } fn setupImports(self: *Wasm) void { var function_index: u32 = 0; var it = self.imports.iterator(); while (it.next()) |entry| { const symbol = &self.symbols.items[entry.key_ptr.*]; const import: wasm.Import = entry.value_ptr.*; switch (import.kind) { .function => { symbol.index = function_index; function_index += 1; }, else => unreachable, } } } /// Sets up the memory section of the wasm module, as well as the stack. fn setupMemory(self: *Wasm) !void { log.debug("Setting up memory layout", .{}); const page_size = 64 * 1024; const stack_size = self.base.options.stack_size_override orelse page_size * 1; const stack_alignment = 16; // wasm's stack alignment as specified by tool-convention // Always place the stack at the start by default // unless the user specified the global-base flag var place_stack_first = true; var memory_ptr: u64 = if (self.base.options.global_base) |base| blk: { place_stack_first = false; break :blk base; } else 0; if (place_stack_first) { memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, stack_alignment); memory_ptr += stack_size; // We always put the stack pointer global at index 0 self.globals.items[0].init.i32_const = @bitCast(i32, @intCast(u32, memory_ptr)); } var offset: u32 = @intCast(u32, memory_ptr); for (self.segments.items) |*segment, i| { // skip 'code' segments if (self.code_section_index) |index| { if (index == i) continue; } memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, segment.alignment); memory_ptr += segment.size; segment.offset = offset; offset += segment.size; } if (!place_stack_first) { memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, stack_alignment); memory_ptr += stack_size; self.globals.items[0].init.i32_const = @bitCast(i32, @intCast(u32, memory_ptr)); } // Setup the max amount of pages // For now we only support wasm32 by setting the maximum allowed memory size 2^32-1 const max_memory_allowed: u64 = (1 << 32) - 1; if (self.base.options.initial_memory) |initial_memory| { if (!std.mem.isAlignedGeneric(u64, initial_memory, page_size)) { log.err("Initial memory must be {d}-byte aligned", .{page_size}); return error.MissAlignment; } if (memory_ptr > initial_memory) { log.err("Initial memory too small, must be at least {d} bytes", .{memory_ptr}); return error.MemoryTooSmall; } if (initial_memory > max_memory_allowed) { log.err("Initial memory exceeds maximum memory {d}", .{max_memory_allowed}); return error.MemoryTooBig; } memory_ptr = initial_memory; } // In case we do not import memory, but define it ourselves, // set the minimum amount of pages on the memory section. self.memories.limits.min = @intCast(u32, std.mem.alignForwardGeneric(u64, memory_ptr, page_size) / page_size); log.debug("Total memory pages: {d}", .{self.memories.limits.min}); if (self.base.options.max_memory) |max_memory| { if (!std.mem.isAlignedGeneric(u64, max_memory, page_size)) { log.err("Maximum memory must be {d}-byte aligned", .{page_size}); return error.MissAlignment; } if (memory_ptr > max_memory) { log.err("Maxmimum memory too small, must be at least {d} bytes", .{memory_ptr}); return error.MemoryTooSmall; } if (max_memory > max_memory_allowed) { log.err("Maximum memory exceeds maxmium amount {d}", .{max_memory_allowed}); return error.MemoryTooBig; } self.memories.limits.max = @intCast(u32, max_memory / page_size); log.debug("Maximum memory pages: {d}", .{self.memories.limits.max}); } } fn resetState(self: *Wasm) void { for (self.segment_info.items) |*segment_info| { self.base.allocator.free(segment_info.name); } var decl_it = self.decls.keyIterator(); while (decl_it.next()) |decl| { const atom = &decl.*.link.wasm; atom.next = null; atom.prev = null; } self.functions.clearRetainingCapacity(); self.segments.clearRetainingCapacity(); self.segment_info.clearRetainingCapacity(); self.data_segments.clearRetainingCapacity(); self.atoms.clearRetainingCapacity(); self.code_section_index = null; } pub fn flush(self: *Wasm, comp: *Compilation) !void { if (self.base.options.emit == null) { if (build_options.have_llvm) { if (self.llvm_object) |llvm_object| { return try llvm_object.flushModule(comp); } } return; } if (build_options.have_llvm and self.base.options.use_lld) { return self.linkWithLLD(comp); } else { return self.flushModule(comp); } } pub fn flushModule(self: *Wasm, comp: *Compilation) !void { _ = comp; const tracy = trace(@src()); defer tracy.end(); // When we finish/error we reset the state of the linker // So we can rebuild the binary file on each incremental update defer self.resetState(); self.setupImports(); var decl_it = self.decls.keyIterator(); while (decl_it.next()) |decl| { if (decl.*.isExtern()) continue; const atom = &decl.*.link.wasm; if (decl.*.ty.zigTypeTag() == .Fn) { try self.parseAtom(atom, .{ .function = decl.*.fn_link.wasm }); } else { try self.parseAtom(atom, .data); } // also parse atoms for a decl's locals for (atom.locals.items) |*local_atom| { try self.parseAtom(local_atom, .data); } } try self.setupMemory(); try self.allocateAtoms(); self.mapFunctionTable(); const file = self.base.file.?; const header_size = 5 + 1; // No need to rewrite the magic/version header try file.setEndPos(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); try file.seekTo(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); // Type section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.func_types.items) |func_type| { try leb.writeULEB128(writer, wasm.function_type); try leb.writeULEB128(writer, @intCast(u32, func_type.params.len)); for (func_type.params) |param_ty| try leb.writeULEB128(writer, wasm.valtype(param_ty)); try leb.writeULEB128(writer, @intCast(u32, func_type.returns.len)); for (func_type.returns) |ret_ty| try leb.writeULEB128(writer, wasm.valtype(ret_ty)); } try writeVecSectionHeader( file, header_offset, .type, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.func_types.items.len), ); } // Import section const import_memory = self.base.options.import_memory; const import_table = self.base.options.import_table; if (self.imports.count() != 0 or import_memory or import_table) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); // import table is always first table so emit that first if (import_table) { const table_imp: wasm.Import = .{ .module_name = self.host_name, .name = "__indirect_function_table", .kind = .{ .table = .{ .limits = .{ .min = @intCast(u32, self.function_table.count()), .max = null, }, .reftype = .funcref, }, }, }; try emitImport(writer, table_imp); } var it = self.imports.iterator(); while (it.next()) |entry| { const import_symbol = self.symbols.items[entry.key_ptr.*]; std.debug.assert(import_symbol.isUndefined()); const import = entry.value_ptr.*; try emitImport(writer, import); } if (import_memory) { const mem_imp: wasm.Import = .{ .module_name = self.host_name, .name = "memory", .kind = .{ .memory = self.memories.limits }, }; try emitImport(writer, mem_imp); } try writeVecSectionHeader( file, header_offset, .import, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.imports.count() + @boolToInt(import_memory) + @boolToInt(import_table)), ); } // Function section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.functions.items) |function| { try leb.writeULEB128(writer, function.type_index); } try writeVecSectionHeader( file, header_offset, .function, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.functions.items.len), ); } // Table section const export_table = self.base.options.export_table; if (!import_table) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); try leb.writeULEB128(writer, wasm.reftype(.funcref)); try emitLimits(writer, .{ .min = @intCast(u32, self.function_table.count()), .max = null, }); try writeVecSectionHeader( file, header_offset, .table, @intCast(u32, (try file.getPos()) - header_offset - header_size), @as(u32, 1), ); } // Memory section if (!self.base.options.import_memory) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); try emitLimits(writer, self.memories.limits); try writeVecSectionHeader( file, header_offset, .memory, @intCast(u32, (try file.getPos()) - header_offset - header_size), @as(u32, 1), // wasm currently only supports 1 linear memory segment ); } // Global section (used to emit stack pointer) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.globals.items) |global| { try writer.writeByte(wasm.valtype(global.global_type.valtype)); try writer.writeByte(@boolToInt(global.global_type.mutable)); try emitInit(writer, global.init); } try writeVecSectionHeader( file, header_offset, .global, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.globals.items.len), ); } // Export section if (self.base.options.module) |module| { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var count: u32 = 0; for (module.decl_exports.values()) |exports| { for (exports) |exprt| { // Export name length + name try leb.writeULEB128(writer, @intCast(u32, exprt.options.name.len)); try writer.writeAll(exprt.options.name); switch (exprt.exported_decl.ty.zigTypeTag()) { .Fn => { const target = exprt.exported_decl.link.wasm.sym_index; const target_symbol = self.symbols.items[target]; std.debug.assert(target_symbol.tag == .function); // Type of the export try writer.writeByte(wasm.externalKind(.function)); // Exported function index try leb.writeULEB128(writer, target_symbol.index); }, else => return error.TODOImplementNonFnDeclsForWasm, } count += 1; } } // export memory if size is not 0 if (!import_memory) { try leb.writeULEB128(writer, @intCast(u32, "memory".len)); try writer.writeAll("memory"); try writer.writeByte(wasm.externalKind(.memory)); try leb.writeULEB128(writer, @as(u32, 0)); // only 1 memory 'object' can exist count += 1; } if (export_table) { try leb.writeULEB128(writer, @intCast(u32, "__indirect_function_table".len)); try writer.writeAll("__indirect_function_table"); try writer.writeByte(wasm.externalKind(.table)); try leb.writeULEB128(writer, @as(u32, 0)); // function table is always the first table count += 1; } try writeVecSectionHeader( file, header_offset, .@"export", @intCast(u32, (try file.getPos()) - header_offset - header_size), count, ); } // element section (function table) if (self.function_table.count() > 0) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var flags: u32 = 0x2; // Yes we have a table try leb.writeULEB128(writer, flags); try leb.writeULEB128(writer, @as(u32, 0)); // index of that table. TODO: Store synthetic symbols try emitInit(writer, .{ .i32_const = 0 }); try leb.writeULEB128(writer, @as(u8, 0)); try leb.writeULEB128(writer, @intCast(u32, self.function_table.count())); var symbol_it = self.function_table.keyIterator(); while (symbol_it.next()) |symbol_index_ptr| { try leb.writeULEB128(writer, self.symbols.items[symbol_index_ptr.*].index); } try writeVecSectionHeader( file, header_offset, .element, @intCast(u32, (try file.getPos()) - header_offset - header_size), @as(u32, 1), ); } // Code section if (self.code_section_index) |code_index| { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var atom: *Atom = self.atoms.get(code_index).?.getFirst(); while (true) { try atom.resolveRelocs(self); try leb.writeULEB128(writer, atom.size); try writer.writeAll(atom.code.items); atom = atom.next orelse break; } try writeVecSectionHeader( file, header_offset, .code, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.functions.items.len), ); } // Data section if (self.data_segments.count() != 0) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var it = self.data_segments.iterator(); var segment_count: u32 = 0; while (it.next()) |entry| { // do not output 'bss' section if (std.mem.eql(u8, entry.key_ptr.*, ".bss")) continue; segment_count += 1; const atom_index = entry.value_ptr.*; var atom: *Atom = self.atoms.getPtr(atom_index).?.*.getFirst(); var segment = self.segments.items[atom_index]; // flag and index to memory section (currently, there can only be 1 memory section in wasm) try leb.writeULEB128(writer, @as(u32, 0)); // offset into data section try emitInit(writer, .{ .i32_const = @bitCast(i32, segment.offset) }); try leb.writeULEB128(writer, segment.size); // fill in the offset table and the data segments var current_offset: u32 = 0; while (true) { try atom.resolveRelocs(self); // Pad with zeroes to ensure all segments are aligned if (current_offset != atom.offset) { const diff = atom.offset - current_offset; try writer.writeByteNTimes(0, diff); current_offset += diff; } std.debug.assert(current_offset == atom.offset); std.debug.assert(atom.code.items.len == atom.size); try writer.writeAll(atom.code.items); current_offset += atom.size; if (atom.next) |next| { atom = next; } else { // also pad with zeroes when last atom to ensure // segments are aligned. if (current_offset != segment.size) { try writer.writeByteNTimes(0, segment.size - current_offset); } break; } } } try writeVecSectionHeader( file, header_offset, .data, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, segment_count), ); } // Custom section "name" which contains symbol names { const Name = struct { index: u32, name: []const u8, fn lessThan(context: void, lhs: @This(), rhs: @This()) bool { _ = context; return lhs.index < rhs.index; } }; var funcs = try std.ArrayList(Name).initCapacity(self.base.allocator, self.functions.items.len + self.imported_functions_count); defer funcs.deinit(); var globals = try std.ArrayList(Name).initCapacity(self.base.allocator, self.globals.items.len); defer globals.deinit(); var segments = try std.ArrayList(Name).initCapacity(self.base.allocator, self.data_segments.count()); defer segments.deinit(); for (self.symbols.items) |symbol| { switch (symbol.tag) { .function => funcs.appendAssumeCapacity(.{ .index = symbol.index, .name = std.mem.sliceTo(symbol.name, 0) }), .global => globals.appendAssumeCapacity(.{ .index = symbol.index, .name = std.mem.sliceTo(symbol.name, 0) }), else => {}, } } // data segments are already 'ordered' for (self.data_segments.keys()) |key, index| { segments.appendAssumeCapacity(.{ .index = @intCast(u32, index), .name = key }); } std.sort.sort(Name, funcs.items, {}, Name.lessThan); std.sort.sort(Name, globals.items, {}, Name.lessThan); const header_offset = try reserveCustomSectionHeader(file); const writer = file.writer(); try leb.writeULEB128(writer, @intCast(u32, "name".len)); try writer.writeAll("name"); try self.emitNameSubsection(.function, funcs.items, writer); try self.emitNameSubsection(.global, globals.items, writer); try self.emitNameSubsection(.data_segment, segments.items, writer); try writeCustomSectionHeader( file, header_offset, @intCast(u32, (try file.getPos()) - header_offset - header_size), ); } } fn emitNameSubsection(self: *Wasm, section_id: std.wasm.NameSubsection, names: anytype, writer: anytype) !void { // We must emit subsection size, so first write to a temporary list var section_list = std.ArrayList(u8).init(self.base.allocator); defer section_list.deinit(); const sub_writer = section_list.writer(); try leb.writeULEB128(sub_writer, @intCast(u32, names.len)); for (names) |name| { try leb.writeULEB128(sub_writer, name.index); try leb.writeULEB128(sub_writer, @intCast(u32, name.name.len)); try sub_writer.writeAll(name.name); } // From now, write to the actual writer try leb.writeULEB128(writer, @enumToInt(section_id)); try leb.writeULEB128(writer, @intCast(u32, section_list.items.len)); try writer.writeAll(section_list.items); } fn emitLimits(writer: anytype, limits: wasm.Limits) !void { try leb.writeULEB128(writer, @boolToInt(limits.max != null)); try leb.writeULEB128(writer, limits.min); if (limits.max) |max| { try leb.writeULEB128(writer, max); } } fn emitInit(writer: anytype, init_expr: wasm.InitExpression) !void { switch (init_expr) { .i32_const => |val| { try writer.writeByte(wasm.opcode(.i32_const)); try leb.writeILEB128(writer, val); }, .i64_const => |val| { try writer.writeByte(wasm.opcode(.i64_const)); try leb.writeILEB128(writer, val); }, .f32_const => |val| { try writer.writeByte(wasm.opcode(.f32_const)); try writer.writeIntLittle(u32, @bitCast(u32, val)); }, .f64_const => |val| { try writer.writeByte(wasm.opcode(.f64_const)); try writer.writeIntLittle(u64, @bitCast(u64, val)); }, .global_get => |val| { try writer.writeByte(wasm.opcode(.global_get)); try leb.writeULEB128(writer, val); }, } try writer.writeByte(wasm.opcode(.end)); } fn emitImport(writer: anytype, import: wasm.Import) !void { try leb.writeULEB128(writer, @intCast(u32, import.module_name.len)); try writer.writeAll(import.module_name); try leb.writeULEB128(writer, @intCast(u32, import.name.len)); try writer.writeAll(import.name); try writer.writeByte(@enumToInt(import.kind)); switch (import.kind) { .function => |type_index| try leb.writeULEB128(writer, type_index), .global => |global_type| { try leb.writeULEB128(writer, wasm.valtype(global_type.valtype)); try writer.writeByte(@boolToInt(global_type.mutable)); }, .table => |table| { try leb.writeULEB128(writer, wasm.reftype(table.reftype)); try emitLimits(writer, table.limits); }, .memory => |limits| { try emitLimits(writer, limits); }, } } fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { const tracy = trace(@src()); defer tracy.end(); var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type. const full_out_path = try directory.join(arena, &[_][]const u8{self.base.options.emit.?.sub_path}); // If there is no Zig code to compile, then we should skip flushing the output file because it // will not be part of the linker line anyway. const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: { const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; if (use_stage1) { const obj_basename = try std.zig.binNameAlloc(arena, .{ .root_name = self.base.options.root_name, .target = self.base.options.target, .output_mode = .Obj, }); switch (self.base.options.cache_mode) { .incremental => break :blk try module.zig_cache_artifact_directory.join( arena, &[_][]const u8{obj_basename}, ), .whole => break :blk try fs.path.join(arena, &.{ fs.path.dirname(full_out_path).?, obj_basename, }), } } try self.flushModule(comp); if (fs.path.dirname(full_out_path)) |dirname| { break :blk try fs.path.join(arena, &.{ dirname, self.base.intermediary_basename.? }); } else { break :blk self.base.intermediary_basename.?; } } else null; const is_obj = self.base.options.output_mode == .Obj; const compiler_rt_path: ?[]const u8 = if (self.base.options.include_compiler_rt and !is_obj) comp.compiler_rt_static_lib.?.full_object_path else null; const target = self.base.options.target; const id_symlink_basename = "lld.id"; var man: Cache.Manifest = undefined; defer if (!self.base.options.disable_lld_caching) man.deinit(); var digest: [Cache.hex_digest_len]u8 = undefined; if (!self.base.options.disable_lld_caching) { man = comp.cache_parent.obtain(); // We are about to obtain this lock, so here we give other processes a chance first. self.base.releaseLock(); comptime assert(Compilation.link_hash_implementation_version == 2); for (self.base.options.objects) |obj| { _ = try man.addFile(obj.path, null); man.hash.add(obj.must_link); } for (comp.c_object_table.keys()) |key| { _ = try man.addFile(key.status.success.object_path, null); } try man.addOptionalFile(module_obj_path); try man.addOptionalFile(compiler_rt_path); man.hash.addOptionalBytes(self.base.options.entry); man.hash.addOptional(self.base.options.stack_size_override); man.hash.add(self.base.options.import_memory); man.hash.add(self.base.options.import_table); man.hash.add(self.base.options.export_table); man.hash.addOptional(self.base.options.initial_memory); man.hash.addOptional(self.base.options.max_memory); man.hash.addOptional(self.base.options.global_base); man.hash.add(self.base.options.export_symbol_names.len); // strip does not need to go into the linker hash because it is part of the hash namespace for (self.base.options.export_symbol_names) |symbol_name| { man.hash.addBytes(symbol_name); } // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock. _ = try man.hit(); digest = man.final(); var prev_digest_buf: [digest.len]u8 = undefined; const prev_digest: []u8 = Cache.readSmallFile( directory.handle, id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { log.debug("WASM LLD new_digest={s} error: {s}", .{ std.fmt.fmtSliceHexLower(&digest), @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; if (mem.eql(u8, prev_digest, &digest)) { log.debug("WASM LLD digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)}); // Hot diggity dog! The output binary is already there. self.base.lock = man.toOwnedLock(); return; } log.debug("WASM LLD prev_digest={s} new_digest={s}", .{ std.fmt.fmtSliceHexLower(prev_digest), std.fmt.fmtSliceHexLower(&digest) }); // We are about to change the output file to be different, so we invalidate the build hash now. directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { error.FileNotFound => {}, else => |e| return e, }; } if (is_obj) { // LLD's WASM driver does not support the equivalent of `-r` so we do a simple file copy // here. TODO: think carefully about how we can avoid this redundant operation when doing // build-obj. See also the corresponding TODO in linkAsArchive. const the_object_path = blk: { if (self.base.options.objects.len != 0) break :blk self.base.options.objects[0].path; if (comp.c_object_table.count() != 0) break :blk comp.c_object_table.keys()[0].status.success.object_path; if (module_obj_path) |p| break :blk p; // TODO I think this is unreachable. Audit this situation when solving the above TODO // regarding eliding redundant object -> object transformations. return error.NoObjectsToLink; }; // This can happen when using --enable-cache and using the stage1 backend. In this case // we can skip the file copy. if (!mem.eql(u8, the_object_path, full_out_path)) { try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{}); } } else { // Create an LLD command line and invoke it. var argv = std.ArrayList([]const u8).init(self.base.allocator); defer argv.deinit(); // We will invoke ourselves as a child process to gain access to LLD. // This is necessary because LLD does not behave properly as a library - // it calls exit() and does not reset all global data between invocations. try argv.appendSlice(&[_][]const u8{ comp.self_exe_path.?, "wasm-ld" }); try argv.append("-error-limit=0"); if (self.base.options.lto) { switch (self.base.options.optimize_mode) { .Debug => {}, .ReleaseSmall => try argv.append("-O2"), .ReleaseFast, .ReleaseSafe => try argv.append("-O3"), } } if (self.base.options.import_memory) { try argv.append("--import-memory"); } if (self.base.options.import_table) { assert(!self.base.options.export_table); try argv.append("--import-table"); } if (self.base.options.export_table) { assert(!self.base.options.import_table); try argv.append("--export-table"); } if (self.base.options.strip) { try argv.append("-s"); } if (self.base.options.initial_memory) |initial_memory| { const arg = try std.fmt.allocPrint(arena, "--initial-memory={d}", .{initial_memory}); try argv.append(arg); } if (self.base.options.max_memory) |max_memory| { const arg = try std.fmt.allocPrint(arena, "--max-memory={d}", .{max_memory}); try argv.append(arg); } if (self.base.options.global_base) |global_base| { const arg = try std.fmt.allocPrint(arena, "--global-base={d}", .{global_base}); try argv.append(arg); } else { // We prepend it by default, so when a stack overflow happens the runtime will trap correctly, // rather than silently overwrite all global declarations. See https://github.com/ziglang/zig/issues/4496 // // The user can overwrite this behavior by setting the global-base try argv.append("--stack-first"); } var auto_export_symbols = true; // Users are allowed to specify which symbols they want to export to the wasm host. for (self.base.options.export_symbol_names) |symbol_name| { const arg = try std.fmt.allocPrint(arena, "--export={s}", .{symbol_name}); try argv.append(arg); auto_export_symbols = false; } if (self.base.options.rdynamic) { try argv.append("--export-dynamic"); auto_export_symbols = false; } if (auto_export_symbols) { if (self.base.options.module) |module| { // when we use stage1, we use the exports that stage1 provided us. // For stage2, we can directly retrieve them from the module. const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; if (use_stage1) { for (comp.export_symbol_names.items) |symbol_name| { try argv.append(try std.fmt.allocPrint(arena, "--export={s}", .{symbol_name})); } } else { const skip_export_non_fn = target.os.tag == .wasi and self.base.options.wasi_exec_model == .command; for (module.decl_exports.values()) |exports| { for (exports) |exprt| { if (skip_export_non_fn and exprt.exported_decl.ty.zigTypeTag() != .Fn) { // skip exporting symbols when we're building a WASI command // and the symbol is not a function continue; } const symbol_name = exprt.exported_decl.name; const arg = try std.fmt.allocPrint(arena, "--export={s}", .{symbol_name}); try argv.append(arg); } } } } } if (self.base.options.entry) |entry| { try argv.append("--entry"); try argv.append(entry); } if (self.base.options.output_mode == .Exe) { // Increase the default stack size to a more reasonable value of 1MB instead of // the default of 1 Wasm page being 64KB, unless overridden by the user. try argv.append("-z"); const stack_size = self.base.options.stack_size_override orelse 1048576; const arg = try std.fmt.allocPrint(arena, "stack-size={d}", .{stack_size}); try argv.append(arg); if (self.base.options.wasi_exec_model == .reactor) { // Reactor execution model does not have _start so lld doesn't look for it. try argv.append("--no-entry"); } } else { if (self.base.options.stack_size_override) |stack_size| { try argv.append("-z"); const arg = try std.fmt.allocPrint(arena, "stack-size={d}", .{stack_size}); try argv.append(arg); } try argv.append("--no-entry"); // So lld doesn't look for _start. } try argv.appendSlice(&[_][]const u8{ "--allow-undefined", "-o", full_out_path, }); if (target.os.tag == .wasi) { const is_exe_or_dyn_lib = self.base.options.output_mode == .Exe or (self.base.options.output_mode == .Lib and self.base.options.link_mode == .Dynamic); if (is_exe_or_dyn_lib) { const wasi_emulated_libs = self.base.options.wasi_emulated_libs; for (wasi_emulated_libs) |crt_file| { try argv.append(try comp.get_libc_crt_file( arena, wasi_libc.emulatedLibCRFileLibName(crt_file), )); } if (self.base.options.link_libc) { try argv.append(try comp.get_libc_crt_file( arena, wasi_libc.execModelCrtFileFullName(self.base.options.wasi_exec_model), )); try argv.append(try comp.get_libc_crt_file(arena, "libc.a")); } if (self.base.options.link_libcpp) { try argv.append(comp.libcxx_static_lib.?.full_object_path); try argv.append(comp.libcxxabi_static_lib.?.full_object_path); } } } // Positional arguments to the linker such as object files. var whole_archive = false; for (self.base.options.objects) |obj| { if (obj.must_link and !whole_archive) { try argv.append("-whole-archive"); whole_archive = true; } else if (!obj.must_link and whole_archive) { try argv.append("-no-whole-archive"); whole_archive = false; } try argv.append(obj.path); } if (whole_archive) { try argv.append("-no-whole-archive"); whole_archive = false; } for (comp.c_object_table.keys()) |key| { try argv.append(key.status.success.object_path); } if (module_obj_path) |p| { try argv.append(p); } if (self.base.options.output_mode != .Obj and !self.base.options.skip_linker_dependencies and !self.base.options.link_libc) { try argv.append(comp.libc_static_lib.?.full_object_path); } if (compiler_rt_path) |p| { try argv.append(p); } if (self.base.options.verbose_link) { // Skip over our own name so that the LLD linker name is the first argv item. Compilation.dump_argv(argv.items[1..]); } // Sadly, we must run LLD as a child process because it does not behave // properly as a library. const child = try std.ChildProcess.init(argv.items, arena); defer child.deinit(); if (comp.clang_passthrough_mode) { child.stdin_behavior = .Inherit; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; const term = child.spawnAndWait() catch |err| { log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); return error.UnableToSpawnSelf; }; switch (term) { .Exited => |code| { if (code != 0) { // TODO https://github.com/ziglang/zig/issues/6342 std.process.exit(1); } }, else => std.process.abort(), } } else { child.stdin_behavior = .Ignore; child.stdout_behavior = .Ignore; child.stderr_behavior = .Pipe; try child.spawn(); const stderr = try child.stderr.?.reader().readAllAlloc(arena, 10 * 1024 * 1024); const term = child.wait() catch |err| { log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); return error.UnableToSpawnSelf; }; switch (term) { .Exited => |code| { if (code != 0) { // TODO parse this output and surface with the Compilation API rather than // directly outputting to stderr here. std.debug.print("{s}", .{stderr}); return error.LLDReportedFailure; } }, else => { log.err("{s} terminated with stderr:\n{s}", .{ argv.items[0], stderr }); return error.LLDCrashed; }, } if (stderr.len != 0) { log.warn("unexpected LLD stderr:\n{s}", .{stderr}); } } } if (!self.base.options.disable_lld_caching) { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { log.warn("failed to save linking hash digest symlink: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. self.base.lock = man.toOwnedLock(); } } fn reserveVecSectionHeader(file: fs.File) !u64 { // section id + fixed leb contents size + fixed leb vector length const header_size = 1 + 5 + 5; // TODO: this should be a single lseek(2) call, but fs.File does not // currently provide a way to do this. try file.seekBy(header_size); return (try file.getPos()) - header_size; } fn reserveCustomSectionHeader(file: fs.File) !u64 { // unlike regular section, we don't emit the count const header_size = 1 + 5; // TODO: this should be a single lseek(2) call, but fs.File does not // currently provide a way to do this. try file.seekBy(header_size); return (try file.getPos()) - header_size; } fn writeVecSectionHeader(file: fs.File, offset: u64, section: wasm.Section, size: u32, items: u32) !void { var buf: [1 + 5 + 5]u8 = undefined; buf[0] = @enumToInt(section); leb.writeUnsignedFixed(5, buf[1..6], size); leb.writeUnsignedFixed(5, buf[6..], items); try file.pwriteAll(&buf, offset); } fn writeCustomSectionHeader(file: fs.File, offset: u64, size: u32) !void { var buf: [1 + 5]u8 = undefined; buf[0] = 0; // 0 = 'custom' section leb.writeUnsignedFixed(5, buf[1..6], size); try file.pwriteAll(&buf, offset); } /// Searches for an a matching function signature, when not found /// a new entry will be made. The index of the existing/new signature will be returned. pub fn putOrGetFuncType(self: *Wasm, func_type: wasm.Type) !u32 { var index: u32 = 0; while (index < self.func_types.items.len) : (index += 1) { if (self.func_types.items[index].eql(func_type)) return index; } // functype does not exist. const params = try self.base.allocator.dupe(wasm.Valtype, func_type.params); errdefer self.base.allocator.free(params); const returns = try self.base.allocator.dupe(wasm.Valtype, func_type.returns); errdefer self.base.allocator.free(returns); try self.func_types.append(self.base.allocator, .{ .params = params, .returns = returns, }); return index; }
src/link/Wasm.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); pub fn HexTile(q: i8, r: i8) usize { return @intCast(usize, ((@intCast(i32, q) + 127) << 8) + (@intCast(i32, r) + 127)); } pub fn Q(ht: usize) i8 { return @intCast(i8, @intCast(i32, (ht >> 8)) - 127); } pub fn R(ht: usize) i8 { return @intCast(i8, @intCast(i32, (ht & 0xff)) - 127); } pub fn HexTileNeighbours(ht: usize) [6]usize { var q = Q(ht); var r = R(ht); return [_]usize{ HexTile(q + 1, r + 0), HexTile(q + 0, r - 1), HexTile(q - 1, r - 1), HexTile(q - 1, r + 0), HexTile(q + 0, r + 1), HexTile(q + 1, r + 1), }; } pub fn HexTileFromString(m: []const u8) usize { var q: i8 = 0; var r: i8 = 0; var i: usize = 0; while (i < m.len) : (i += 1) { switch (m[i]) { 'e' => { q += 1; }, 'w' => { q -= 1; }, 's' => { if (m[i + 1] == 'e') { r -= 1; } else { q -= 1; r -= 1; } i += 1; }, 'n' => { if (m[i + 1] == 'e') { q += 1; r += 1; } else { r += 1; } i += 1; }, else => { unreachable; }, } } return HexTile(q, r); } test "hex tile" { var ht = HexTileFromString("sesenwnenenewseeswwswswwnenewsewsw"); try aoc.assertEq(@as(i8, -3), Q(ht)); try aoc.assertEq(@as(i8, -2), R(ht)); var n = HexTileNeighbours(ht); try aoc.assertEq(@as(i8, -2), Q(n[0])); try aoc.assertEq(@as(i8, -2), R(n[0])); try aoc.assertEq(@as(i8, -3), Q(n[1])); try aoc.assertEq(@as(i8, -3), R(n[1])); try aoc.assertEq(@as(i8, -4), Q(n[2])); try aoc.assertEq(@as(i8, -3), R(n[2])); try aoc.assertEq(@as(i8, -4), Q(n[3])); try aoc.assertEq(@as(i8, -2), R(n[3])); try aoc.assertEq(@as(i8, -3), Q(n[4])); try aoc.assertEq(@as(i8, -1), R(n[4])); try aoc.assertEq(@as(i8, -2), Q(n[5])); try aoc.assertEq(@as(i8, -1), R(n[5])); } const HexLife = struct { pub const State = enum(u2) { white, black }; pub const BB = struct { qmin: i8, qmax: i8, rmin: i8, rmax: i8, alloc: std.mem.Allocator, pub fn init(alloc: std.mem.Allocator) !*BB { var s = try alloc.create(BB); s.alloc = alloc; s.qmin = std.math.maxInt(i8); s.qmax = std.math.minInt(i8); s.rmin = std.math.maxInt(i8); s.rmax = std.math.minInt(i8); return s; } pub fn deinit(s: *BB) void { s.alloc.destroy(s); } pub fn reset(s: *BB) void { s.qmin = std.math.maxInt(i8); s.qmax = std.math.minInt(i8); s.rmin = std.math.maxInt(i8); s.rmax = std.math.minInt(i8); } pub fn Update(s: *BB, q: i8, r: i8) void { if (q < s.qmin) { s.qmin = q; } if (q > s.qmax) { s.qmax = q; } if (r < s.rmin) { s.rmin = r; } if (r > s.rmax) { s.rmax = r; } } }; init: std.AutoHashMap(usize, State), alloc: std.mem.Allocator, debug: bool, pub fn init(alloc: std.mem.Allocator, in: [][]const u8) !*HexLife { var s = try alloc.create(HexLife); s.alloc = alloc; s.debug = false; s.init = std.AutoHashMap(usize, State).init(alloc); for (in) |line| { var ht = HexTileFromString(line); if (s.init.contains(ht)) { _ = s.init.remove(ht); } else { try s.init.put(ht, .black); } } return s; } pub fn deinit(s: *HexLife) void { s.init.deinit(); s.alloc.destroy(s); } pub fn part1(s: *HexLife) usize { return s.init.count(); } pub fn part2(s: *HexLife, days: usize) usize { var cur = std.AutoHashMap(usize, State).init(s.alloc); defer cur.deinit(); var cur_bb = BB.init(s.alloc) catch unreachable; defer cur_bb.deinit(); var it = s.init.iterator(); while (it.next()) |e| { var ht = e.key_ptr.*; cur.put(ht, .black) catch unreachable; cur_bb.Update(Q(ht), R(ht)); } var next = std.AutoHashMap(usize, State).init(s.alloc); defer next.deinit(); var day: usize = 1; var bc: usize = 0; var next_bb = BB.init(s.alloc) catch unreachable; defer next_bb.deinit(); while (day <= days) : (day += 1) { bc = 0; var q = cur_bb.qmin - 1; while (q <= cur_bb.qmax + 1) : (q += 1) { var r = cur_bb.rmin - 1; while (r <= cur_bb.rmax + 1) : (r += 1) { var nc: usize = 0; var ht = HexTile(q, r); for (HexTileNeighbours(ht)) |n| { var nst = cur.get(n) orelse .white; if (nst == .black) { nc += 1; } } var st = cur.get(ht) orelse .white; if ((st == .black and !(nc == 0 or nc > 2)) or (st == .white and nc == 2)) { next.put(ht, .black) catch unreachable; bc += 1; next_bb.Update(Q(ht), R(ht)); } } } if (s.debug) { std.debug.print("Day {}: {} ({})\n", .{ day, bc, next.count() }); } var tmp = cur; cur = next; next = tmp; next.clearAndFree(); var tmp_bb = cur_bb; cur_bb = next_bb; next_bb = tmp_bb; next_bb.reset(); } if (s.debug) { std.debug.print("N: {} - {} {} - {}\n", .{ cur_bb.qmin, cur_bb.qmax, cur_bb.rmin, cur_bb.rmax, }); } return bc; } }; test "hex life part1" { const test1 = aoc.readLines(aoc.talloc, aoc.test1file); defer aoc.talloc.free(test1); const inp = aoc.readLines(aoc.talloc, aoc.inputfile); defer aoc.talloc.free(inp); var gt = try HexLife.init(aoc.talloc, test1); defer gt.deinit(); try aoc.assertEq(@as(usize, 10), gt.part1()); var g = try HexLife.init(aoc.talloc, inp); defer g.deinit(); try aoc.assertEq(@as(usize, 307), g.part1()); } test "hex life part2" { const test1 = aoc.readLines(aoc.talloc, aoc.test1file); defer aoc.talloc.free(test1); const inp = aoc.readLines(aoc.talloc, aoc.inputfile); defer aoc.talloc.free(inp); var gt = try HexLife.init(aoc.talloc, test1); defer gt.deinit(); var g = try HexLife.init(aoc.talloc, inp); defer g.deinit(); try aoc.assertEq(@as(usize, 15), gt.part2(1)); try aoc.assertEq(@as(usize, 12), gt.part2(2)); try aoc.assertEq(@as(usize, 37), gt.part2(10)); try aoc.assertEq(@as(usize, 2208), gt.part2(100)); try aoc.assertEq(@as(usize, 3787), g.part2(100)); } fn day24(inp: []const u8, bench: bool) anyerror!void { const lines = aoc.readLines(aoc.halloc, inp); defer aoc.halloc.free(lines); var g = try HexLife.init(aoc.halloc, lines); defer g.deinit(); var p1 = g.part1(); var p2 = g.part2(100); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day24); }
2020/24/aoc.zig
const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const std = @import("std"); const mqtt_string = @import("../../mqtt_string.zig"); const Allocator = std.mem.Allocator; const FixedHeader = @import("../packet.zig").Packet.FixedHeader; const QoS = @import("../../qos.zig").QoS; pub const Publish = struct { duplicate: bool, qos: QoS, retain: bool, topic: []const u8, packet_id: ?u16 = null, payload: []const u8, pub const ParseError = error{ InvalidQoS, }; pub fn parse(fixed_header: FixedHeader, allocator: *Allocator, inner_reader: anytype) !Publish { // Hold this so we can query remaining bytes var limited_reader = std.io.limitedReader(inner_reader, fixed_header.remaining_length); const reader = limited_reader.reader(); const retain = (fixed_header.flags & 0b0001) == 1; const qos_int: u2 = @intCast(u2, @shrExact(fixed_header.flags & 0b0110, 1)); if (qos_int > 2) { return error.InvalidQoS; } const qos = @intToEnum(QoS, qos_int); const duplicate = @shrExact(fixed_header.flags & 0b1000, 3) == 1; const topic = try mqtt_string.read(allocator, reader); errdefer allocator.free(topic); const packet_id = switch (qos) { QoS.qos0 => null, QoS.qos1, QoS.qos2 => try reader.readIntBig(u16), }; const payload_length = limited_reader.bytes_left; const payload = try allocator.alloc(u8, payload_length); errdefer allocator.free(payload); try reader.readNoEof(payload); return Publish{ .retain = retain, .qos = qos, .duplicate = duplicate, .topic = topic, .packet_id = packet_id, .payload = payload, }; } pub fn serialize(self: Publish, writer: anytype) !void { try mqtt_string.write(self.topic, writer); switch (self.qos) { QoS.qos0 => {}, // No packet id QoS.qos1, QoS.qos2 => try writer.writeIntBig(u16, self.packet_id.?), // Serialize packet_id // TODO: handle missing packet_id more gracefully? } try writer.writeAll(self.payload); } pub fn serializedLength(self: Publish) u32 { var length: u32 = mqtt_string.serializedLength(self.topic) + @intCast(u32, self.payload.len); switch (self.qos) { QoS.qos0 => return length, // No packet id QoS.qos1, QoS.qos2 => return length + @sizeOf(u16), // Add space for packet id } } pub fn fixedHeaderFlags(self: Publish) u4 { var ret: u4 = @boolToInt(self.retain); ret |= @shlExact(@intCast(u4, @enumToInt(self.qos)), 1); ret |= @shlExact(@intCast(u4, @boolToInt(self.duplicate)), 3); return ret; } pub fn deinit(self: *Publish, allocator: *Allocator) void { allocator.free(self.topic); allocator.free(self.payload); } }; test "Publish payload parsing" { const allocator = std.testing.allocator; const buffer = // Topic length, 7 "\x00\x07" ++ // Topic "foo/bar" ++ // Packet ID, 42 "\x00\x2a" ++ // payload "baz"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.publish, .flags = 0b1101, // Retain + QoS 2 + DUP .remaining_length = @intCast(u32, buffer.len), }; var publish = try Publish.parse(fixed_header, allocator, stream); defer publish.deinit(allocator); try expect(publish.retain == true); try expect(publish.qos == .qos2); try expect(publish.duplicate == true); try expect(publish.packet_id.? == 42); try expectEqualSlices(u8, publish.topic, "foo/bar"); try expectEqualSlices(u8, publish.payload, "baz"); } test "QoS 0 and empty payload parsing" { const allocator = std.testing.allocator; const buffer = // Topic length, 7 "\x00\x07" ++ // Topic "foo/bar"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.publish, .flags = 0b0000, // No retain + QoS 0 + No DUP .remaining_length = @intCast(u32, buffer.len), }; var publish = try Publish.parse(fixed_header, allocator, stream); defer publish.deinit(allocator); try expect(publish.retain == false); try expect(publish.qos == .qos0); try expect(publish.duplicate == false); try expect(publish.packet_id == null); try expectEqualSlices(u8, publish.topic, "foo/bar"); try expectEqualSlices(u8, publish.payload, ""); } test "serialize/parse roundtrip" { const publish = Publish{ .retain = false, .qos = .qos1, .duplicate = false, .topic = "my/topic", .packet_id = 12, .payload = "henlo", }; var buffer = [_]u8{0} ** 100; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try publish.serialize(writer); const written = try stream.getPos(); stream.reset(); const reader = stream.reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.publish, .flags = 0b0010, .remaining_length = @intCast(u32, written), }; const allocator = std.testing.allocator; var deser_publish = try Publish.parse(fixed_header, allocator, reader); defer deser_publish.deinit(allocator); try expect(publish.retain == deser_publish.retain); try expect(publish.qos == deser_publish.qos); try expect(publish.duplicate == deser_publish.duplicate); try expect(publish.packet_id.? == deser_publish.packet_id.?); try expectEqualSlices(u8, publish.topic, deser_publish.topic); try expectEqualSlices(u8, publish.payload, deser_publish.payload); }
src/mqtt4/packet/publish.zig
const std = @import("std"); const Feature = @import("enums.zig").Feature; const Limits = @import("data.zig").Limits; const Device = @import("Device.zig"); const Adapter = @This(); /// The features which can be used to create devices on this adapter. features: []Feature, _features: [std.enums.values(Feature).len]Feature = undefined, /// The best limits which can be used to create devices on this adapter. /// /// Each adapter limit will be the same or better than its default value in supported limits. limits: Limits, /// If set to true indicates that the adapter is a fallback adapter. /// /// An adapter may be considered a fallback adapter if it has significant performance caveats in /// exchange for some combination of wider compatibility, more predictable behavior, or improved /// privacy. It is not guaranteed that a fallback adapter is available on every system. /// /// Always false on native implementations of WebGPU (TODO: why is this not queryable in Dawn?) fallback: bool, properties: Properties, /// The type erased pointer to the Adapter implementation /// Equal to c.WGPUAdapter for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, requestDevice: fn requestDevice( ptr: *anyopaque, descriptor: *const Device.Descriptor, callback: *RequestDeviceCallback, ) void, }; pub inline fn reference(adapter: Adapter) void { adapter.vtable.reference(adapter.ptr); } pub inline fn release(adapter: Adapter) void { adapter.vtable.release(adapter.ptr); } /// Tests of the given feature can be used to create devices on this adapter. pub fn hasFeature(adapter: Adapter, feature: Feature) bool { for (adapter.features) |f| { if (f == feature) return true; } return false; } pub const Properties = struct { vendor_id: u32, device_id: u32, name: []const u8, driver_description: []const u8, adapter_type: Type, backend_type: BackendType, }; pub const Type = enum(u32) { discrete_gpu, integrated_gpu, cpu, unknown, }; pub fn typeName(t: Type) []const u8 { return switch (t) { .discrete_gpu => "Discrete GPU", .integrated_gpu => "Integrated GPU", .cpu => "CPU", .unknown => "Unknown", }; } pub const BackendType = enum(u32) { nul, webgpu, d3d11, d3d12, metal, vulkan, opengl, opengles, }; pub fn backendTypeName(t: BackendType) []const u8 { return switch (t) { .nul => "Null", .webgpu => "WebGPU", .d3d11 => "D3D11", .d3d12 => "D3D12", .metal => "Metal", .vulkan => "Vulkan", .opengl => "OpenGL", .opengles => "OpenGLES", }; } pub const RequestDeviceErrorCode = error{ Error, Unknown, }; pub const RequestDeviceError = struct { message: []const u8, code: RequestDeviceErrorCode, }; pub const RequestDeviceResponseTag = enum { device, err, }; pub const RequestDeviceResponse = union(RequestDeviceResponseTag) { device: Device, err: RequestDeviceError, }; pub fn requestDevice( adapter: Adapter, descriptor: *const Device.Descriptor, callback: *RequestDeviceCallback, ) void { adapter.vtable.requestDevice(adapter.ptr, descriptor, callback); } pub const RequestDeviceCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, response: RequestDeviceResponse) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, response: RequestDeviceResponse) void, ) RequestDeviceCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, response: RequestDeviceResponse) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(@alignOf(Context), type_erased_ctx)), response); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; /// A helper which invokes requestDevice and blocks until the device is recieved. pub fn waitForDevice(adapter: Adapter, descriptor: *const Device.Descriptor) RequestDeviceResponse { var response: RequestDeviceResponse = undefined; var callback = RequestDeviceCallback.init(*RequestDeviceResponse, &response, (struct { pub fn callback(ctx: *RequestDeviceResponse, callback_response: RequestDeviceResponse) void { ctx.* = callback_response; } }).callback); adapter.requestDevice(descriptor, &callback); // TODO: FUTURE: Once crbug.com/dawn/1122 is fixed, we should process events here otherwise our // callback would not be invoked: //c.wgpuInstanceProcessEvents(adapter.instance) return response; } test { _ = VTable; _ = hasFeature; _ = Properties; _ = Type; _ = BackendType; _ = RequestDeviceErrorCode; _ = RequestDeviceError; _ = RequestDeviceResponse; _ = RequestDeviceCallback; _ = requestDevice; _ = waitForDevice; }
gpu/src/Adapter.zig
const std = @import("std"); const atomic = std.atomic; const fmt = std.fmt; const io = std.io; const math = std.math; const mem = std.mem; const zort = std.sort.sort; const unicode = std.unicode; const CccMap = @import("../components.zig").CombiningMap; const Normalizer = @import("../components.zig").Normalizer; const Props = @import("../components.zig").PropList; const Trie = @import("CollatorTrie.zig"); pub const AllKeysFile = @import("AllKeysFile.zig"); const Elements = @import("AllKeysFile.zig").Elements; allocator: *mem.Allocator, arena: std.heap.ArenaAllocator, implicits: []AllKeysFile.Implicit, normalizer: Normalizer, table: Trie, const Self = @This(); /// `init` produces a new Collator using the Default Unicode Collation Elements Table (DUCET) in `src/data/uca/allkeys.bin`. pub fn init(allocator: *mem.Allocator) !Self { var self = Self{ .allocator = allocator, .arena = std.heap.ArenaAllocator.init(allocator), .implicits = undefined, .normalizer = try Normalizer.init(allocator), .table = Trie.init(allocator), }; const allkeys = @embedFile("../data/uca/allkeys.bin"); var reader = std.io.fixedBufferStream(allkeys).reader(); var file = try AllKeysFile.decompress(allocator, reader); defer file.deinit(); while (file.next()) |entry| { try self.table.add(entry.key, entry.value); } self.implicits = file.implicits.toOwnedSlice(); return self; } /// `initWithReader` allows tailoring of the sorting algorithm via a supplied alternate weights table. The `reader` /// parameter can be a file, network stream, or anything else that exposes a `std.io.Reader`. pub fn initWithReader(allocator: *mem.Allocator, reader: anytype) !Self { var self = Self{ .allocator = allocator, .arena = std.heap.ArenaAllocator.init(allocator), .implicits = undefined, .normalizer = try Normalizer.init(allocator), .table = Trie.init(allocator), }; var file = try AllKeysFile.decompress(allocator, reader); defer file.deinit(); while (file.next()) |entry| { try self.table.add(entry.key, entry.value); } self.implicits = file.implicits.toOwnedSlice(); return self; } pub fn deinit(self: *Self) void { self.normalizer.deinit(); self.table.deinit(); self.arena.child_allocator.free(self.implicits); self.arena.deinit(); } pub fn collationElements(self: *Self, normalized: []const u21) ![]AllKeysFile.Element { var all_elements = std.ArrayList(AllKeysFile.Element).init(&self.arena.allocator); var code_points = normalized; var code_points_len = code_points.len; var cp_index: usize = 0; while (cp_index < code_points_len) { var lookup = self.table.find(code_points[cp_index..]); const S = code_points[0 .. cp_index + lookup.index + 1]; var elements = lookup.value; // elements for S. // handle non-starters var last_class: ?u8 = null; const tail_start = cp_index + lookup.index + 1; var tail_index: usize = tail_start; // Advance to last combining C. while (tail_index < code_points_len) : (tail_index += 1) { const combining_class = CccMap.combiningClass(code_points[tail_index]); if (combining_class == 0) { if (tail_index != tail_start) tail_index -= 1; break; } if (last_class) |last| { if (last >= combining_class) { if (tail_index != tail_start) tail_index -= 1; break; } } last_class = combining_class; } if (tail_index == code_points_len) tail_index -= 1; if (tail_index > tail_start) { const C = code_points[tail_index]; var new_key = try self.arena.allocator.alloc(u21, S.len + 1); mem.copy(u21, new_key, S); new_key[new_key.len - 1] = C; var new_lookup = self.table.find(new_key); if (new_lookup.index == (new_key.len - 1) and new_lookup.value != null) { cp_index = tail_start; // Splice var tmp = try self.arena.allocator.alloc(u21, code_points_len - 1); mem.copy(u21, tmp, code_points[0..tail_index]); if (tail_index + 1 < code_points_len) { mem.copy(u21, tmp[tail_index..], code_points[tail_index + 1 ..]); } code_points = tmp; code_points_len = code_points.len; // Add elements to final collection. for (new_lookup.value.?.items[0..new_lookup.value.?.len]) |element| { try all_elements.append(element); } continue; } } if (elements == null) { elements = self.implicitWeight(code_points[0]); } // Add elements to final collection. for (elements.?.items[0..elements.?.len]) |element| { try all_elements.append(element); } cp_index += lookup.index + 1; } return all_elements.toOwnedSlice(); } pub fn sortKeyFromCollationElements(self: *Self, collation_elements: []AllKeysFile.Element) ![]const u16 { var sort_key = std.ArrayList(u16).init(&self.arena.allocator); var level: usize = 0; while (level < 3) : (level += 1) { if (level != 0) try sort_key.append(0); // level separator for (collation_elements) |e| { switch (level) { 0 => if (e.l1 != 0) try sort_key.append(e.l1), 1 => if (e.l2 != 0) try sort_key.append(e.l2), 2 => if (e.l3 != 0) try sort_key.append(e.l3), else => unreachable, } } } return sort_key.toOwnedSlice(); } pub fn sortKey(self: *Self, str: []const u8) ![]const u16 { const normalized = try self.normalizer.normalizeToCodePoints(.canon, str); const collation_elements = try self.collationElements(normalized); return self.sortKeyFromCollationElements(collation_elements); } pub fn implicitWeight(self: Self, cp: u21) AllKeysFile.Elements { var base: u21 = 0; var aaaa: ?u21 = null; var bbbb: u21 = 0; if (Props.isUnifiedIdeograph(cp) and ((cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0xF900 and cp <= 0xFAFF))) { base = 0xFB40; aaaa = base + (cp >> 15); bbbb = (cp & 0x7FFF) | 0x8000; } else if (Props.isUnifiedIdeograph(cp) and !((cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0xF900 and cp <= 0xFAFF))) { base = 0xFB80; aaaa = base + (cp >> 15); bbbb = (cp & 0x7FFF) | 0x8000; } else { for (self.implicits) |weights| { if (cp >= weights.start and cp <= weights.end) { aaaa = weights.base; if (cp >= 0x18D00 and cp <= 0x18D8F) { bbbb = (cp - 17000) | 0x8000; } else { bbbb = (cp - weights.start) | 0x8000; } break; } } if (aaaa == null) { base = 0xFBC0; aaaa = base + (cp >> 15); bbbb = (cp & 0x7FFF) | 0x8000; } } var elements: Elements = undefined; elements.len = 2; elements.items[0] = .{ .l1 = @truncate(u16, aaaa.?), .l2 = 0x0020, .l3 = 0x0002 }; elements.items[1] = .{ .l1 = @truncate(u16, bbbb), .l2 = 0x0000, .l3 = 0x0000 }; return elements; } /// asciiCmp compares `a` with `b` returing a `math.Order` result. pub fn asciiCmp(a: []const u8, b: []const u8) math.Order { var long_is_a = true; var long = a; var short = b; if (a.len < b.len) { long_is_a = false; long = b; short = a; } for (short) |_, i| { if (short[i] == long[i]) continue; return if (long_is_a) math.order(long[i], short[i]) else math.order(short[i], long[i]); } return math.order(a.len, b.len); } test "Collator ASCII compare" { try testing.expectEqual(asciiCmp("abc", "def"), .lt); try testing.expectEqual(asciiCmp("Abc", "abc"), .lt); try testing.expectEqual(asciiCmp("abc", "abcd"), .lt); try testing.expectEqual(asciiCmp("abc", "abc"), .eq); try testing.expectEqual(asciiCmp("dbc", "abc"), .gt); try testing.expectEqual(asciiCmp("adc", "abc"), .gt); try testing.expectEqual(asciiCmp("abd", "abc"), .gt); } /// asciiAsc is a sort function producing ascending binary order of ASCII strings. pub fn asciiAsc(_: Self, a: []const u8, b: []const u8) bool { return asciiCmp(a, b) == .lt; } /// asciiDesc is a sort function producing descending binary order of ASCII strings. pub fn asciiDesc(_: Self, a: []const u8, b: []const u8) bool { return asciiCmp(a, b) == .gt; } pub const Level = enum(u2) { primary = 1, // different base letters. secondary, // different marks (i.e. accents). tertiary, // different letter case. pub fn incr(self: Level) Level { return switch (self) { .primary => .secondary, .secondary => .tertiary, .tertiary => .tertiary, }; } }; /// keyLevelCmp compares key `a` with key `b` up to the given level, returning a `math.Order`. pub fn keyLevelCmp(a: []const u16, b: []const u16, level: Level) math.Order { // Compare var long_is_a = true; var long = a; var short = b; var current_level: Level = .primary; if (a.len < b.len) { long_is_a = false; long = b; short = a; } return for (short) |_, i| { if (short[i] == long[i]) { if (short[i] == 0) { // New level. if (current_level == level) { break .eq; } current_level = current_level.incr(); } continue; } if (short[i] == 0) { // Short less than long. if (long_is_a) { break .gt; } else { break .lt; } } if (long[i] == 0) { // long less than short. if (long_is_a) { break .lt; } else { break .gt; } } break if (long_is_a) math.order(long[i], short[i]) else math.order(short[i], long[i]); } else .eq; } test "Collator keyLevelCmp" { var allocator = std.testing.allocator; var collator = try init(allocator); defer collator.deinit(); var key_a = try collator.sortKey("cab"); var key_b = try collator.sortKey("Cab"); try testing.expectEqual(keyLevelCmp(key_a, key_b, .tertiary), .lt); try testing.expectEqual(keyLevelCmp(key_a, key_b, .secondary), .eq); try testing.expectEqual(keyLevelCmp(key_a, key_b, .primary), .eq); key_a = try collator.sortKey("Cab"); key_b = try collator.sortKey("cáb"); try testing.expectEqual(keyLevelCmp(key_a, key_b, .tertiary), .lt); try testing.expectEqual(keyLevelCmp(key_a, key_b, .secondary), .lt); try testing.expectEqual(keyLevelCmp(key_a, key_b, .primary), .eq); key_a = try collator.sortKey("cáb"); key_b = try collator.sortKey("dab"); try testing.expectEqual(keyLevelCmp(key_a, key_b, .tertiary), .lt); try testing.expectEqual(keyLevelCmp(key_a, key_b, .secondary), .lt); try testing.expectEqual(keyLevelCmp(key_a, key_b, .primary), .lt); } /// tertiaryAsc is a sort function producing a full weight matching ascending sort. Since this /// function cannot return an error as per `sort.sort` requirements, it may cause a crash or undefined /// behavior under error conditions. pub fn tertiaryAsc(self: *Self, a: []const u8, b: []const u8) bool { return self.orderFn(a, b, .tertiary, .lt) catch unreachable; } /// tertiaryDesc is a sort function producing a full weight matching descending sort. Since this /// function cannot return an error as per `sort.sort` requirements, it may cause a crash or undefined /// behavior under error conditions. pub fn tertiaryDesc(self: *Self, a: []const u8, b: []const u8) bool { return self.orderFn(a, b, .tertiary, .gt) catch unreachable; } /// orderFn can be used to match, compare, and sort strings at various collation element levels and orderings. pub fn orderFn(self: *Self, a: []const u8, b: []const u8, level: Level, order: math.Order) !bool { var key_a = try self.sortKey(a); var key_b = try self.sortKey(b); return keyLevelCmp(key_a, key_b, level) == order; } /// sortAsc orders the strings in `strings` in ascending full tertiary level order. pub fn sortAsc(self: *Self, strings: [][]const u8) void { zort([]const u8, strings, self, tertiaryAsc); } /// sortDesc orders the strings in `strings` in ascending full tertiary level order. pub fn sortDesc(self: *Self, strings: [][]const u8) void { zort([]const u8, strings, self, tertiaryDesc); } /// sortAsciiAsc orders the strings in `strings` in ASCII ascending order. pub fn sortAsciiAsc(self: Self, strings: [][]const u8) void { zort([]const u8, strings, self, asciiAsc); } /// sortAsciiDesc orders the strings in `strings` in ASCII ascending order. pub fn sortAsciiDesc(self: Self, strings: [][]const u8) void { zort([]const u8, strings, self, asciiDesc); } const testing = std.testing; test "Collator sort" { var allocator = std.testing.allocator; var collator = try init(allocator); defer collator.deinit(); try testing.expect(collator.tertiaryAsc("abc", "def")); try testing.expect(collator.tertiaryDesc("def", "abc")); try testing.expect(collator.asciiAsc("abc", "def")); try testing.expect(collator.asciiDesc("def", "abc")); try testing.expect(try collator.orderFn("José", "jose", .primary, .eq)); var strings: [3][]const u8 = .{ "xyz", "def", "abc" }; collator.sortAsc(&strings); try testing.expectEqual(strings[0], "abc"); try testing.expectEqual(strings[1], "def"); try testing.expectEqual(strings[2], "xyz"); collator.sortDesc(&strings); try testing.expectEqual(strings[0], "xyz"); try testing.expectEqual(strings[1], "def"); try testing.expectEqual(strings[2], "abc"); strings = .{ "xyz", "def", "abc" }; collator.sortAsciiAsc(&strings); try testing.expectEqual(strings[0], "abc"); try testing.expectEqual(strings[1], "def"); try testing.expectEqual(strings[2], "xyz"); collator.sortAsciiDesc(&strings); try testing.expectEqual(strings[0], "xyz"); try testing.expectEqual(strings[1], "def"); try testing.expectEqual(strings[2], "abc"); } test "Collator UCA" { var path_buf: [1024]u8 = undefined; var path = try std.fs.cwd().realpath(".", &path_buf); // Check if testing in this library path. if (!mem.endsWith(u8, path, "ziglyph")) return; const uca_tests = "src/data/uca/CollationTest_NON_IGNORABLE_SHORT.txt"; var file = try std.fs.cwd().openFile(uca_tests, .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()).reader(); var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var buf: [1024]u8 = undefined; // Skip header. var line_no: usize = 1; while (try buf_reader.readUntilDelimiterOrEof(&buf, '\n')) |line| : (line_no += 1) { if (line.len == 0) { line_no += 1; break; } } var prev_key: []const u16 = &[_]u16{}; var collator = try init(allocator); defer collator.deinit(); var cp_buf: [4]u8 = undefined; lines: while (try buf_reader.readUntilDelimiterOrEof(&buf, '\n')) |line| : (line_no += 1) { if (line.len == 0 or line[0] == '#') continue; //std.debug.print("line {d}: {s}\n", .{ line_no, line }); var bytes = std.ArrayList(u8).init(allocator); var cp_strs = mem.split(u8, line, " "); while (cp_strs.next()) |cp_str| { const cp = try fmt.parseInt(u21, cp_str, 16); const len = unicode.utf8Encode(cp, &cp_buf) catch continue :lines; try bytes.appendSlice(cp_buf[0..len]); } const current_key = try collator.sortKey(bytes.items); if (prev_key.len == 0) { prev_key = current_key; continue; } try testing.expect((keyLevelCmp(prev_key, current_key, .tertiary) == .eq) or (keyLevelCmp(prev_key, current_key, .tertiary) == .lt)); prev_key = current_key; } }
src/collator/Collator.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const TypeId = std.builtin.TypeId; const maxInt = std.math.maxInt; /// Returns the square root of x. /// /// Special Cases: /// - sqrt(+inf) = +inf /// - sqrt(+-0) = +-0 /// - sqrt(x) = nan if x < 0 /// - sqrt(nan) = nan /// TODO Decide if all this logic should be implemented directly in the @sqrt bultin function. pub fn sqrt(x: anytype) Sqrt(@TypeOf(x)) { const T = @TypeOf(x); switch (@typeInfo(T)) { .Float, .ComptimeFloat => return @sqrt(x), .ComptimeInt => comptime { if (x > maxInt(u128)) { @compileError("sqrt not implemented for comptime_int greater than 128 bits"); } if (x < 0) { @compileError("sqrt on negative number"); } return @as(T, sqrt_int(u128, x)); }, .Int => |IntType| switch (IntType.signedness) { .signed => return @compileError("sqrt not implemented for signed integers"), .unsigned => return sqrt_int(T, x), }, else => @compileError("sqrt not implemented for " ++ @typeName(T)), } } fn sqrt_int(comptime T: type, value: T) Sqrt(T) { switch (T) { u0 => return 0, u1 => return value, else => {}, } var op = value; var res: T = 0; var one: T = 1 << (@typeInfo(T).Int.bits - 2); // "one" starts at the highest power of four <= than the argument. while (one > op) { one >>= 2; } while (one != 0) { if (op >= res + one) { op -= res + one; res += 2 * one; } res >>= 1; one >>= 2; } const ResultType = Sqrt(T); return @intCast(ResultType, res); } test "math.sqrt_int" { try expect(sqrt_int(u0, 0) == 0); try expect(sqrt_int(u1, 1) == 1); try expect(sqrt_int(u32, 3) == 1); try expect(sqrt_int(u32, 4) == 2); try expect(sqrt_int(u32, 5) == 2); try expect(sqrt_int(u32, 8) == 2); try expect(sqrt_int(u32, 9) == 3); try expect(sqrt_int(u32, 10) == 3); } /// Returns the return type `sqrt` will return given an operand of type `T`. pub fn Sqrt(comptime T: type) type { return switch (@typeInfo(T)) { .Int => |int| { return switch (int.bits) { 0 => u0, 1 => u1, else => std.meta.Int(.unsigned, int.bits / 2), }; }, else => T, }; }
lib/std/math/sqrt.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day13.txt"); // const data = @embedFile("../data/day13-tst.txt"); pub fn main() !void { var it = tokenize(u8, data, "\r\n"); var points = List([2]usize).init(gpa); defer points.deinit(); var folds = List(Fold).init(gpa); defer folds.deinit(); while (it.next()) |line| { if (std.mem.startsWith(u8, line, "fold")) { var fold_it = tokenize(u8, line, "fold along ="); var dir = if (fold_it.next().?[0] == 'x') Dir.x else Dir.y; var index = try parseInt(usize, fold_it.next().?, 10); try folds.append(Fold{ .dir = dir, .index = index }); } else { var points_it = tokenize(u8, line, ","); var x = try parseInt(usize, points_it.next().?, 10); var y = try parseInt(usize, points_it.next().?, 10); try points.append([2]usize{ x, y }); } } // Part 1 fold(&points.items, folds.items[0]); var set = Map([2]usize, void).init(gpa); defer set.deinit(); for (points.items) |point| { try set.put(point, {}); } print("{}\n", .{set.count()}); // Part 2 for (folds.items[1..]) |the_fold| { fold(&points.items, the_fold); } printGrid(points.items); } fn cmpValue(_: void, a: [2]usize, b: [2]usize) bool { if (a[0] < b[0]) return true; if (a[0] > b[0]) return false; if (a[1] < b[1]) return true; return false; } const Dir = enum { x, y }; const Fold = struct { dir: Dir, index: usize, }; fn fold(points: *[][2]usize, the_fold: Fold) void { var coord: usize = switch (the_fold.dir) { .x => 0, .y => 1, }; for (points.*) |*point| { if (point[coord] > the_fold.index) { point[coord] = 2 * the_fold.index - point[coord]; } } std.sort.sort([2]usize, points.*, {}, cmpValue); } fn printGrid(points: [][2]usize) void { var xmax: usize = 0; var ymax: usize = 0; for (points) |p| { xmax = max(p[0], xmax); ymax = max(p[1], ymax); } var grid = List(bool).init(gpa); defer grid.deinit(); grid.resize((xmax + 1) * (ymax + 1)) catch unreachable; for (points) |p| { var index: usize = p[0] + p[1] * (xmax + 1); grid.items[index] = true; } var y: usize = 0; while (y < ymax + 1) : (y += 1) { var x: usize = 0; while (x < xmax + 1) : (x += 1) { var index = x + y * (xmax + 1); if (grid.items[index]) { print("{c}", .{'#'}); } else { print("{c}", .{'.'}); } } print("\n", .{}); } } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day13.zig
const std = @import("std"); const print = std.debug.print; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; var file = try std.fs.cwd().openFile( "./inputs/day05.txt", .{ .read = true, }, ); var buf_file = std.io.bufferedReader(file.reader()); var word_buffer = std.ArrayList(u8).init(allocator); defer word_buffer.deinit(); var nice_1_words: usize = 0; var nice_2_words: usize = 0; while (true) { buf_file.reader().readUntilDelimiterArrayList(&word_buffer, '\n', 100) catch break; if (nice_1(word_buffer.items)) { nice_1_words += 1; } if (nice_2(word_buffer.items)) { nice_2_words += 1; } } print("Part 1 | Number of nice words: {d}\n", .{nice_1_words}); print("Part 2 | Number of nice words: {d}\n", .{nice_2_words}); } fn nice_1(str: []u8) bool { var vowel_count: usize = 0; var prev_letter: ?u8 = null; var at_least_one_repeat = false; for (str) |c| { switch (c) { 'a', 'e', 'i', 'o', 'u' => vowel_count += 1, else => {}, } if (prev_letter) |p| { if (p == c) { at_least_one_repeat = true; } if (p == 'a' and c == 'b') { return false; } if (p == 'c' and c == 'd') { return false; } if (p == 'p' and c == 'q') { return false; } if (p == 'x' and c == 'y') { return false; } } prev_letter = c; } return at_least_one_repeat and vowel_count >= 3; } fn contains(haystack: []u8, needle: []u8) bool { if (needle.len > haystack.len) { return false; } for (haystack) |_, i| { if (haystack.len - i < needle.len) { return false; } if (std.mem.eql(u8, haystack[i .. i + needle.len], needle)) { return true; } } return false; } fn nice_2(str: []u8) bool { var at_least_one_repeat = false; var at_least_one_pair = false; for (str) |_, i| { if (i + 3 < str.len) { if (contains(str[i + 2 ..], str[i .. i + 2])) { at_least_one_pair = true; } } if (i + 2 < str.len) { if (str[i] == str[i + 2]) { at_least_one_repeat = true; } } } return at_least_one_pair and at_least_one_repeat; }
src/day05.zig
const std = @import("std"); // used to get monotonic time, as opposed to wall-clock time var timer: ?std.time.Timer = null; fn nanotime() u64 { if (timer == null) { timer = std.time.Timer.start() catch unreachable; } return timer.?.read(); } // holds the frame, and the nanotime of // when the frame should be resumed const Delay = struct { frame: anyframe, expires: u64, }; // suspend the caller, to be resumed later by the event loop fn waitForTime(time_ms: u64) void { suspend timer_queue.add(Delay{ .frame = @frame(), .expires = nanotime() + (time_ms * std.time.ns_per_ms), }) catch unreachable; } fn waitUntilAndPrint( time1: u64, time2: u64, name: []const u8, ) void { const start = nanotime(); // suspend self, to be woken up when time1 has passed waitForTime(time1); std.debug.print( "[{s}] it is now {} ms since start!\n", .{ name, (nanotime() - start) / std.time.ns_per_ms }, ); // suspend self, to be woken up when time2 has passed waitForTime(time2); std.debug.print( "[{s}] it is now {} ms since start!\n", .{ name, (nanotime() - start) / std.time.ns_per_ms }, ); } fn asyncMain() void { // stores the async frames of our tasks var tasks = [_]@Frame(waitUntilAndPrint){ async waitUntilAndPrint(1000, 1200, "task-pair a"), async waitUntilAndPrint(500, 1300, "task-pair b"), }; // |*t| is used, as |t| would be a *const @Frame(...) // which cannot be awaited upon for (tasks) |*t| await t; } // priority queue of tasks // lower .expires => higher priority => to be executed before var timer_queue: std.PriorityQueue(Delay) = undefined; fn cmp(a: Delay, b: Delay) bool { return a.expires < b.expires; } pub fn main() !void { timer_queue = std.PriorityQueue(Delay).init( std.heap.page_allocator, cmp, ); defer timer_queue.deinit(); var main_task = async asyncMain(); // the body of the event loop // pops the task which is to be next executed while (timer_queue.removeOrNull()) |delay| { // wait until it is time to execute next task const now = nanotime(); if (now < delay.expires) { std.time.sleep(delay.expires - now); } // execute next task resume delay.frame; } nosuspend await main_task; }
src/main.zig
pub const WSDAPI_OPTION_MAX_INBOUND_MESSAGE_SIZE = @as(u32, 1); pub const WSDAPI_OPTION_TRACE_XML_TO_DEBUGGER = @as(u32, 2); pub const WSDAPI_OPTION_TRACE_XML_TO_FILE = @as(u32, 3); pub const WSDAPI_SSL_CERT_APPLY_DEFAULT_CHECKS = @as(u32, 0); pub const WSDAPI_SSL_CERT_IGNORE_REVOCATION = @as(u32, 1); pub const WSDAPI_SSL_CERT_IGNORE_EXPIRY = @as(u32, 2); pub const WSDAPI_SSL_CERT_IGNORE_WRONG_USAGE = @as(u32, 4); pub const WSDAPI_SSL_CERT_IGNORE_UNKNOWN_CA = @as(u32, 8); pub const WSDAPI_SSL_CERT_IGNORE_INVALID_CN = @as(u32, 16); pub const WSDAPI_COMPACTSIG_ACCEPT_ALL_MESSAGES = @as(u32, 1); pub const WSD_SECURITY_HTTP_AUTH_SCHEME_NEGOTIATE = @as(u32, 1); pub const WSD_SECURITY_HTTP_AUTH_SCHEME_NTLM = @as(u32, 2); pub const WSDAPI_ADDRESSFAMILY_IPV4 = @as(u32, 1); pub const WSDAPI_ADDRESSFAMILY_IPV6 = @as(u32, 2); //-------------------------------------------------------------------------------- // Section: Types (110) //-------------------------------------------------------------------------------- pub const WSD_CONFIG_PARAM_TYPE = enum(i32) { CONFIG_MAX_INBOUND_MESSAGE_SIZE = 1, CONFIG_MAX_OUTBOUND_MESSAGE_SIZE = 2, SECURITY_SSL_CERT_FOR_CLIENT_AUTH = 3, SECURITY_SSL_SERVER_CERT_VALIDATION = 4, SECURITY_SSL_CLIENT_CERT_VALIDATION = 5, SECURITY_SSL_NEGOTIATE_CLIENT_CERT = 6, SECURITY_COMPACTSIG_SIGNING_CERT = 7, SECURITY_COMPACTSIG_VALIDATION = 8, CONFIG_HOSTING_ADDRESSES = 9, CONFIG_DEVICE_ADDRESSES = 10, SECURITY_REQUIRE_HTTP_CLIENT_AUTH = 11, SECURITY_REQUIRE_CLIENT_CERT_OR_HTTP_CLIENT_AUTH = 12, SECURITY_USE_HTTP_CLIENT_AUTH = 13, }; pub const WSD_CONFIG_MAX_INBOUND_MESSAGE_SIZE = WSD_CONFIG_PARAM_TYPE.CONFIG_MAX_INBOUND_MESSAGE_SIZE; pub const WSD_CONFIG_MAX_OUTBOUND_MESSAGE_SIZE = WSD_CONFIG_PARAM_TYPE.CONFIG_MAX_OUTBOUND_MESSAGE_SIZE; pub const WSD_SECURITY_SSL_CERT_FOR_CLIENT_AUTH = WSD_CONFIG_PARAM_TYPE.SECURITY_SSL_CERT_FOR_CLIENT_AUTH; pub const WSD_SECURITY_SSL_SERVER_CERT_VALIDATION = WSD_CONFIG_PARAM_TYPE.SECURITY_SSL_SERVER_CERT_VALIDATION; pub const WSD_SECURITY_SSL_CLIENT_CERT_VALIDATION = WSD_CONFIG_PARAM_TYPE.SECURITY_SSL_CLIENT_CERT_VALIDATION; pub const WSD_SECURITY_SSL_NEGOTIATE_CLIENT_CERT = WSD_CONFIG_PARAM_TYPE.SECURITY_SSL_NEGOTIATE_CLIENT_CERT; pub const WSD_SECURITY_COMPACTSIG_SIGNING_CERT = WSD_CONFIG_PARAM_TYPE.SECURITY_COMPACTSIG_SIGNING_CERT; pub const WSD_SECURITY_COMPACTSIG_VALIDATION = WSD_CONFIG_PARAM_TYPE.SECURITY_COMPACTSIG_VALIDATION; pub const WSD_CONFIG_HOSTING_ADDRESSES = WSD_CONFIG_PARAM_TYPE.CONFIG_HOSTING_ADDRESSES; pub const WSD_CONFIG_DEVICE_ADDRESSES = WSD_CONFIG_PARAM_TYPE.CONFIG_DEVICE_ADDRESSES; pub const WSD_SECURITY_REQUIRE_HTTP_CLIENT_AUTH = WSD_CONFIG_PARAM_TYPE.SECURITY_REQUIRE_HTTP_CLIENT_AUTH; pub const WSD_SECURITY_REQUIRE_CLIENT_CERT_OR_HTTP_CLIENT_AUTH = WSD_CONFIG_PARAM_TYPE.SECURITY_REQUIRE_CLIENT_CERT_OR_HTTP_CLIENT_AUTH; pub const WSD_SECURITY_USE_HTTP_CLIENT_AUTH = WSD_CONFIG_PARAM_TYPE.SECURITY_USE_HTTP_CLIENT_AUTH; pub const WSD_CONFIG_PARAM = extern struct { configParamType: WSD_CONFIG_PARAM_TYPE, pConfigData: ?*anyopaque, dwConfigDataSize: u32, }; pub const WSD_SECURITY_CERT_VALIDATION_V1 = extern struct { certMatchArray: ?*?*CERT_CONTEXT, dwCertMatchArrayCount: u32, hCertMatchStore: ?*anyopaque, hCertIssuerStore: ?*anyopaque, dwCertCheckOptions: u32, }; pub const WSD_SECURITY_CERT_VALIDATION = extern struct { certMatchArray: ?*?*CERT_CONTEXT, dwCertMatchArrayCount: u32, hCertMatchStore: ?*anyopaque, hCertIssuerStore: ?*anyopaque, dwCertCheckOptions: u32, pszCNGHashAlgId: ?[*:0]const u16, pbCertHash: ?*u8, dwCertHashSize: u32, }; pub const WSD_SECURITY_SIGNATURE_VALIDATION = extern struct { signingCertArray: ?*?*CERT_CONTEXT, dwSigningCertArrayCount: u32, hSigningCertStore: ?*anyopaque, dwFlags: u32, }; pub const WSD_CONFIG_ADDRESSES = extern struct { addresses: ?*?*IWSDAddress, dwAddressCount: u32, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDAddress_Value = @import("../zig.zig").Guid.initString("b9574c6c-12a6-4f74-93a1-3318ff605759"); pub const IID_IWSDAddress = &IID_IWSDAddress_Value; pub const IWSDAddress = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Serialize: fn( self: *const IWSDAddress, pszBuffer: [*:0]u16, cchLength: u32, fSafe: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Deserialize: fn( self: *const IWSDAddress, pszBuffer: ?[*:0]const 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 IWSDAddress_Serialize(self: *const T, pszBuffer: [*:0]u16, cchLength: u32, fSafe: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAddress.VTable, self.vtable).Serialize(@ptrCast(*const IWSDAddress, self), pszBuffer, cchLength, fSafe); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAddress_Deserialize(self: *const T, pszBuffer: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAddress.VTable, self.vtable).Deserialize(@ptrCast(*const IWSDAddress, self), pszBuffer); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDTransportAddress_Value = @import("../zig.zig").Guid.initString("70d23498-4ee6-4340-a3df-d845d2235467"); pub const IID_IWSDTransportAddress = &IID_IWSDTransportAddress_Value; pub const IWSDTransportAddress = extern struct { pub const VTable = extern struct { base: IWSDAddress.VTable, GetPort: fn( self: *const IWSDTransportAddress, pwPort: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPort: fn( self: *const IWSDTransportAddress, wPort: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransportAddress: fn( self: *const IWSDTransportAddress, ppszAddress: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransportAddressEx: fn( self: *const IWSDTransportAddress, fSafe: BOOL, ppszAddress: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransportAddress: fn( self: *const IWSDTransportAddress, pszAddress: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDAddress.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDTransportAddress_GetPort(self: *const T, pwPort: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDTransportAddress.VTable, self.vtable).GetPort(@ptrCast(*const IWSDTransportAddress, self), pwPort); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDTransportAddress_SetPort(self: *const T, wPort: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDTransportAddress.VTable, self.vtable).SetPort(@ptrCast(*const IWSDTransportAddress, self), wPort); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDTransportAddress_GetTransportAddress(self: *const T, ppszAddress: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDTransportAddress.VTable, self.vtable).GetTransportAddress(@ptrCast(*const IWSDTransportAddress, self), ppszAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDTransportAddress_GetTransportAddressEx(self: *const T, fSafe: BOOL, ppszAddress: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDTransportAddress.VTable, self.vtable).GetTransportAddressEx(@ptrCast(*const IWSDTransportAddress, self), fSafe, ppszAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDTransportAddress_SetTransportAddress(self: *const T, pszAddress: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDTransportAddress.VTable, self.vtable).SetTransportAddress(@ptrCast(*const IWSDTransportAddress, self), pszAddress); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDMessageParameters_Value = @import("../zig.zig").Guid.initString("1fafe8a2-e6fc-4b80-b6cf-b7d45c416d7c"); pub const IID_IWSDMessageParameters = &IID_IWSDMessageParameters_Value; pub const IWSDMessageParameters = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLocalAddress: fn( self: *const IWSDMessageParameters, ppAddress: ?*?*IWSDAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLocalAddress: fn( self: *const IWSDMessageParameters, pAddress: ?*IWSDAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRemoteAddress: fn( self: *const IWSDMessageParameters, ppAddress: ?*?*IWSDAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRemoteAddress: fn( self: *const IWSDMessageParameters, pAddress: ?*IWSDAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLowerParameters: fn( self: *const IWSDMessageParameters, ppTxParams: ?*?*IWSDMessageParameters, ) 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 IWSDMessageParameters_GetLocalAddress(self: *const T, ppAddress: ?*?*IWSDAddress) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMessageParameters.VTable, self.vtable).GetLocalAddress(@ptrCast(*const IWSDMessageParameters, self), ppAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDMessageParameters_SetLocalAddress(self: *const T, pAddress: ?*IWSDAddress) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMessageParameters.VTable, self.vtable).SetLocalAddress(@ptrCast(*const IWSDMessageParameters, self), pAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDMessageParameters_GetRemoteAddress(self: *const T, ppAddress: ?*?*IWSDAddress) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMessageParameters.VTable, self.vtable).GetRemoteAddress(@ptrCast(*const IWSDMessageParameters, self), ppAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDMessageParameters_SetRemoteAddress(self: *const T, pAddress: ?*IWSDAddress) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMessageParameters.VTable, self.vtable).SetRemoteAddress(@ptrCast(*const IWSDMessageParameters, self), pAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDMessageParameters_GetLowerParameters(self: *const T, ppTxParams: ?*?*IWSDMessageParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMessageParameters.VTable, self.vtable).GetLowerParameters(@ptrCast(*const IWSDMessageParameters, self), ppTxParams); } };} pub usingnamespace MethodMixin(@This()); }; pub const WSDUdpRetransmitParams = extern struct { ulSendDelay: u32, ulRepeat: u32, ulRepeatMinDelay: u32, ulRepeatMaxDelay: u32, ulRepeatUpperDelay: u32, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDUdpMessageParameters_Value = @import("../zig.zig").Guid.initString("9934149f-8f0c-447b-aa0b-73124b0ca7f0"); pub const IID_IWSDUdpMessageParameters = &IID_IWSDUdpMessageParameters_Value; pub const IWSDUdpMessageParameters = extern struct { pub const VTable = extern struct { base: IWSDMessageParameters.VTable, SetRetransmitParams: fn( self: *const IWSDUdpMessageParameters, pParams: ?*const WSDUdpRetransmitParams, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRetransmitParams: fn( self: *const IWSDUdpMessageParameters, pParams: ?*WSDUdpRetransmitParams, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDMessageParameters.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpMessageParameters_SetRetransmitParams(self: *const T, pParams: ?*const WSDUdpRetransmitParams) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpMessageParameters.VTable, self.vtable).SetRetransmitParams(@ptrCast(*const IWSDUdpMessageParameters, self), pParams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpMessageParameters_GetRetransmitParams(self: *const T, pParams: ?*WSDUdpRetransmitParams) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpMessageParameters.VTable, self.vtable).GetRetransmitParams(@ptrCast(*const IWSDUdpMessageParameters, self), pParams); } };} pub usingnamespace MethodMixin(@This()); }; pub const WSDUdpMessageType = enum(i32) { ONE_WAY = 0, TWO_WAY = 1, }; pub const ONE_WAY = WSDUdpMessageType.ONE_WAY; pub const TWO_WAY = WSDUdpMessageType.TWO_WAY; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDUdpAddress_Value = @import("../zig.zig").Guid.initString("74d6124a-a441-4f78-a1eb-97a8d1996893"); pub const IID_IWSDUdpAddress = &IID_IWSDUdpAddress_Value; pub const IWSDUdpAddress = extern struct { pub const VTable = extern struct { base: IWSDTransportAddress.VTable, SetSockaddr: fn( self: *const IWSDUdpAddress, pSockAddr: ?*const SOCKADDR_STORAGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSockaddr: fn( self: *const IWSDUdpAddress, pSockAddr: ?*SOCKADDR_STORAGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetExclusive: fn( self: *const IWSDUdpAddress, fExclusive: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExclusive: fn( self: *const IWSDUdpAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMessageType: fn( self: *const IWSDUdpAddress, messageType: WSDUdpMessageType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessageType: fn( self: *const IWSDUdpAddress, pMessageType: ?*WSDUdpMessageType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTTL: fn( self: *const IWSDUdpAddress, dwTTL: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTTL: fn( self: *const IWSDUdpAddress, pdwTTL: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAlias: fn( self: *const IWSDUdpAddress, pAlias: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAlias: fn( self: *const IWSDUdpAddress, pAlias: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDTransportAddress.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_SetSockaddr(self: *const T, pSockAddr: ?*const SOCKADDR_STORAGE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).SetSockaddr(@ptrCast(*const IWSDUdpAddress, self), pSockAddr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_GetSockaddr(self: *const T, pSockAddr: ?*SOCKADDR_STORAGE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).GetSockaddr(@ptrCast(*const IWSDUdpAddress, self), pSockAddr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_SetExclusive(self: *const T, fExclusive: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).SetExclusive(@ptrCast(*const IWSDUdpAddress, self), fExclusive); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_GetExclusive(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).GetExclusive(@ptrCast(*const IWSDUdpAddress, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_SetMessageType(self: *const T, messageType: WSDUdpMessageType) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).SetMessageType(@ptrCast(*const IWSDUdpAddress, self), messageType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_GetMessageType(self: *const T, pMessageType: ?*WSDUdpMessageType) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).GetMessageType(@ptrCast(*const IWSDUdpAddress, self), pMessageType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_SetTTL(self: *const T, dwTTL: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).SetTTL(@ptrCast(*const IWSDUdpAddress, self), dwTTL); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_GetTTL(self: *const T, pdwTTL: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).GetTTL(@ptrCast(*const IWSDUdpAddress, self), pdwTTL); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_SetAlias(self: *const T, pAlias: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).SetAlias(@ptrCast(*const IWSDUdpAddress, self), pAlias); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDUdpAddress_GetAlias(self: *const T, pAlias: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDUdpAddress.VTable, self.vtable).GetAlias(@ptrCast(*const IWSDUdpAddress, self), pAlias); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDHttpMessageParameters_Value = @import("../zig.zig").Guid.initString("540bd122-5c83-4dec-b396-ea62a2697fdf"); pub const IID_IWSDHttpMessageParameters = &IID_IWSDHttpMessageParameters_Value; pub const IWSDHttpMessageParameters = extern struct { pub const VTable = extern struct { base: IWSDMessageParameters.VTable, SetInboundHttpHeaders: fn( self: *const IWSDHttpMessageParameters, pszHeaders: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInboundHttpHeaders: fn( self: *const IWSDHttpMessageParameters, ppszHeaders: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutboundHttpHeaders: fn( self: *const IWSDHttpMessageParameters, pszHeaders: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutboundHttpHeaders: fn( self: *const IWSDHttpMessageParameters, ppszHeaders: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetID: fn( self: *const IWSDHttpMessageParameters, pszId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetID: fn( self: *const IWSDHttpMessageParameters, ppszId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContext: fn( self: *const IWSDHttpMessageParameters, pContext: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContext: fn( self: *const IWSDHttpMessageParameters, ppContext: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IWSDHttpMessageParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDMessageParameters.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_SetInboundHttpHeaders(self: *const T, pszHeaders: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).SetInboundHttpHeaders(@ptrCast(*const IWSDHttpMessageParameters, self), pszHeaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_GetInboundHttpHeaders(self: *const T, ppszHeaders: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).GetInboundHttpHeaders(@ptrCast(*const IWSDHttpMessageParameters, self), ppszHeaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_SetOutboundHttpHeaders(self: *const T, pszHeaders: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).SetOutboundHttpHeaders(@ptrCast(*const IWSDHttpMessageParameters, self), pszHeaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_GetOutboundHttpHeaders(self: *const T, ppszHeaders: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).GetOutboundHttpHeaders(@ptrCast(*const IWSDHttpMessageParameters, self), ppszHeaders); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_SetID(self: *const T, pszId: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).SetID(@ptrCast(*const IWSDHttpMessageParameters, self), pszId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_GetID(self: *const T, ppszId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).GetID(@ptrCast(*const IWSDHttpMessageParameters, self), ppszId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_SetContext(self: *const T, pContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).SetContext(@ptrCast(*const IWSDHttpMessageParameters, self), pContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_GetContext(self: *const T, ppContext: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).GetContext(@ptrCast(*const IWSDHttpMessageParameters, self), ppContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpMessageParameters_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpMessageParameters.VTable, self.vtable).Clear(@ptrCast(*const IWSDHttpMessageParameters, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDHttpAddress_Value = @import("../zig.zig").Guid.initString("d09ac7bd-2a3e-4b85-8605-2737ff3e4ea0"); pub const IID_IWSDHttpAddress = &IID_IWSDHttpAddress_Value; pub const IWSDHttpAddress = extern struct { pub const VTable = extern struct { base: IWSDTransportAddress.VTable, GetSecure: fn( self: *const IWSDHttpAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecure: fn( self: *const IWSDHttpAddress, fSecure: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPath: fn( self: *const IWSDHttpAddress, ppszPath: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPath: fn( self: *const IWSDHttpAddress, pszPath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDTransportAddress.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpAddress_GetSecure(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAddress.VTable, self.vtable).GetSecure(@ptrCast(*const IWSDHttpAddress, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpAddress_SetSecure(self: *const T, fSecure: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAddress.VTable, self.vtable).SetSecure(@ptrCast(*const IWSDHttpAddress, self), fSecure); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpAddress_GetPath(self: *const T, ppszPath: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAddress.VTable, self.vtable).GetPath(@ptrCast(*const IWSDHttpAddress, self), ppszPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpAddress_SetPath(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAddress.VTable, self.vtable).SetPath(@ptrCast(*const IWSDHttpAddress, self), pszPath); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWSDSSLClientCertificate_Value = @import("../zig.zig").Guid.initString("de105e87-a0da-418e-98ad-27b9eed87bdc"); pub const IID_IWSDSSLClientCertificate = &IID_IWSDSSLClientCertificate_Value; pub const IWSDSSLClientCertificate = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetClientCertificate: fn( self: *const IWSDSSLClientCertificate, ppCertContext: ?*?*CERT_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMappedAccessToken: fn( self: *const IWSDSSLClientCertificate, phToken: ?*?HANDLE, ) 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 IWSDSSLClientCertificate_GetClientCertificate(self: *const T, ppCertContext: ?*?*CERT_CONTEXT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSSLClientCertificate.VTable, self.vtable).GetClientCertificate(@ptrCast(*const IWSDSSLClientCertificate, self), ppCertContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDSSLClientCertificate_GetMappedAccessToken(self: *const T, phToken: ?*?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSSLClientCertificate.VTable, self.vtable).GetMappedAccessToken(@ptrCast(*const IWSDSSLClientCertificate, self), phToken); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWSDHttpAuthParameters_Value = @import("../zig.zig").Guid.initString("0b476df0-8dac-480d-b05c-99781a5884aa"); pub const IID_IWSDHttpAuthParameters = &IID_IWSDHttpAuthParameters_Value; pub const IWSDHttpAuthParameters = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetClientAccessToken: fn( self: *const IWSDHttpAuthParameters, phToken: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAuthType: fn( self: *const IWSDHttpAuthParameters, pAuthType: ?*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 IWSDHttpAuthParameters_GetClientAccessToken(self: *const T, phToken: ?*?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAuthParameters.VTable, self.vtable).GetClientAccessToken(@ptrCast(*const IWSDHttpAuthParameters, self), phToken); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDHttpAuthParameters_GetAuthType(self: *const T, pAuthType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDHttpAuthParameters.VTable, self.vtable).GetAuthType(@ptrCast(*const IWSDHttpAuthParameters, self), pAuthType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWSDSignatureProperty_Value = @import("../zig.zig").Guid.initString("03ce20aa-71c4-45e2-b32e-3766c61c790f"); pub const IID_IWSDSignatureProperty = &IID_IWSDSignatureProperty_Value; pub const IWSDSignatureProperty = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, IsMessageSigned: fn( self: *const IWSDSignatureProperty, pbSigned: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsMessageSignatureTrusted: fn( self: *const IWSDSignatureProperty, pbSignatureTrusted: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKeyInfo: fn( self: *const IWSDSignatureProperty, // TODO: what to do with BytesParamIndex 1? pbKeyInfo: ?*u8, pdwKeyInfoSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignature: fn( self: *const IWSDSignatureProperty, // TODO: what to do with BytesParamIndex 1? pbSignature: ?*u8, pdwSignatureSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignedInfoHash: fn( self: *const IWSDSignatureProperty, // TODO: what to do with BytesParamIndex 1? pbSignedInfoHash: ?*u8, pdwHashSize: ?*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 IWSDSignatureProperty_IsMessageSigned(self: *const T, pbSigned: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSignatureProperty.VTable, self.vtable).IsMessageSigned(@ptrCast(*const IWSDSignatureProperty, self), pbSigned); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDSignatureProperty_IsMessageSignatureTrusted(self: *const T, pbSignatureTrusted: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSignatureProperty.VTable, self.vtable).IsMessageSignatureTrusted(@ptrCast(*const IWSDSignatureProperty, self), pbSignatureTrusted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDSignatureProperty_GetKeyInfo(self: *const T, pbKeyInfo: ?*u8, pdwKeyInfoSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSignatureProperty.VTable, self.vtable).GetKeyInfo(@ptrCast(*const IWSDSignatureProperty, self), pbKeyInfo, pdwKeyInfoSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDSignatureProperty_GetSignature(self: *const T, pbSignature: ?*u8, pdwSignatureSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSignatureProperty.VTable, self.vtable).GetSignature(@ptrCast(*const IWSDSignatureProperty, self), pbSignature, pdwSignatureSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDSignatureProperty_GetSignedInfoHash(self: *const T, pbSignedInfoHash: ?*u8, pdwHashSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDSignatureProperty.VTable, self.vtable).GetSignedInfoHash(@ptrCast(*const IWSDSignatureProperty, self), pbSignedInfoHash, pdwHashSize); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDAttachment_Value = @import("../zig.zig").Guid.initString("5d55a616-9df8-4b09-b156-9ba351a48b76"); pub const IID_IWSDAttachment = &IID_IWSDAttachment_Value; pub const IWSDAttachment = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDOutboundAttachment_Value = @import("../zig.zig").Guid.initString("aa302f8d-5a22-4ba5-b392-aa8486f4c15d"); pub const IID_IWSDOutboundAttachment = &IID_IWSDOutboundAttachment_Value; pub const IWSDOutboundAttachment = extern struct { pub const VTable = extern struct { base: IWSDAttachment.VTable, Write: fn( self: *const IWSDOutboundAttachment, pBuffer: [*:0]const u8, dwBytesToWrite: u32, pdwNumberOfBytesWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWSDOutboundAttachment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Abort: fn( self: *const IWSDOutboundAttachment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDAttachment.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDOutboundAttachment_Write(self: *const T, pBuffer: [*:0]const u8, dwBytesToWrite: u32, pdwNumberOfBytesWritten: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDOutboundAttachment.VTable, self.vtable).Write(@ptrCast(*const IWSDOutboundAttachment, self), pBuffer, dwBytesToWrite, pdwNumberOfBytesWritten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDOutboundAttachment_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDOutboundAttachment.VTable, self.vtable).Close(@ptrCast(*const IWSDOutboundAttachment, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDOutboundAttachment_Abort(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDOutboundAttachment.VTable, self.vtable).Abort(@ptrCast(*const IWSDOutboundAttachment, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDInboundAttachment_Value = @import("../zig.zig").Guid.initString("5bd6ca65-233c-4fb8-9f7a-2641619655c9"); pub const IID_IWSDInboundAttachment = &IID_IWSDInboundAttachment_Value; pub const IWSDInboundAttachment = extern struct { pub const VTable = extern struct { base: IWSDAttachment.VTable, Read: fn( self: *const IWSDInboundAttachment, pBuffer: [*:0]u8, dwBytesToRead: u32, pdwNumberOfBytesRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWSDInboundAttachment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDAttachment.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDInboundAttachment_Read(self: *const T, pBuffer: [*:0]u8, dwBytesToRead: u32, pdwNumberOfBytesRead: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDInboundAttachment.VTable, self.vtable).Read(@ptrCast(*const IWSDInboundAttachment, self), pBuffer, dwBytesToRead, pdwNumberOfBytesRead); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDInboundAttachment_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDInboundAttachment.VTable, self.vtable).Close(@ptrCast(*const IWSDInboundAttachment, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const WSD_DATETIME = extern struct { isPositive: BOOL, year: u32, month: u8, day: u8, hour: u8, minute: u8, second: u8, millisecond: u32, TZIsLocal: BOOL, TZIsPositive: BOOL, TZHour: u8, TZMinute: u8, }; pub const WSD_DURATION = extern struct { isPositive: BOOL, year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32, millisecond: u32, }; pub const WSDXML_OP = enum(i32) { None = 0, EndOfTable = 1, BeginElement_ = 2, BeginAnyElement = 3, EndElement = 4, Element_ = 5, AnyElement = 6, AnyElements = 7, AnyText = 8, Attribute_ = 9, BeginChoice = 10, EndChoice = 11, BeginSequence = 12, EndSequence = 13, BeginAll = 14, EndAll = 15, Anything = 16, AnyNumber = 17, OneOrMore = 18, Optional = 19, FormatBool_ = 20, FormatInt8_ = 21, FormatInt16_ = 22, FormatInt32_ = 23, FormatInt64_ = 24, FormatUInt8_ = 25, FormatUInt16_ = 26, FormatUInt32_ = 27, FormatUInt64_ = 28, FormatUnicodeString_ = 29, FormatDom_ = 30, FormatStruct_ = 31, FormatUri_ = 32, FormatUuidUri_ = 33, FormatName_ = 34, FormatListInsertTail_ = 35, FormatType_ = 36, FormatDynamicType_ = 37, FormatLookupType_ = 38, FormatDuration_ = 39, FormatDateTime_ = 40, FormatFloat_ = 41, FormatDouble_ = 42, Process_ = 43, QualifiedAttribute_ = 44, FormatXMLDeclaration_ = 45, FormatMax = 46, }; pub const OpNone = WSDXML_OP.None; pub const OpEndOfTable = WSDXML_OP.EndOfTable; pub const OpBeginElement_ = WSDXML_OP.BeginElement_; pub const OpBeginAnyElement = WSDXML_OP.BeginAnyElement; pub const OpEndElement = WSDXML_OP.EndElement; pub const OpElement_ = WSDXML_OP.Element_; pub const OpAnyElement = WSDXML_OP.AnyElement; pub const OpAnyElements = WSDXML_OP.AnyElements; pub const OpAnyText = WSDXML_OP.AnyText; pub const OpAttribute_ = WSDXML_OP.Attribute_; pub const OpBeginChoice = WSDXML_OP.BeginChoice; pub const OpEndChoice = WSDXML_OP.EndChoice; pub const OpBeginSequence = WSDXML_OP.BeginSequence; pub const OpEndSequence = WSDXML_OP.EndSequence; pub const OpBeginAll = WSDXML_OP.BeginAll; pub const OpEndAll = WSDXML_OP.EndAll; pub const OpAnything = WSDXML_OP.Anything; pub const OpAnyNumber = WSDXML_OP.AnyNumber; pub const OpOneOrMore = WSDXML_OP.OneOrMore; pub const OpOptional = WSDXML_OP.Optional; pub const OpFormatBool_ = WSDXML_OP.FormatBool_; pub const OpFormatInt8_ = WSDXML_OP.FormatInt8_; pub const OpFormatInt16_ = WSDXML_OP.FormatInt16_; pub const OpFormatInt32_ = WSDXML_OP.FormatInt32_; pub const OpFormatInt64_ = WSDXML_OP.FormatInt64_; pub const OpFormatUInt8_ = WSDXML_OP.FormatUInt8_; pub const OpFormatUInt16_ = WSDXML_OP.FormatUInt16_; pub const OpFormatUInt32_ = WSDXML_OP.FormatUInt32_; pub const OpFormatUInt64_ = WSDXML_OP.FormatUInt64_; pub const OpFormatUnicodeString_ = WSDXML_OP.FormatUnicodeString_; pub const OpFormatDom_ = WSDXML_OP.FormatDom_; pub const OpFormatStruct_ = WSDXML_OP.FormatStruct_; pub const OpFormatUri_ = WSDXML_OP.FormatUri_; pub const OpFormatUuidUri_ = WSDXML_OP.FormatUuidUri_; pub const OpFormatName_ = WSDXML_OP.FormatName_; pub const OpFormatListInsertTail_ = WSDXML_OP.FormatListInsertTail_; pub const OpFormatType_ = WSDXML_OP.FormatType_; pub const OpFormatDynamicType_ = WSDXML_OP.FormatDynamicType_; pub const OpFormatLookupType_ = WSDXML_OP.FormatLookupType_; pub const OpFormatDuration_ = WSDXML_OP.FormatDuration_; pub const OpFormatDateTime_ = WSDXML_OP.FormatDateTime_; pub const OpFormatFloat_ = WSDXML_OP.FormatFloat_; pub const OpFormatDouble_ = WSDXML_OP.FormatDouble_; pub const OpProcess_ = WSDXML_OP.Process_; pub const OpQualifiedAttribute_ = WSDXML_OP.QualifiedAttribute_; pub const OpFormatXMLDeclaration_ = WSDXML_OP.FormatXMLDeclaration_; pub const OpFormatMax = WSDXML_OP.FormatMax; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDXMLContext_Value = @import("../zig.zig").Guid.initString("75d8f3ee-3e5a-43b4-a15a-bcf6887460c0"); pub const IID_IWSDXMLContext = &IID_IWSDXMLContext_Value; pub const IWSDXMLContext = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddNamespace: fn( self: *const IWSDXMLContext, pszUri: ?[*:0]const u16, pszSuggestedPrefix: ?[*:0]const u16, ppNamespace: ?*?*WSDXML_NAMESPACE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddNameToNamespace: fn( self: *const IWSDXMLContext, pszUri: ?[*:0]const u16, pszName: ?[*:0]const u16, ppName: ?*?*WSDXML_NAME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNamespaces: fn( self: *const IWSDXMLContext, pNamespaces: [*]const ?*const WSDXML_NAMESPACE, wNamespacesCount: u16, bLayerNumber: u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTypes: fn( self: *const IWSDXMLContext, pTypes: [*]const ?*const WSDXML_TYPE, dwTypesCount: u32, bLayerNumber: 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 IWSDXMLContext_AddNamespace(self: *const T, pszUri: ?[*:0]const u16, pszSuggestedPrefix: ?[*:0]const u16, ppNamespace: ?*?*WSDXML_NAMESPACE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDXMLContext.VTable, self.vtable).AddNamespace(@ptrCast(*const IWSDXMLContext, self), pszUri, pszSuggestedPrefix, ppNamespace); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDXMLContext_AddNameToNamespace(self: *const T, pszUri: ?[*:0]const u16, pszName: ?[*:0]const u16, ppName: ?*?*WSDXML_NAME) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDXMLContext.VTable, self.vtable).AddNameToNamespace(@ptrCast(*const IWSDXMLContext, self), pszUri, pszName, ppName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDXMLContext_SetNamespaces(self: *const T, pNamespaces: [*]const ?*const WSDXML_NAMESPACE, wNamespacesCount: u16, bLayerNumber: u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDXMLContext.VTable, self.vtable).SetNamespaces(@ptrCast(*const IWSDXMLContext, self), pNamespaces, wNamespacesCount, bLayerNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDXMLContext_SetTypes(self: *const T, pTypes: [*]const ?*const WSDXML_TYPE, dwTypesCount: u32, bLayerNumber: u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDXMLContext.VTable, self.vtable).SetTypes(@ptrCast(*const IWSDXMLContext, self), pTypes, dwTypesCount, bLayerNumber); } };} pub usingnamespace MethodMixin(@This()); }; pub const WSDXML_NAMESPACE = extern struct { Uri: ?[*:0]const u16, PreferredPrefix: ?[*:0]const u16, Names: ?*WSDXML_NAME, NamesCount: u16, Encoding: u16, }; pub const WSDXML_NAME = extern struct { Space: ?*WSDXML_NAMESPACE, LocalName: ?PWSTR, }; pub const WSDXML_TYPE = extern struct { Uri: ?[*:0]const u16, Table: ?*const u8, }; pub const WSDXML_PREFIX_MAPPING = extern struct { Refs: u32, Next: ?*WSDXML_PREFIX_MAPPING, Space: ?*WSDXML_NAMESPACE, Prefix: ?PWSTR, }; pub const WSDXML_ATTRIBUTE = extern struct { Element: ?*WSDXML_ELEMENT, Next: ?*WSDXML_ATTRIBUTE, Name: ?*WSDXML_NAME, Value: ?PWSTR, }; pub const WSDXML_NODE = extern struct { Type: i32, Parent: ?*WSDXML_ELEMENT, Next: ?*WSDXML_NODE, }; pub const WSDXML_ELEMENT = extern struct { Node: WSDXML_NODE, Name: ?*WSDXML_NAME, FirstAttribute: ?*WSDXML_ATTRIBUTE, FirstChild: ?*WSDXML_NODE, PrefixMappings: ?*WSDXML_PREFIX_MAPPING, }; pub const WSDXML_TEXT = extern struct { Node: WSDXML_NODE, Text: ?PWSTR, }; pub const WSDXML_ELEMENT_LIST = extern struct { Next: ?*WSDXML_ELEMENT_LIST, Element: ?*WSDXML_ELEMENT, }; pub const WSD_STUB_FUNCTION = fn( server: ?*IUnknown, session: ?*IWSDServiceMessaging, event: ?*WSD_EVENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const DeviceDiscoveryMechanism = enum(i32) { MulticastDiscovery = 0, DirectedDiscovery = 1, SecureDirectedDiscovery = 2, }; pub const MulticastDiscovery = DeviceDiscoveryMechanism.MulticastDiscovery; pub const DirectedDiscovery = DeviceDiscoveryMechanism.DirectedDiscovery; pub const SecureDirectedDiscovery = DeviceDiscoveryMechanism.SecureDirectedDiscovery; pub const WSD_PROTOCOL_TYPE = enum(i32) { NONE = 0, UDP = 1, HTTP = 2, HTTPS = 4, ALL = 255, }; pub const WSD_PT_NONE = WSD_PROTOCOL_TYPE.NONE; pub const WSD_PT_UDP = WSD_PROTOCOL_TYPE.UDP; pub const WSD_PT_HTTP = WSD_PROTOCOL_TYPE.HTTP; pub const WSD_PT_HTTPS = WSD_PROTOCOL_TYPE.HTTPS; pub const WSD_PT_ALL = WSD_PROTOCOL_TYPE.ALL; pub const WSD_OPERATION = extern struct { RequestType: ?*WSDXML_TYPE, ResponseType: ?*WSDXML_TYPE, RequestStubFunction: ?WSD_STUB_FUNCTION, }; pub const PWSD_SOAP_MESSAGE_HANDLER = fn( thisUnknown: ?*IUnknown, event: ?*WSD_EVENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WSD_HANDLER_CONTEXT = extern struct { Handler: ?PWSD_SOAP_MESSAGE_HANDLER, PVoid: ?*anyopaque, Unknown: ?*IUnknown, }; pub const WSDEventType = enum(i32) { NONE = 0, INCOMING_MESSAGE = 1, INCOMING_FAULT = 2, TRANSMISSION_FAILURE = 3, RESPONSE_TIMEOUT = 4, }; pub const WSDET_NONE = WSDEventType.NONE; pub const WSDET_INCOMING_MESSAGE = WSDEventType.INCOMING_MESSAGE; pub const WSDET_INCOMING_FAULT = WSDEventType.INCOMING_FAULT; pub const WSDET_TRANSMISSION_FAILURE = WSDEventType.TRANSMISSION_FAILURE; pub const WSDET_RESPONSE_TIMEOUT = WSDEventType.RESPONSE_TIMEOUT; pub const WSD_SYNCHRONOUS_RESPONSE_CONTEXT = extern struct { hr: HRESULT, eventHandle: ?HANDLE, messageParameters: ?*IWSDMessageParameters, results: ?*anyopaque, }; pub const WSD_PORT_TYPE = extern struct { EncodedName: u32, OperationCount: u32, Operations: ?*WSD_OPERATION, ProtocolType: WSD_PROTOCOL_TYPE, }; pub const WSD_RELATIONSHIP_METADATA = extern struct { Type: ?[*:0]const u16, Data: ?*WSD_HOST_METADATA, Any: ?*WSDXML_ELEMENT, }; pub const WSD_SERVICE_METADATA_LIST = extern struct { Next: ?*WSD_SERVICE_METADATA_LIST, Element: ?*WSD_SERVICE_METADATA, }; pub const WSD_HOST_METADATA = extern struct { Host: ?*WSD_SERVICE_METADATA, Hosted: ?*WSD_SERVICE_METADATA_LIST, }; pub const WSD_ENDPOINT_REFERENCE_LIST = extern struct { Next: ?*WSD_ENDPOINT_REFERENCE_LIST, Element: ?*WSD_ENDPOINT_REFERENCE, }; pub const WSD_SERVICE_METADATA = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE_LIST, Types: ?*WSD_NAME_LIST, ServiceId: ?[*:0]const u16, Any: ?*WSDXML_ELEMENT, }; pub const WSD_THIS_DEVICE_METADATA = extern struct { FriendlyName: ?*WSD_LOCALIZED_STRING_LIST, FirmwareVersion: ?[*:0]const u16, SerialNumber: ?[*:0]const u16, Any: ?*WSDXML_ELEMENT, }; pub const WSD_THIS_MODEL_METADATA = extern struct { Manufacturer: ?*WSD_LOCALIZED_STRING_LIST, ManufacturerUrl: ?[*:0]const u16, ModelName: ?*WSD_LOCALIZED_STRING_LIST, ModelNumber: ?[*:0]const u16, ModelUrl: ?[*:0]const u16, PresentationUrl: ?[*:0]const u16, Any: ?*WSDXML_ELEMENT, }; pub const WSD_LOCALIZED_STRING_LIST = extern struct { Next: ?*WSD_LOCALIZED_STRING_LIST, Element: ?*WSD_LOCALIZED_STRING, }; pub const WSD_SOAP_FAULT_REASON = extern struct { Text: ?*WSD_LOCALIZED_STRING_LIST, }; pub const WSD_SOAP_FAULT_SUBCODE = extern struct { Value: ?*WSDXML_NAME, Subcode: ?*WSD_SOAP_FAULT_SUBCODE, }; pub const WSD_SOAP_FAULT_CODE = extern struct { Value: ?*WSDXML_NAME, Subcode: ?*WSD_SOAP_FAULT_SUBCODE, }; pub const WSD_SOAP_FAULT = extern struct { Code: ?*WSD_SOAP_FAULT_CODE, Reason: ?*WSD_SOAP_FAULT_REASON, Node: ?[*:0]const u16, Role: ?[*:0]const u16, Detail: ?*WSDXML_ELEMENT, }; pub const WSD_APP_SEQUENCE = extern struct { InstanceId: u64, SequenceId: ?[*:0]const u16, MessageNumber: u64, }; pub const WSD_HEADER_RELATESTO = extern struct { RelationshipType: ?*WSDXML_NAME, MessageID: ?[*:0]const u16, }; pub const WSD_SOAP_HEADER = extern struct { To: ?[*:0]const u16, Action: ?[*:0]const u16, MessageID: ?[*:0]const u16, RelatesTo: WSD_HEADER_RELATESTO, ReplyTo: ?*WSD_ENDPOINT_REFERENCE, From: ?*WSD_ENDPOINT_REFERENCE, FaultTo: ?*WSD_ENDPOINT_REFERENCE, AppSequence: ?*WSD_APP_SEQUENCE, AnyHeaders: ?*WSDXML_ELEMENT, }; pub const WSD_SOAP_MESSAGE = extern struct { Header: WSD_SOAP_HEADER, Body: ?*anyopaque, BodyType: ?*WSDXML_TYPE, }; pub const WSD_RESOLVE_MATCHES = extern struct { ResolveMatch: ?*WSD_RESOLVE_MATCH, Any: ?*WSDXML_ELEMENT, }; pub const WSD_RESOLVE_MATCH = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE, Types: ?*WSD_NAME_LIST, Scopes: ?*WSD_SCOPES, XAddrs: ?*WSD_URI_LIST, MetadataVersion: u64, Any: ?*WSDXML_ELEMENT, }; pub const WSD_RESOLVE = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE, Any: ?*WSDXML_ELEMENT, }; pub const WSD_PROBE_MATCH = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE, Types: ?*WSD_NAME_LIST, Scopes: ?*WSD_SCOPES, XAddrs: ?*WSD_URI_LIST, MetadataVersion: u64, Any: ?*WSDXML_ELEMENT, }; pub const WSD_PROBE_MATCH_LIST = extern struct { Next: ?*WSD_PROBE_MATCH_LIST, Element: ?*WSD_PROBE_MATCH, }; pub const WSD_PROBE_MATCHES = extern struct { ProbeMatch: ?*WSD_PROBE_MATCH_LIST, Any: ?*WSDXML_ELEMENT, }; pub const WSD_PROBE = extern struct { Types: ?*WSD_NAME_LIST, Scopes: ?*WSD_SCOPES, Any: ?*WSDXML_ELEMENT, }; pub const WSD_BYE = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE, Any: ?*WSDXML_ELEMENT, }; pub const WSD_SCOPES = extern struct { MatchBy: ?[*:0]const u16, Scopes: ?*WSD_URI_LIST, }; pub const WSD_NAME_LIST = extern struct { Next: ?*WSD_NAME_LIST, Element: ?*WSDXML_NAME, }; pub const WSD_HELLO = extern struct { EndpointReference: ?*WSD_ENDPOINT_REFERENCE, Types: ?*WSD_NAME_LIST, Scopes: ?*WSD_SCOPES, XAddrs: ?*WSD_URI_LIST, MetadataVersion: u64, Any: ?*WSDXML_ELEMENT, }; pub const WSD_REFERENCE_PARAMETERS = extern struct { Any: ?*WSDXML_ELEMENT, }; pub const WSD_REFERENCE_PROPERTIES = extern struct { Any: ?*WSDXML_ELEMENT, }; pub const WSD_ENDPOINT_REFERENCE = extern struct { Address: ?[*:0]const u16, ReferenceProperties: WSD_REFERENCE_PROPERTIES, ReferenceParameters: WSD_REFERENCE_PARAMETERS, PortType: ?*WSDXML_NAME, ServiceName: ?*WSDXML_NAME, Any: ?*WSDXML_ELEMENT, }; pub const WSD_METADATA_SECTION = extern struct { Dialect: ?[*:0]const u16, Identifier: ?[*:0]const u16, Data: ?*anyopaque, MetadataReference: ?*WSD_ENDPOINT_REFERENCE, Location: ?[*:0]const u16, Any: ?*WSDXML_ELEMENT, }; pub const WSD_METADATA_SECTION_LIST = extern struct { Next: ?*WSD_METADATA_SECTION_LIST, Element: ?*WSD_METADATA_SECTION, }; pub const WSD_URI_LIST = extern struct { Next: ?*WSD_URI_LIST, Element: ?[*:0]const u16, }; pub const WSD_EVENTING_FILTER_ACTION = extern struct { Actions: ?*WSD_URI_LIST, }; pub const WSD_EVENTING_FILTER = extern struct { Dialect: ?[*:0]const u16, FilterAction: ?*WSD_EVENTING_FILTER_ACTION, Data: ?*anyopaque, }; pub const WSD_EVENTING_EXPIRES = extern struct { Duration: ?*WSD_DURATION, DateTime: ?*WSD_DATETIME, }; pub const WSD_EVENTING_DELIVERY_MODE_PUSH = extern struct { NotifyTo: ?*WSD_ENDPOINT_REFERENCE, }; pub const WSD_EVENTING_DELIVERY_MODE = extern struct { Mode: ?[*:0]const u16, Push: ?*WSD_EVENTING_DELIVERY_MODE_PUSH, Data: ?*anyopaque, }; pub const WSD_LOCALIZED_STRING = extern struct { lang: ?[*:0]const u16, String: ?[*:0]const u16, }; pub const RESPONSEBODY_GetMetadata = extern struct { Metadata: ?*WSD_METADATA_SECTION_LIST, }; pub const REQUESTBODY_Subscribe = extern struct { EndTo: ?*WSD_ENDPOINT_REFERENCE, Delivery: ?*WSD_EVENTING_DELIVERY_MODE, Expires: ?*WSD_EVENTING_EXPIRES, Filter: ?*WSD_EVENTING_FILTER, Any: ?*WSDXML_ELEMENT, }; pub const RESPONSEBODY_Subscribe = extern struct { SubscriptionManager: ?*WSD_ENDPOINT_REFERENCE, expires: ?*WSD_EVENTING_EXPIRES, any: ?*WSDXML_ELEMENT, }; pub const REQUESTBODY_Renew = extern struct { Expires: ?*WSD_EVENTING_EXPIRES, Any: ?*WSDXML_ELEMENT, }; pub const RESPONSEBODY_Renew = extern struct { expires: ?*WSD_EVENTING_EXPIRES, any: ?*WSDXML_ELEMENT, }; pub const REQUESTBODY_GetStatus = extern struct { Any: ?*WSDXML_ELEMENT, }; pub const RESPONSEBODY_GetStatus = extern struct { expires: ?*WSD_EVENTING_EXPIRES, any: ?*WSDXML_ELEMENT, }; pub const REQUESTBODY_Unsubscribe = extern struct { any: ?*WSDXML_ELEMENT, }; pub const RESPONSEBODY_SubscriptionEnd = extern struct { SubscriptionManager: ?*WSD_ENDPOINT_REFERENCE, Status: ?[*:0]const u16, Reason: ?*WSD_LOCALIZED_STRING, Any: ?*WSDXML_ELEMENT, }; pub const WSD_UNKNOWN_LOOKUP = extern struct { Any: ?*WSDXML_ELEMENT, }; pub const WSD_EVENT = extern struct { Hr: HRESULT, EventType: u32, DispatchTag: ?PWSTR, HandlerContext: WSD_HANDLER_CONTEXT, Soap: ?*WSD_SOAP_MESSAGE, Operation: ?*WSD_OPERATION, MessageParameters: ?*IWSDMessageParameters, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDiscoveryProvider_Value = @import("../zig.zig").Guid.initString("8ffc8e55-f0eb-480f-88b7-b435dd281d45"); pub const IID_IWSDiscoveryProvider = &IID_IWSDiscoveryProvider_Value; pub const IWSDiscoveryProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAddressFamily: fn( self: *const IWSDiscoveryProvider, dwAddressFamily: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Attach: fn( self: *const IWSDiscoveryProvider, pSink: ?*IWSDiscoveryProviderNotify, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Detach: fn( self: *const IWSDiscoveryProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchById: fn( self: *const IWSDiscoveryProvider, pszId: ?[*:0]const u16, pszTag: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchByAddress: fn( self: *const IWSDiscoveryProvider, pszAddress: ?[*:0]const u16, pszTag: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchByType: fn( self: *const IWSDiscoveryProvider, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pszMatchBy: ?[*:0]const u16, pszTag: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXMLContext: fn( self: *const IWSDiscoveryProvider, ppContext: ?*?*IWSDXMLContext, ) 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 IWSDiscoveryProvider_SetAddressFamily(self: *const T, dwAddressFamily: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).SetAddressFamily(@ptrCast(*const IWSDiscoveryProvider, self), dwAddressFamily); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_Attach(self: *const T, pSink: ?*IWSDiscoveryProviderNotify) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).Attach(@ptrCast(*const IWSDiscoveryProvider, self), pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_Detach(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).Detach(@ptrCast(*const IWSDiscoveryProvider, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_SearchById(self: *const T, pszId: ?[*:0]const u16, pszTag: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).SearchById(@ptrCast(*const IWSDiscoveryProvider, self), pszId, pszTag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_SearchByAddress(self: *const T, pszAddress: ?[*:0]const u16, pszTag: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).SearchByAddress(@ptrCast(*const IWSDiscoveryProvider, self), pszAddress, pszTag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_SearchByType(self: *const T, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pszMatchBy: ?[*:0]const u16, pszTag: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).SearchByType(@ptrCast(*const IWSDiscoveryProvider, self), pTypesList, pScopesList, pszMatchBy, pszTag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProvider_GetXMLContext(self: *const T, ppContext: ?*?*IWSDXMLContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProvider.VTable, self.vtable).GetXMLContext(@ptrCast(*const IWSDiscoveryProvider, self), ppContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDiscoveryProviderNotify_Value = @import("../zig.zig").Guid.initString("73ee3ced-b6e6-4329-a546-3e8ad46563d2"); pub const IID_IWSDiscoveryProviderNotify = &IID_IWSDiscoveryProviderNotify_Value; pub const IWSDiscoveryProviderNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Add: fn( self: *const IWSDiscoveryProviderNotify, pService: ?*IWSDiscoveredService, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IWSDiscoveryProviderNotify, pService: ?*IWSDiscoveredService, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchFailed: fn( self: *const IWSDiscoveryProviderNotify, hr: HRESULT, pszTag: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchComplete: fn( self: *const IWSDiscoveryProviderNotify, pszTag: ?[*:0]const 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 IWSDiscoveryProviderNotify_Add(self: *const T, pService: ?*IWSDiscoveredService) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProviderNotify.VTable, self.vtable).Add(@ptrCast(*const IWSDiscoveryProviderNotify, self), pService); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProviderNotify_Remove(self: *const T, pService: ?*IWSDiscoveredService) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProviderNotify.VTable, self.vtable).Remove(@ptrCast(*const IWSDiscoveryProviderNotify, self), pService); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProviderNotify_SearchFailed(self: *const T, hr: HRESULT, pszTag: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProviderNotify.VTable, self.vtable).SearchFailed(@ptrCast(*const IWSDiscoveryProviderNotify, self), hr, pszTag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryProviderNotify_SearchComplete(self: *const T, pszTag: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryProviderNotify.VTable, self.vtable).SearchComplete(@ptrCast(*const IWSDiscoveryProviderNotify, self), pszTag); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDiscoveredService_Value = @import("../zig.zig").Guid.initString("4bad8a3b-b374-4420-9632-aac945b374aa"); pub const IID_IWSDiscoveredService = &IID_IWSDiscoveredService_Value; pub const IWSDiscoveredService = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetEndpointReference: fn( self: *const IWSDiscoveredService, ppEndpointReference: ?*?*WSD_ENDPOINT_REFERENCE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypes: fn( self: *const IWSDiscoveredService, ppTypesList: ?*?*WSD_NAME_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScopes: fn( self: *const IWSDiscoveredService, ppScopesList: ?*?*WSD_URI_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXAddrs: fn( self: *const IWSDiscoveredService, ppXAddrsList: ?*?*WSD_URI_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataVersion: fn( self: *const IWSDiscoveredService, pullMetadataVersion: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExtendedDiscoXML: fn( self: *const IWSDiscoveredService, ppHeaderAny: ?*?*WSDXML_ELEMENT, ppBodyAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProbeResolveTag: fn( self: *const IWSDiscoveredService, ppszTag: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRemoteTransportAddress: fn( self: *const IWSDiscoveredService, ppszRemoteTransportAddress: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocalTransportAddress: fn( self: *const IWSDiscoveredService, ppszLocalTransportAddress: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocalInterfaceGUID: fn( self: *const IWSDiscoveredService, pGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInstanceId: fn( self: *const IWSDiscoveredService, pullInstanceId: ?*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 IWSDiscoveredService_GetEndpointReference(self: *const T, ppEndpointReference: ?*?*WSD_ENDPOINT_REFERENCE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetEndpointReference(@ptrCast(*const IWSDiscoveredService, self), ppEndpointReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetTypes(self: *const T, ppTypesList: ?*?*WSD_NAME_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetTypes(@ptrCast(*const IWSDiscoveredService, self), ppTypesList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetScopes(self: *const T, ppScopesList: ?*?*WSD_URI_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetScopes(@ptrCast(*const IWSDiscoveredService, self), ppScopesList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetXAddrs(self: *const T, ppXAddrsList: ?*?*WSD_URI_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetXAddrs(@ptrCast(*const IWSDiscoveredService, self), ppXAddrsList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetMetadataVersion(self: *const T, pullMetadataVersion: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetMetadataVersion(@ptrCast(*const IWSDiscoveredService, self), pullMetadataVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetExtendedDiscoXML(self: *const T, ppHeaderAny: ?*?*WSDXML_ELEMENT, ppBodyAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetExtendedDiscoXML(@ptrCast(*const IWSDiscoveredService, self), ppHeaderAny, ppBodyAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetProbeResolveTag(self: *const T, ppszTag: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetProbeResolveTag(@ptrCast(*const IWSDiscoveredService, self), ppszTag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetRemoteTransportAddress(self: *const T, ppszRemoteTransportAddress: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetRemoteTransportAddress(@ptrCast(*const IWSDiscoveredService, self), ppszRemoteTransportAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetLocalTransportAddress(self: *const T, ppszLocalTransportAddress: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetLocalTransportAddress(@ptrCast(*const IWSDiscoveredService, self), ppszLocalTransportAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetLocalInterfaceGUID(self: *const T, pGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetLocalInterfaceGUID(@ptrCast(*const IWSDiscoveredService, self), pGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveredService_GetInstanceId(self: *const T, pullInstanceId: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveredService.VTable, self.vtable).GetInstanceId(@ptrCast(*const IWSDiscoveredService, self), pullInstanceId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDiscoveryPublisher_Value = @import("../zig.zig").Guid.initString("ae01e1a8-3ff9-4148-8116-057cc616fe13"); pub const IID_IWSDiscoveryPublisher = &IID_IWSDiscoveryPublisher_Value; pub const IWSDiscoveryPublisher = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAddressFamily: fn( self: *const IWSDiscoveryPublisher, dwAddressFamily: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterNotificationSink: fn( self: *const IWSDiscoveryPublisher, pSink: ?*IWSDiscoveryPublisherNotify, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnRegisterNotificationSink: fn( self: *const IWSDiscoveryPublisher, pSink: ?*IWSDiscoveryPublisherNotify, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Publish: fn( self: *const IWSDiscoveryPublisher, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnPublish: fn( self: *const IWSDiscoveryPublisher, pszId: ?[*:0]const u16, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pAny: ?*const WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchProbe: fn( self: *const IWSDiscoveryPublisher, pProbeMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchResolve: fn( self: *const IWSDiscoveryPublisher, pResolveMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PublishEx: fn( self: *const IWSDiscoveryPublisher, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchProbeEx: fn( self: *const IWSDiscoveryPublisher, pProbeMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchResolveEx: fn( self: *const IWSDiscoveryPublisher, pResolveMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterScopeMatchingRule: fn( self: *const IWSDiscoveryPublisher, pScopeMatchingRule: ?*IWSDScopeMatchingRule, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnRegisterScopeMatchingRule: fn( self: *const IWSDiscoveryPublisher, pScopeMatchingRule: ?*IWSDScopeMatchingRule, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXMLContext: fn( self: *const IWSDiscoveryPublisher, ppContext: ?*?*IWSDXMLContext, ) 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 IWSDiscoveryPublisher_SetAddressFamily(self: *const T, dwAddressFamily: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).SetAddressFamily(@ptrCast(*const IWSDiscoveryPublisher, self), dwAddressFamily); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_RegisterNotificationSink(self: *const T, pSink: ?*IWSDiscoveryPublisherNotify) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).RegisterNotificationSink(@ptrCast(*const IWSDiscoveryPublisher, self), pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_UnRegisterNotificationSink(self: *const T, pSink: ?*IWSDiscoveryPublisherNotify) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).UnRegisterNotificationSink(@ptrCast(*const IWSDiscoveryPublisher, self), pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_Publish(self: *const T, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).Publish(@ptrCast(*const IWSDiscoveryPublisher, self), pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_UnPublish(self: *const T, pszId: ?[*:0]const u16, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pAny: ?*const WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).UnPublish(@ptrCast(*const IWSDiscoveryPublisher, self), pszId, ullInstanceId, ullMessageNumber, pszSessionId, pAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_MatchProbe(self: *const T, pProbeMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).MatchProbe(@ptrCast(*const IWSDiscoveryPublisher, self), pProbeMessage, pMessageParameters, pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_MatchResolve(self: *const T, pResolveMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).MatchResolve(@ptrCast(*const IWSDiscoveryPublisher, self), pResolveMessage, pMessageParameters, pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_PublishEx(self: *const T, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).PublishEx(@ptrCast(*const IWSDiscoveryPublisher, self), pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList, pHeaderAny, pReferenceParameterAny, pPolicyAny, pEndpointReferenceAny, pAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_MatchProbeEx(self: *const T, pProbeMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).MatchProbeEx(@ptrCast(*const IWSDiscoveryPublisher, self), pProbeMessage, pMessageParameters, pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList, pHeaderAny, pReferenceParameterAny, pPolicyAny, pEndpointReferenceAny, pAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_MatchResolveEx(self: *const T, pResolveMessage: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, pszId: ?[*:0]const u16, ullMetadataVersion: u64, ullInstanceId: u64, ullMessageNumber: u64, pszSessionId: ?[*:0]const u16, pTypesList: ?*const WSD_NAME_LIST, pScopesList: ?*const WSD_URI_LIST, pXAddrsList: ?*const WSD_URI_LIST, pHeaderAny: ?*const WSDXML_ELEMENT, pReferenceParameterAny: ?*const WSDXML_ELEMENT, pPolicyAny: ?*const WSDXML_ELEMENT, pEndpointReferenceAny: ?*const WSDXML_ELEMENT, pAny: ?*const WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).MatchResolveEx(@ptrCast(*const IWSDiscoveryPublisher, self), pResolveMessage, pMessageParameters, pszId, ullMetadataVersion, ullInstanceId, ullMessageNumber, pszSessionId, pTypesList, pScopesList, pXAddrsList, pHeaderAny, pReferenceParameterAny, pPolicyAny, pEndpointReferenceAny, pAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_RegisterScopeMatchingRule(self: *const T, pScopeMatchingRule: ?*IWSDScopeMatchingRule) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).RegisterScopeMatchingRule(@ptrCast(*const IWSDiscoveryPublisher, self), pScopeMatchingRule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_UnRegisterScopeMatchingRule(self: *const T, pScopeMatchingRule: ?*IWSDScopeMatchingRule) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).UnRegisterScopeMatchingRule(@ptrCast(*const IWSDiscoveryPublisher, self), pScopeMatchingRule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisher_GetXMLContext(self: *const T, ppContext: ?*?*IWSDXMLContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisher.VTable, self.vtable).GetXMLContext(@ptrCast(*const IWSDiscoveryPublisher, self), ppContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDiscoveryPublisherNotify_Value = @import("../zig.zig").Guid.initString("e67651b0-337a-4b3c-9758-733388568251"); pub const IID_IWSDiscoveryPublisherNotify = &IID_IWSDiscoveryPublisherNotify_Value; pub const IWSDiscoveryPublisherNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ProbeHandler: fn( self: *const IWSDiscoveryPublisherNotify, pSoap: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveHandler: fn( self: *const IWSDiscoveryPublisherNotify, pSoap: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters, ) 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 IWSDiscoveryPublisherNotify_ProbeHandler(self: *const T, pSoap: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisherNotify.VTable, self.vtable).ProbeHandler(@ptrCast(*const IWSDiscoveryPublisherNotify, self), pSoap, pMessageParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDiscoveryPublisherNotify_ResolveHandler(self: *const T, pSoap: ?*const WSD_SOAP_MESSAGE, pMessageParameters: ?*IWSDMessageParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDiscoveryPublisherNotify.VTable, self.vtable).ResolveHandler(@ptrCast(*const IWSDiscoveryPublisherNotify, self), pSoap, pMessageParameters); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDScopeMatchingRule_Value = @import("../zig.zig").Guid.initString("fcafe424-fef5-481a-bd9f-33ce0574256f"); pub const IID_IWSDScopeMatchingRule = &IID_IWSDScopeMatchingRule_Value; pub const IWSDScopeMatchingRule = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetScopeRule: fn( self: *const IWSDScopeMatchingRule, ppszScopeMatchingRule: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchScopes: fn( self: *const IWSDScopeMatchingRule, pszScope1: ?[*:0]const u16, pszScope2: ?[*:0]const u16, pfMatch: ?*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 IWSDScopeMatchingRule_GetScopeRule(self: *const T, ppszScopeMatchingRule: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDScopeMatchingRule.VTable, self.vtable).GetScopeRule(@ptrCast(*const IWSDScopeMatchingRule, self), ppszScopeMatchingRule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDScopeMatchingRule_MatchScopes(self: *const T, pszScope1: ?[*:0]const u16, pszScope2: ?[*:0]const u16, pfMatch: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDScopeMatchingRule.VTable, self.vtable).MatchScopes(@ptrCast(*const IWSDScopeMatchingRule, self), pszScope1, pszScope2, pfMatch); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDEndpointProxy_Value = @import("../zig.zig").Guid.initString("1860d430-b24c-4975-9f90-dbb39baa24ec"); pub const IID_IWSDEndpointProxy = &IID_IWSDEndpointProxy_Value; pub const IWSDEndpointProxy = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SendOneWayRequest: fn( self: *const IWSDEndpointProxy, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendTwoWayRequest: fn( self: *const IWSDEndpointProxy, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, pResponseContext: ?*const WSD_SYNCHRONOUS_RESPONSE_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendTwoWayRequestAsync: fn( self: *const IWSDEndpointProxy, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, pAsyncState: ?*IUnknown, pCallback: ?*IWSDAsyncCallback, pResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AbortAsyncOperation: fn( self: *const IWSDEndpointProxy, pAsyncResult: ?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessFault: fn( self: *const IWSDEndpointProxy, pFault: ?*const WSD_SOAP_FAULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorInfo: fn( self: *const IWSDEndpointProxy, ppszErrorInfo: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFaultInfo: fn( self: *const IWSDEndpointProxy, ppFault: ?*?*WSD_SOAP_FAULT, ) 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 IWSDEndpointProxy_SendOneWayRequest(self: *const T, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).SendOneWayRequest(@ptrCast(*const IWSDEndpointProxy, self), pBody, pOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_SendTwoWayRequest(self: *const T, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, pResponseContext: ?*const WSD_SYNCHRONOUS_RESPONSE_CONTEXT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).SendTwoWayRequest(@ptrCast(*const IWSDEndpointProxy, self), pBody, pOperation, pResponseContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_SendTwoWayRequestAsync(self: *const T, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, pAsyncState: ?*IUnknown, pCallback: ?*IWSDAsyncCallback, pResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).SendTwoWayRequestAsync(@ptrCast(*const IWSDEndpointProxy, self), pBody, pOperation, pAsyncState, pCallback, pResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_AbortAsyncOperation(self: *const T, pAsyncResult: ?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).AbortAsyncOperation(@ptrCast(*const IWSDEndpointProxy, self), pAsyncResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_ProcessFault(self: *const T, pFault: ?*const WSD_SOAP_FAULT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).ProcessFault(@ptrCast(*const IWSDEndpointProxy, self), pFault); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_GetErrorInfo(self: *const T, ppszErrorInfo: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).GetErrorInfo(@ptrCast(*const IWSDEndpointProxy, self), ppszErrorInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEndpointProxy_GetFaultInfo(self: *const T, ppFault: ?*?*WSD_SOAP_FAULT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDEndpointProxy.VTable, self.vtable).GetFaultInfo(@ptrCast(*const IWSDEndpointProxy, self), ppFault); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDMetadataExchange_Value = @import("../zig.zig").Guid.initString("06996d57-1d67-4928-9307-3d7833fdb846"); pub const IID_IWSDMetadataExchange = &IID_IWSDMetadataExchange_Value; pub const IWSDMetadataExchange = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMetadata: fn( self: *const IWSDMetadataExchange, MetadataOut: ?*?*WSD_METADATA_SECTION_LIST, ) 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 IWSDMetadataExchange_GetMetadata(self: *const T, MetadataOut: ?*?*WSD_METADATA_SECTION_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDMetadataExchange.VTable, self.vtable).GetMetadata(@ptrCast(*const IWSDMetadataExchange, self), MetadataOut); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDServiceProxy_Value = @import("../zig.zig").Guid.initString("d4c7fb9c-03ab-4175-9d67-094fafebf487"); pub const IID_IWSDServiceProxy = &IID_IWSDServiceProxy_Value; pub const IWSDServiceProxy = extern struct { pub const VTable = extern struct { base: IWSDMetadataExchange.VTable, BeginGetMetadata: fn( self: *const IWSDServiceProxy, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndGetMetadata: fn( self: *const IWSDServiceProxy, pResult: ?*IWSDAsyncResult, ppMetadata: ?*?*WSD_METADATA_SECTION_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetServiceMetadata: fn( self: *const IWSDServiceProxy, ppServiceMetadata: ?*?*WSD_SERVICE_METADATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SubscribeToOperation: fn( self: *const IWSDServiceProxy, pOperation: ?*const WSD_OPERATION, pUnknown: ?*IUnknown, pAny: ?*const WSDXML_ELEMENT, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnsubscribeToOperation: fn( self: *const IWSDServiceProxy, pOperation: ?*const WSD_OPERATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEventingStatusCallback: fn( self: *const IWSDServiceProxy, pStatus: ?*IWSDEventingStatus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndpointProxy: fn( self: *const IWSDServiceProxy, ppProxy: ?*?*IWSDEndpointProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDMetadataExchange.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_BeginGetMetadata(self: *const T, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).BeginGetMetadata(@ptrCast(*const IWSDServiceProxy, self), ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_EndGetMetadata(self: *const T, pResult: ?*IWSDAsyncResult, ppMetadata: ?*?*WSD_METADATA_SECTION_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).EndGetMetadata(@ptrCast(*const IWSDServiceProxy, self), pResult, ppMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_GetServiceMetadata(self: *const T, ppServiceMetadata: ?*?*WSD_SERVICE_METADATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).GetServiceMetadata(@ptrCast(*const IWSDServiceProxy, self), ppServiceMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_SubscribeToOperation(self: *const T, pOperation: ?*const WSD_OPERATION, pUnknown: ?*IUnknown, pAny: ?*const WSDXML_ELEMENT, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).SubscribeToOperation(@ptrCast(*const IWSDServiceProxy, self), pOperation, pUnknown, pAny, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_UnsubscribeToOperation(self: *const T, pOperation: ?*const WSD_OPERATION) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).UnsubscribeToOperation(@ptrCast(*const IWSDServiceProxy, self), pOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_SetEventingStatusCallback(self: *const T, pStatus: ?*IWSDEventingStatus) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).SetEventingStatusCallback(@ptrCast(*const IWSDServiceProxy, self), pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxy_GetEndpointProxy(self: *const T, ppProxy: ?*?*IWSDEndpointProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxy.VTable, self.vtable).GetEndpointProxy(@ptrCast(*const IWSDServiceProxy, self), ppProxy); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWSDServiceProxyEventing_Value = @import("../zig.zig").Guid.initString("f9279d6d-1012-4a94-b8cc-fd35d2202bfe"); pub const IID_IWSDServiceProxyEventing = &IID_IWSDServiceProxyEventing_Value; pub const IWSDServiceProxyEventing = extern struct { pub const VTable = extern struct { base: IWSDServiceProxy.VTable, SubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pUnknown: ?*IUnknown, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginSubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pUnknown: ?*IUnknown, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndSubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnsubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginUnsubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndUnsubscribeToMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RenewMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginRenewMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndRenewMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatusForMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginGetStatusForMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndGetStatusForMultipleOperations: fn( self: *const IWSDServiceProxyEventing, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSDServiceProxy.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_SubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pUnknown: ?*IUnknown, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).SubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pUnknown, pExpires, pAny, ppExpires, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_BeginSubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pUnknown: ?*IUnknown, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).BeginSubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pUnknown, pExpires, pAny, pAsyncState, pAsyncCallback, ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_EndSubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).EndSubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pResult, ppExpires, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_UnsubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).UnsubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_BeginUnsubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).BeginUnsubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pAny, pAsyncState, pAsyncCallback, ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_EndUnsubscribeToMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).EndUnsubscribeToMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_RenewMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).RenewMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pExpires, pAny, ppExpires, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_BeginRenewMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pExpires: ?*const WSD_EVENTING_EXPIRES, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).BeginRenewMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pExpires, pAny, pAsyncState, pAsyncCallback, ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_EndRenewMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).EndRenewMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pResult, ppExpires, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_GetStatusForMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).GetStatusForMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pAny, ppExpires, ppAny); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_BeginGetStatusForMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pAny: ?*const WSDXML_ELEMENT, pAsyncState: ?*IUnknown, pAsyncCallback: ?*IWSDAsyncCallback, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).BeginGetStatusForMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pAny, pAsyncState, pAsyncCallback, ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceProxyEventing_EndGetStatusForMultipleOperations(self: *const T, pOperations: [*]const WSD_OPERATION, dwOperationCount: u32, pResult: ?*IWSDAsyncResult, ppExpires: ?*?*WSD_EVENTING_EXPIRES, ppAny: ?*?*WSDXML_ELEMENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceProxyEventing.VTable, self.vtable).EndGetStatusForMultipleOperations(@ptrCast(*const IWSDServiceProxyEventing, self), pOperations, dwOperationCount, pResult, ppExpires, ppAny); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDDeviceProxy_Value = @import("../zig.zig").Guid.initString("eee0c031-c578-4c0e-9a3b-973c35f409db"); pub const IID_IWSDDeviceProxy = &IID_IWSDDeviceProxy_Value; pub const IWSDDeviceProxy = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Init: fn( self: *const IWSDDeviceProxy, pszDeviceId: ?[*:0]const u16, pDeviceAddress: ?*IWSDAddress, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, pSponsor: ?*IWSDDeviceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BeginGetMetadata: fn( self: *const IWSDDeviceProxy, ppResult: ?*?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndGetMetadata: fn( self: *const IWSDDeviceProxy, pResult: ?*IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHostMetadata: fn( self: *const IWSDDeviceProxy, ppHostMetadata: ?*?*WSD_HOST_METADATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThisModelMetadata: fn( self: *const IWSDDeviceProxy, ppManufacturerMetadata: ?*?*WSD_THIS_MODEL_METADATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThisDeviceMetadata: fn( self: *const IWSDDeviceProxy, ppThisDeviceMetadata: ?*?*WSD_THIS_DEVICE_METADATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllMetadata: fn( self: *const IWSDDeviceProxy, ppMetadata: ?*?*WSD_METADATA_SECTION_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetServiceProxyById: fn( self: *const IWSDDeviceProxy, pszServiceId: ?[*:0]const u16, ppServiceProxy: ?*?*IWSDServiceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetServiceProxyByType: fn( self: *const IWSDDeviceProxy, pType: ?*const WSDXML_NAME, ppServiceProxy: ?*?*IWSDServiceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndpointProxy: fn( self: *const IWSDDeviceProxy, ppProxy: ?*?*IWSDEndpointProxy, ) 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 IWSDDeviceProxy_Init(self: *const T, pszDeviceId: ?[*:0]const u16, pDeviceAddress: ?*IWSDAddress, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, pSponsor: ?*IWSDDeviceProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).Init(@ptrCast(*const IWSDDeviceProxy, self), pszDeviceId, pDeviceAddress, pszLocalId, pContext, pSponsor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_BeginGetMetadata(self: *const T, ppResult: ?*?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).BeginGetMetadata(@ptrCast(*const IWSDDeviceProxy, self), ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_EndGetMetadata(self: *const T, pResult: ?*IWSDAsyncResult) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).EndGetMetadata(@ptrCast(*const IWSDDeviceProxy, self), pResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetHostMetadata(self: *const T, ppHostMetadata: ?*?*WSD_HOST_METADATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetHostMetadata(@ptrCast(*const IWSDDeviceProxy, self), ppHostMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetThisModelMetadata(self: *const T, ppManufacturerMetadata: ?*?*WSD_THIS_MODEL_METADATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetThisModelMetadata(@ptrCast(*const IWSDDeviceProxy, self), ppManufacturerMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetThisDeviceMetadata(self: *const T, ppThisDeviceMetadata: ?*?*WSD_THIS_DEVICE_METADATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetThisDeviceMetadata(@ptrCast(*const IWSDDeviceProxy, self), ppThisDeviceMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetAllMetadata(self: *const T, ppMetadata: ?*?*WSD_METADATA_SECTION_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetAllMetadata(@ptrCast(*const IWSDDeviceProxy, self), ppMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetServiceProxyById(self: *const T, pszServiceId: ?[*:0]const u16, ppServiceProxy: ?*?*IWSDServiceProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetServiceProxyById(@ptrCast(*const IWSDDeviceProxy, self), pszServiceId, ppServiceProxy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetServiceProxyByType(self: *const T, pType: ?*const WSDXML_NAME, ppServiceProxy: ?*?*IWSDServiceProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetServiceProxyByType(@ptrCast(*const IWSDDeviceProxy, self), pType, ppServiceProxy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceProxy_GetEndpointProxy(self: *const T, ppProxy: ?*?*IWSDEndpointProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceProxy.VTable, self.vtable).GetEndpointProxy(@ptrCast(*const IWSDDeviceProxy, self), ppProxy); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDAsyncResult_Value = @import("../zig.zig").Guid.initString("11a9852a-8dd8-423e-b537-9356db4fbfb8"); pub const IID_IWSDAsyncResult = &IID_IWSDAsyncResult_Value; pub const IWSDAsyncResult = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetCallback: fn( self: *const IWSDAsyncResult, pCallback: ?*IWSDAsyncCallback, pAsyncState: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWaitHandle: fn( self: *const IWSDAsyncResult, hWaitHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HasCompleted: fn( self: *const IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAsyncState: fn( self: *const IWSDAsyncResult, ppAsyncState: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Abort: fn( self: *const IWSDAsyncResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEvent: fn( self: *const IWSDAsyncResult, pEvent: ?*WSD_EVENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndpointProxy: fn( self: *const IWSDAsyncResult, ppEndpoint: ?*?*IWSDEndpointProxy, ) 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 IWSDAsyncResult_SetCallback(self: *const T, pCallback: ?*IWSDAsyncCallback, pAsyncState: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).SetCallback(@ptrCast(*const IWSDAsyncResult, self), pCallback, pAsyncState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_SetWaitHandle(self: *const T, hWaitHandle: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).SetWaitHandle(@ptrCast(*const IWSDAsyncResult, self), hWaitHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_HasCompleted(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).HasCompleted(@ptrCast(*const IWSDAsyncResult, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_GetAsyncState(self: *const T, ppAsyncState: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).GetAsyncState(@ptrCast(*const IWSDAsyncResult, self), ppAsyncState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_Abort(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).Abort(@ptrCast(*const IWSDAsyncResult, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_GetEvent(self: *const T, pEvent: ?*WSD_EVENT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).GetEvent(@ptrCast(*const IWSDAsyncResult, self), pEvent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDAsyncResult_GetEndpointProxy(self: *const T, ppEndpoint: ?*?*IWSDEndpointProxy) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncResult.VTable, self.vtable).GetEndpointProxy(@ptrCast(*const IWSDAsyncResult, self), ppEndpoint); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDAsyncCallback_Value = @import("../zig.zig").Guid.initString("a63e109d-ce72-49e2-ba98-e845f5ee1666"); pub const IID_IWSDAsyncCallback = &IID_IWSDAsyncCallback_Value; pub const IWSDAsyncCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AsyncOperationComplete: fn( self: *const IWSDAsyncCallback, pAsyncResult: ?*IWSDAsyncResult, pAsyncState: ?*IUnknown, ) 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 IWSDAsyncCallback_AsyncOperationComplete(self: *const T, pAsyncResult: ?*IWSDAsyncResult, pAsyncState: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDAsyncCallback.VTable, self.vtable).AsyncOperationComplete(@ptrCast(*const IWSDAsyncCallback, self), pAsyncResult, pAsyncState); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDEventingStatus_Value = @import("../zig.zig").Guid.initString("49b17f52-637a-407a-ae99-fbe82a4d38c0"); pub const IID_IWSDEventingStatus = &IID_IWSDEventingStatus_Value; pub const IWSDEventingStatus = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SubscriptionRenewed: fn( self: *const IWSDEventingStatus, pszSubscriptionAction: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void, SubscriptionRenewalFailed: fn( self: *const IWSDEventingStatus, pszSubscriptionAction: ?[*:0]const u16, hr: HRESULT, ) callconv(@import("std").os.windows.WINAPI) void, SubscriptionEnded: fn( self: *const IWSDEventingStatus, pszSubscriptionAction: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void, }; 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 IWSDEventingStatus_SubscriptionRenewed(self: *const T, pszSubscriptionAction: ?[*:0]const u16) callconv(.Inline) void { return @ptrCast(*const IWSDEventingStatus.VTable, self.vtable).SubscriptionRenewed(@ptrCast(*const IWSDEventingStatus, self), pszSubscriptionAction); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEventingStatus_SubscriptionRenewalFailed(self: *const T, pszSubscriptionAction: ?[*:0]const u16, hr: HRESULT) callconv(.Inline) void { return @ptrCast(*const IWSDEventingStatus.VTable, self.vtable).SubscriptionRenewalFailed(@ptrCast(*const IWSDEventingStatus, self), pszSubscriptionAction, hr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDEventingStatus_SubscriptionEnded(self: *const T, pszSubscriptionAction: ?[*:0]const u16) callconv(.Inline) void { return @ptrCast(*const IWSDEventingStatus.VTable, self.vtable).SubscriptionEnded(@ptrCast(*const IWSDEventingStatus, self), pszSubscriptionAction); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDDeviceHost_Value = @import("../zig.zig").Guid.initString("917fe891-3d13-4138-9809-934c8abeb12c"); pub const IID_IWSDDeviceHost = &IID_IWSDDeviceHost_Value; pub const IWSDDeviceHost = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Init: fn( self: *const IWSDDeviceHost, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppHostAddresses: ?[*]?*IWSDAddress, dwHostAddressCount: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Start: fn( self: *const IWSDDeviceHost, ullInstanceId: u64, pScopeList: ?*const WSD_URI_LIST, pNotificationSink: ?*IWSDDeviceHostNotify, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IWSDDeviceHost, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Terminate: fn( self: *const IWSDDeviceHost, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterPortType: fn( self: *const IWSDDeviceHost, pPortType: ?*const WSD_PORT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMetadata: fn( self: *const IWSDDeviceHost, pThisModelMetadata: ?*const WSD_THIS_MODEL_METADATA, pThisDeviceMetadata: ?*const WSD_THIS_DEVICE_METADATA, pHostMetadata: ?*const WSD_HOST_METADATA, pCustomMetadata: ?*const WSD_METADATA_SECTION_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterService: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, pService: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RetireService: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddDynamicService: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, pszEndpointAddress: ?[*:0]const u16, pPortType: ?*const WSD_PORT_TYPE, pPortName: ?*const WSDXML_NAME, pAny: ?*const WSDXML_ELEMENT, pService: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveDynamicService: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetServiceDiscoverable: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, fDiscoverable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SignalEvent: fn( self: *const IWSDDeviceHost, pszServiceId: ?[*:0]const u16, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION, ) 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 IWSDDeviceHost_Init(self: *const T, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppHostAddresses: ?[*]?*IWSDAddress, dwHostAddressCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).Init(@ptrCast(*const IWSDDeviceHost, self), pszLocalId, pContext, ppHostAddresses, dwHostAddressCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_Start(self: *const T, ullInstanceId: u64, pScopeList: ?*const WSD_URI_LIST, pNotificationSink: ?*IWSDDeviceHostNotify) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).Start(@ptrCast(*const IWSDDeviceHost, self), ullInstanceId, pScopeList, pNotificationSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).Stop(@ptrCast(*const IWSDDeviceHost, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_Terminate(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).Terminate(@ptrCast(*const IWSDDeviceHost, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_RegisterPortType(self: *const T, pPortType: ?*const WSD_PORT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).RegisterPortType(@ptrCast(*const IWSDDeviceHost, self), pPortType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_SetMetadata(self: *const T, pThisModelMetadata: ?*const WSD_THIS_MODEL_METADATA, pThisDeviceMetadata: ?*const WSD_THIS_DEVICE_METADATA, pHostMetadata: ?*const WSD_HOST_METADATA, pCustomMetadata: ?*const WSD_METADATA_SECTION_LIST) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).SetMetadata(@ptrCast(*const IWSDDeviceHost, self), pThisModelMetadata, pThisDeviceMetadata, pHostMetadata, pCustomMetadata); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_RegisterService(self: *const T, pszServiceId: ?[*:0]const u16, pService: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).RegisterService(@ptrCast(*const IWSDDeviceHost, self), pszServiceId, pService); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_RetireService(self: *const T, pszServiceId: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).RetireService(@ptrCast(*const IWSDDeviceHost, self), pszServiceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_AddDynamicService(self: *const T, pszServiceId: ?[*:0]const u16, pszEndpointAddress: ?[*:0]const u16, pPortType: ?*const WSD_PORT_TYPE, pPortName: ?*const WSDXML_NAME, pAny: ?*const WSDXML_ELEMENT, pService: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).AddDynamicService(@ptrCast(*const IWSDDeviceHost, self), pszServiceId, pszEndpointAddress, pPortType, pPortName, pAny, pService); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_RemoveDynamicService(self: *const T, pszServiceId: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).RemoveDynamicService(@ptrCast(*const IWSDDeviceHost, self), pszServiceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_SetServiceDiscoverable(self: *const T, pszServiceId: ?[*:0]const u16, fDiscoverable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).SetServiceDiscoverable(@ptrCast(*const IWSDDeviceHost, self), pszServiceId, fDiscoverable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDDeviceHost_SignalEvent(self: *const T, pszServiceId: ?[*:0]const u16, pBody: ?*const anyopaque, pOperation: ?*const WSD_OPERATION) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHost.VTable, self.vtable).SignalEvent(@ptrCast(*const IWSDDeviceHost, self), pszServiceId, pBody, pOperation); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDDeviceHostNotify_Value = @import("../zig.zig").Guid.initString("b5bee9f9-eeda-41fe-96f7-f45e14990fb0"); pub const IID_IWSDDeviceHostNotify = &IID_IWSDDeviceHostNotify_Value; pub const IWSDDeviceHostNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetService: fn( self: *const IWSDDeviceHostNotify, pszServiceId: ?[*:0]const u16, ppService: ?*?*IUnknown, ) 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 IWSDDeviceHostNotify_GetService(self: *const T, pszServiceId: ?[*:0]const u16, ppService: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDDeviceHostNotify.VTable, self.vtable).GetService(@ptrCast(*const IWSDDeviceHostNotify, self), pszServiceId, ppService); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSDServiceMessaging_Value = @import("../zig.zig").Guid.initString("94974cf4-0cab-460d-a3f6-7a0ad623c0e6"); pub const IID_IWSDServiceMessaging = &IID_IWSDServiceMessaging_Value; pub const IWSDServiceMessaging = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SendResponse: fn( self: *const IWSDServiceMessaging, pBody: ?*anyopaque, pOperation: ?*WSD_OPERATION, pMessageParameters: ?*IWSDMessageParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FaultRequest: fn( self: *const IWSDServiceMessaging, pRequestHeader: ?*WSD_SOAP_HEADER, pMessageParameters: ?*IWSDMessageParameters, pFault: ?*WSD_SOAP_FAULT, ) 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 IWSDServiceMessaging_SendResponse(self: *const T, pBody: ?*anyopaque, pOperation: ?*WSD_OPERATION, pMessageParameters: ?*IWSDMessageParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceMessaging.VTable, self.vtable).SendResponse(@ptrCast(*const IWSDServiceMessaging, self), pBody, pOperation, pMessageParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSDServiceMessaging_FaultRequest(self: *const T, pRequestHeader: ?*WSD_SOAP_HEADER, pMessageParameters: ?*IWSDMessageParameters, pFault: ?*WSD_SOAP_FAULT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSDServiceMessaging.VTable, self.vtable).FaultRequest(@ptrCast(*const IWSDServiceMessaging, self), pRequestHeader, pMessageParameters, pFault); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (32) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateUdpMessageParameters( ppTxParams: ?*?*IWSDUdpMessageParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateUdpAddress( ppAddress: ?*?*IWSDUdpAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateHttpMessageParameters( ppTxParams: ?*?*IWSDHttpMessageParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateHttpAddress( ppAddress: ?*?*IWSDHttpAddress, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateOutboundAttachment( ppAttachment: ?*?*IWSDOutboundAttachment, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLGetNameFromBuiltinNamespace( pszNamespace: ?[*:0]const u16, pszName: ?[*:0]const u16, ppName: ?*?*WSDXML_NAME, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLCreateContext( ppContext: ?*?*IWSDXMLContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDiscoveryProvider( pContext: ?*IWSDXMLContext, ppProvider: ?*?*IWSDiscoveryProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDCreateDiscoveryProvider2( pContext: ?*IWSDXMLContext, pConfigParams: ?[*]WSD_CONFIG_PARAM, dwConfigParamCount: u32, ppProvider: ?*?*IWSDiscoveryProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDiscoveryPublisher( pContext: ?*IWSDXMLContext, ppPublisher: ?*?*IWSDiscoveryPublisher, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDCreateDiscoveryPublisher2( pContext: ?*IWSDXMLContext, pConfigParams: ?[*]WSD_CONFIG_PARAM, dwConfigParamCount: u32, ppPublisher: ?*?*IWSDiscoveryPublisher, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDeviceProxy( pszDeviceId: ?[*:0]const u16, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppDeviceProxy: ?*?*IWSDDeviceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDeviceProxyAdvanced( pszDeviceId: ?[*:0]const u16, pDeviceAddress: ?*IWSDAddress, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppDeviceProxy: ?*?*IWSDDeviceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDCreateDeviceProxy2( pszDeviceId: ?[*:0]const u16, pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, pConfigParams: ?[*]WSD_CONFIG_PARAM, dwConfigParamCount: u32, ppDeviceProxy: ?*?*IWSDDeviceProxy, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDeviceHost( pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppDeviceHost: ?*?*IWSDDeviceHost, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDCreateDeviceHostAdvanced( pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppHostAddresses: ?[*]?*IWSDAddress, dwHostAddressCount: u32, ppDeviceHost: ?*?*IWSDDeviceHost, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDCreateDeviceHost2( pszLocalId: ?[*:0]const u16, pContext: ?*IWSDXMLContext, pConfigParams: ?[*]WSD_CONFIG_PARAM, dwConfigParamCount: u32, ppDeviceHost: ?*?*IWSDDeviceHost, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDSetConfigurationOption( dwOption: u32, // TODO: what to do with BytesParamIndex 2? pVoid: ?*anyopaque, cbInBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDGetConfigurationOption( dwOption: u32, // TODO: what to do with BytesParamIndex 2? pVoid: ?*anyopaque, cbOutBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDAllocateLinkedMemory( pParent: ?*anyopaque, cbSize: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDFreeLinkedMemory( pVoid: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDAttachLinkedMemory( pParent: ?*anyopaque, pChild: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDDetachLinkedMemory( pVoid: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLBuildAnyForSingleElement( pElementName: ?*WSDXML_NAME, pszText: ?[*:0]const u16, ppAny: ?*?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLGetValueFromAny( pszNamespace: ?[*:0]const u16, pszName: ?[*:0]const u16, pAny: ?*WSDXML_ELEMENT, ppszValue: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLAddSibling( pFirst: ?*WSDXML_ELEMENT, pSecond: ?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLAddChild( pParent: ?*WSDXML_ELEMENT, pChild: ?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDXMLCleanupElement( pAny: ?*WSDXML_ELEMENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDGenerateFault( pszCode: ?[*:0]const u16, pszSubCode: ?[*:0]const u16, pszReason: ?[*:0]const u16, pszDetail: ?[*:0]const u16, pContext: ?*IWSDXMLContext, ppFault: ?*?*WSD_SOAP_FAULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wsdapi" fn WSDGenerateFaultEx( pCode: ?*WSDXML_NAME, pSubCode: ?*WSDXML_NAME, pReasons: ?*WSD_LOCALIZED_STRING_LIST, pszDetail: ?[*:0]const u16, ppFault: ?*?*WSD_SOAP_FAULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDUriEncode( source: [*:0]const u16, cchSource: u32, destOut: [*]?PWSTR, cchDestOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "wsdapi" fn WSDUriDecode( source: [*:0]const u16, cchSource: u32, destOut: [*]?PWSTR, cchDestOut: ?*u32, ) 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 (8) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const IUnknown = @import("../system/com.zig").IUnknown; const PWSTR = @import("../foundation.zig").PWSTR; const SOCKADDR_STORAGE = @import("../networking/win_sock.zig").SOCKADDR_STORAGE; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "WSD_STUB_FUNCTION")) { _ = WSD_STUB_FUNCTION; } if (@hasDecl(@This(), "PWSD_SOAP_MESSAGE_HANDLER")) { _ = PWSD_SOAP_MESSAGE_HANDLER; } @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/devices/web_services_on_devices.zig
const std = @import("../std.zig"); const Cpu = std.Target.Cpu; pub const Feature = enum { @"16_bit_insts", DumpCode, add_no_carry_insts, aperture_regs, atomic_fadd_insts, auto_waitcnt_before_barrier, ci_insts, code_object_v3, cumode, dl_insts, dot1_insts, dot2_insts, dot3_insts, dot4_insts, dot5_insts, dot6_insts, dpp, dpp8, dumpcode, enable_ds128, enable_prt_strict_null, fast_fmaf, flat_address_space, flat_for_global, flat_global_insts, flat_inst_offsets, flat_scratch_insts, flat_segment_offset_bug, fma_mix_insts, fmaf, fp_exceptions, fp16_denormals, fp32_denormals, fp64, fp64_denormals, fp64_fp16_denormals, gcn3_encoding, gfx10, gfx10_insts, gfx7_gfx8_gfx9_insts, gfx8_insts, gfx9, gfx9_insts, half_rate_64_ops, inst_fwd_prefetch_bug, int_clamp_insts, inv_2pi_inline_imm, lds_branch_vmem_war_hazard, lds_misaligned_bug, ldsbankcount16, ldsbankcount32, load_store_opt, localmemorysize0, localmemorysize32768, localmemorysize65536, mad_mix_insts, mai_insts, max_private_element_size_16, max_private_element_size_4, max_private_element_size_8, mimg_r128, movrel, no_data_dep_hazard, no_sdst_cmpx, no_sram_ecc_support, no_xnack_support, nsa_encoding, nsa_to_vmem_bug, offset_3f_bug, pk_fmac_f16_inst, promote_alloca, r128_a16, register_banking, s_memrealtime, scalar_atomics, scalar_flat_scratch_insts, scalar_stores, sdwa, sdwa_mav, sdwa_omod, sdwa_out_mods_vopc, sdwa_scalar, sdwa_sdst, sea_islands, sgpr_init_bug, si_scheduler, smem_to_vector_write_hazard, southern_islands, sram_ecc, trap_handler, trig_reduced_range, unaligned_buffer_access, unaligned_scratch_access, unpacked_d16_vmem, unsafe_ds_offset_folding, vcmpx_exec_war_hazard, vcmpx_permlane_hazard, vgpr_index_mode, vmem_to_scalar_write_hazard, volcanic_islands, vop3_literal, vop3p, vscnt, wavefrontsize16, wavefrontsize32, wavefrontsize64, xnack, }; 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.@"16_bit_insts")] = .{ .llvm_name = "16-bit-insts", .description = "Has i16/f16 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.DumpCode)] = .{ .llvm_name = "DumpCode", .description = "Dump MachineInstrs in the CodeEmitter", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.add_no_carry_insts)] = .{ .llvm_name = "add-no-carry-insts", .description = "Have VALU add/sub instructions without carry out", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.aperture_regs)] = .{ .llvm_name = "aperture-regs", .description = "Has Memory Aperture Base and Size Registers", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.atomic_fadd_insts)] = .{ .llvm_name = "atomic-fadd-insts", .description = "Has buffer_atomic_add_f32, buffer_atomic_pk_add_f16, global_atomic_add_f32, global_atomic_pk_add_f16 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.auto_waitcnt_before_barrier)] = .{ .llvm_name = "auto-waitcnt-before-barrier", .description = "Hardware automatically inserts waitcnt before barrier", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ci_insts)] = .{ .llvm_name = "ci-insts", .description = "Additional instructions for CI+", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.code_object_v3)] = .{ .llvm_name = "code-object-v3", .description = "Generate code object version 3", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.cumode)] = .{ .llvm_name = "cumode", .description = "Enable CU wavefront execution mode", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dl_insts)] = .{ .llvm_name = "dl-insts", .description = "Has v_fmac_f32 and v_xnor_b32 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot1_insts)] = .{ .llvm_name = "dot1-insts", .description = "Has v_dot4_i32_i8 and v_dot8_i32_i4 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot2_insts)] = .{ .llvm_name = "dot2-insts", .description = "Has v_dot2_f32_f16, v_dot2_i32_i16, v_dot2_u32_u16, v_dot4_u32_u8, v_dot8_u32_u4 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot3_insts)] = .{ .llvm_name = "dot3-insts", .description = "Has v_dot8c_i32_i4 instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot4_insts)] = .{ .llvm_name = "dot4-insts", .description = "Has v_dot2c_i32_i16 instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot5_insts)] = .{ .llvm_name = "dot5-insts", .description = "Has v_dot2c_f32_f16 instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dot6_insts)] = .{ .llvm_name = "dot6-insts", .description = "Has v_dot4c_i32_i8 instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dpp)] = .{ .llvm_name = "dpp", .description = "Support DPP (Data Parallel Primitives) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dpp8)] = .{ .llvm_name = "dpp8", .description = "Support DPP8 (Data Parallel Primitives) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.dumpcode)] = .{ .llvm_name = "dumpcode", .description = "Dump MachineInstrs in the CodeEmitter", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.enable_ds128)] = .{ .llvm_name = "enable-ds128", .description = "Use ds_read|write_b128", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.enable_prt_strict_null)] = .{ .llvm_name = "enable-prt-strict-null", .description = "Enable zeroing of result registers for sparse texture fetches", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fast_fmaf)] = .{ .llvm_name = "fast-fmaf", .description = "Assuming f32 fma is at least as fast as mul + add", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_address_space)] = .{ .llvm_name = "flat-address-space", .description = "Support flat address space", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_for_global)] = .{ .llvm_name = "flat-for-global", .description = "Force to generate flat instruction for global", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_global_insts)] = .{ .llvm_name = "flat-global-insts", .description = "Have global_* flat memory instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_inst_offsets)] = .{ .llvm_name = "flat-inst-offsets", .description = "Flat instructions have immediate offset addressing mode", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_scratch_insts)] = .{ .llvm_name = "flat-scratch-insts", .description = "Have scratch_* flat memory instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.flat_segment_offset_bug)] = .{ .llvm_name = "flat-segment-offset-bug", .description = "GFX10 bug, inst_offset ignored in flat segment", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fma_mix_insts)] = .{ .llvm_name = "fma-mix-insts", .description = "Has v_fma_mix_f32, v_fma_mixlo_f16, v_fma_mixhi_f16 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fmaf)] = .{ .llvm_name = "fmaf", .description = "Enable single precision FMA (not as fast as mul+add, but fused)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fp_exceptions)] = .{ .llvm_name = "fp-exceptions", .description = "Enable floating point exceptions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fp16_denormals)] = .{ .llvm_name = "fp16-denormals", .description = "Enable half precision denormal handling", .dependencies = featureSet(&[_]Feature{ .fp64_fp16_denormals, }), }; result[@enumToInt(Feature.fp32_denormals)] = .{ .llvm_name = "fp32-denormals", .description = "Enable single precision denormal handling", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fp64)] = .{ .llvm_name = "fp64", .description = "Enable double precision operations", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.fp64_denormals)] = .{ .llvm_name = "fp64-denormals", .description = "Enable double and half precision denormal handling", .dependencies = featureSet(&[_]Feature{ .fp64, .fp64_fp16_denormals, }), }; result[@enumToInt(Feature.fp64_fp16_denormals)] = .{ .llvm_name = "fp64-fp16-denormals", .description = "Enable double and half precision denormal handling", .dependencies = featureSet(&[_]Feature{ .fp64, }), }; result[@enumToInt(Feature.gcn3_encoding)] = .{ .llvm_name = "gcn3-encoding", .description = "Encoding format for VI", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.gfx10)] = .{ .llvm_name = "gfx10", .description = "GFX10 GPU generation", .dependencies = featureSet(&[_]Feature{ .@"16_bit_insts", .add_no_carry_insts, .aperture_regs, .ci_insts, .dpp, .dpp8, .fast_fmaf, .flat_address_space, .flat_global_insts, .flat_inst_offsets, .flat_scratch_insts, .fma_mix_insts, .fp64, .gfx10_insts, .gfx8_insts, .gfx9_insts, .int_clamp_insts, .inv_2pi_inline_imm, .localmemorysize65536, .mimg_r128, .movrel, .no_data_dep_hazard, .no_sdst_cmpx, .no_sram_ecc_support, .pk_fmac_f16_inst, .register_banking, .s_memrealtime, .sdwa, .sdwa_omod, .sdwa_scalar, .sdwa_sdst, .vop3_literal, .vop3p, .vscnt, }), }; result[@enumToInt(Feature.gfx10_insts)] = .{ .llvm_name = "gfx10-insts", .description = "Additional instructions for GFX10+", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.gfx7_gfx8_gfx9_insts)] = .{ .llvm_name = "gfx7-gfx8-gfx9-insts", .description = "Instructions shared in GFX7, GFX8, GFX9", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.gfx8_insts)] = .{ .llvm_name = "gfx8-insts", .description = "Additional instructions for GFX8+", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.gfx9)] = .{ .llvm_name = "gfx9", .description = "GFX9 GPU generation", .dependencies = featureSet(&[_]Feature{ .@"16_bit_insts", .add_no_carry_insts, .aperture_regs, .ci_insts, .dpp, .fast_fmaf, .flat_address_space, .flat_global_insts, .flat_inst_offsets, .flat_scratch_insts, .fp64, .gcn3_encoding, .gfx7_gfx8_gfx9_insts, .gfx8_insts, .gfx9_insts, .int_clamp_insts, .inv_2pi_inline_imm, .localmemorysize65536, .r128_a16, .s_memrealtime, .scalar_atomics, .scalar_flat_scratch_insts, .scalar_stores, .sdwa, .sdwa_omod, .sdwa_scalar, .sdwa_sdst, .vgpr_index_mode, .vop3p, .wavefrontsize64, }), }; result[@enumToInt(Feature.gfx9_insts)] = .{ .llvm_name = "gfx9-insts", .description = "Additional instructions for GFX9+", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.half_rate_64_ops)] = .{ .llvm_name = "half-rate-64-ops", .description = "Most fp64 instructions are half rate instead of quarter", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.inst_fwd_prefetch_bug)] = .{ .llvm_name = "inst-fwd-prefetch-bug", .description = "S_INST_PREFETCH instruction causes shader to hang", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.int_clamp_insts)] = .{ .llvm_name = "int-clamp-insts", .description = "Support clamp for integer destination", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.inv_2pi_inline_imm)] = .{ .llvm_name = "inv-2pi-inline-imm", .description = "Has 1 / (2 * pi) as inline immediate", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.lds_branch_vmem_war_hazard)] = .{ .llvm_name = "lds-branch-vmem-war-hazard", .description = "Switching between LDS and VMEM-tex not waiting VM_VSRC=0", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.lds_misaligned_bug)] = .{ .llvm_name = "lds-misaligned-bug", .description = "Some GFX10 bug with misaligned multi-dword LDS access in WGP mode", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ldsbankcount16)] = .{ .llvm_name = "ldsbankcount16", .description = "The number of LDS banks per compute unit.", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ldsbankcount32)] = .{ .llvm_name = "ldsbankcount32", .description = "The number of LDS banks per compute unit.", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.load_store_opt)] = .{ .llvm_name = "load-store-opt", .description = "Enable SI load/store optimizer pass", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.localmemorysize0)] = .{ .llvm_name = "localmemorysize0", .description = "The size of local memory in bytes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.localmemorysize32768)] = .{ .llvm_name = "localmemorysize32768", .description = "The size of local memory in bytes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.localmemorysize65536)] = .{ .llvm_name = "localmemorysize65536", .description = "The size of local memory in bytes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.mad_mix_insts)] = .{ .llvm_name = "mad-mix-insts", .description = "Has v_mad_mix_f32, v_mad_mixlo_f16, v_mad_mixhi_f16 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.mai_insts)] = .{ .llvm_name = "mai-insts", .description = "Has mAI instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.max_private_element_size_16)] = .{ .llvm_name = "max-private-element-size-16", .description = "Maximum private access size may be 16", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.max_private_element_size_4)] = .{ .llvm_name = "max-private-element-size-4", .description = "Maximum private access size may be 4", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.max_private_element_size_8)] = .{ .llvm_name = "max-private-element-size-8", .description = "Maximum private access size may be 8", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.mimg_r128)] = .{ .llvm_name = "mimg-r128", .description = "Support 128-bit texture resources", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.movrel)] = .{ .llvm_name = "movrel", .description = "Has v_movrel*_b32 instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.no_data_dep_hazard)] = .{ .llvm_name = "no-data-dep-hazard", .description = "Does not need SW waitstates", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.no_sdst_cmpx)] = .{ .llvm_name = "no-sdst-cmpx", .description = "V_CMPX does not write VCC/SGPR in addition to EXEC", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.no_sram_ecc_support)] = .{ .llvm_name = "no-sram-ecc-support", .description = "Hardware does not support SRAM ECC", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.no_xnack_support)] = .{ .llvm_name = "no-xnack-support", .description = "Hardware does not support XNACK", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.nsa_encoding)] = .{ .llvm_name = "nsa-encoding", .description = "Support NSA encoding for image instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.nsa_to_vmem_bug)] = .{ .llvm_name = "nsa-to-vmem-bug", .description = "MIMG-NSA followed by VMEM fail if EXEC_LO or EXEC_HI equals zero", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.offset_3f_bug)] = .{ .llvm_name = "offset-3f-bug", .description = "Branch offset of 3f hardware bug", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.pk_fmac_f16_inst)] = .{ .llvm_name = "pk-fmac-f16-inst", .description = "Has v_pk_fmac_f16 instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.promote_alloca)] = .{ .llvm_name = "promote-alloca", .description = "Enable promote alloca pass", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.r128_a16)] = .{ .llvm_name = "r128-a16", .description = "Support 16 bit coordindates/gradients/lod/clamp/mip types on gfx9", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.register_banking)] = .{ .llvm_name = "register-banking", .description = "Has register banking", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.s_memrealtime)] = .{ .llvm_name = "s-memrealtime", .description = "Has s_memrealtime instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.scalar_atomics)] = .{ .llvm_name = "scalar-atomics", .description = "Has atomic scalar memory instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.scalar_flat_scratch_insts)] = .{ .llvm_name = "scalar-flat-scratch-insts", .description = "Have s_scratch_* flat memory instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.scalar_stores)] = .{ .llvm_name = "scalar-stores", .description = "Has store scalar memory instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa)] = .{ .llvm_name = "sdwa", .description = "Support SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa_mav)] = .{ .llvm_name = "sdwa-mav", .description = "Support v_mac_f32/f16 with SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa_omod)] = .{ .llvm_name = "sdwa-omod", .description = "Support OMod with SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa_out_mods_vopc)] = .{ .llvm_name = "sdwa-out-mods-vopc", .description = "Support clamp for VOPC with SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa_scalar)] = .{ .llvm_name = "sdwa-scalar", .description = "Support scalar register with SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sdwa_sdst)] = .{ .llvm_name = "sdwa-sdst", .description = "Support scalar dst for VOPC with SDWA (Sub-DWORD Addressing) extension", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.sea_islands)] = .{ .llvm_name = "sea-islands", .description = "SEA_ISLANDS GPU generation", .dependencies = featureSet(&[_]Feature{ .ci_insts, .flat_address_space, .fp64, .gfx7_gfx8_gfx9_insts, .localmemorysize65536, .mimg_r128, .movrel, .no_sram_ecc_support, .trig_reduced_range, .wavefrontsize64, }), }; result[@enumToInt(Feature.sgpr_init_bug)] = .{ .llvm_name = "sgpr-init-bug", .description = "VI SGPR initialization bug requiring a fixed SGPR allocation size", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.si_scheduler)] = .{ .llvm_name = "si-scheduler", .description = "Enable SI Machine Scheduler", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.smem_to_vector_write_hazard)] = .{ .llvm_name = "smem-to-vector-write-hazard", .description = "s_load_dword followed by v_cmp page faults", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.southern_islands)] = .{ .llvm_name = "southern-islands", .description = "SOUTHERN_ISLANDS GPU generation", .dependencies = featureSet(&[_]Feature{ .fp64, .ldsbankcount32, .localmemorysize32768, .mimg_r128, .movrel, .no_sram_ecc_support, .no_xnack_support, .trig_reduced_range, .wavefrontsize64, }), }; result[@enumToInt(Feature.sram_ecc)] = .{ .llvm_name = "sram-ecc", .description = "Enable SRAM ECC", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.trap_handler)] = .{ .llvm_name = "trap-handler", .description = "Trap handler support", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.trig_reduced_range)] = .{ .llvm_name = "trig-reduced-range", .description = "Requires use of fract on arguments to trig instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.unaligned_buffer_access)] = .{ .llvm_name = "unaligned-buffer-access", .description = "Support unaligned global loads and stores", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.unaligned_scratch_access)] = .{ .llvm_name = "unaligned-scratch-access", .description = "Support unaligned scratch loads and stores", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.unpacked_d16_vmem)] = .{ .llvm_name = "unpacked-d16-vmem", .description = "Has unpacked d16 vmem instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.unsafe_ds_offset_folding)] = .{ .llvm_name = "unsafe-ds-offset-folding", .description = "Force using DS instruction immediate offsets on SI", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vcmpx_exec_war_hazard)] = .{ .llvm_name = "vcmpx-exec-war-hazard", .description = "V_CMPX WAR hazard on EXEC (V_CMPX issue ONLY)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vcmpx_permlane_hazard)] = .{ .llvm_name = "vcmpx-permlane-hazard", .description = "TODO: describe me", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vgpr_index_mode)] = .{ .llvm_name = "vgpr-index-mode", .description = "Has VGPR mode register indexing", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vmem_to_scalar_write_hazard)] = .{ .llvm_name = "vmem-to-scalar-write-hazard", .description = "VMEM instruction followed by scalar writing to EXEC mask, M0 or SGPR leads to incorrect execution.", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.volcanic_islands)] = .{ .llvm_name = "volcanic-islands", .description = "VOLCANIC_ISLANDS GPU generation", .dependencies = featureSet(&[_]Feature{ .@"16_bit_insts", .ci_insts, .dpp, .flat_address_space, .fp64, .gcn3_encoding, .gfx7_gfx8_gfx9_insts, .gfx8_insts, .int_clamp_insts, .inv_2pi_inline_imm, .localmemorysize65536, .mimg_r128, .movrel, .no_sram_ecc_support, .s_memrealtime, .scalar_stores, .sdwa, .sdwa_mav, .sdwa_out_mods_vopc, .trig_reduced_range, .vgpr_index_mode, .wavefrontsize64, }), }; result[@enumToInt(Feature.vop3_literal)] = .{ .llvm_name = "vop3-literal", .description = "Can use one literal in VOP3", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vop3p)] = .{ .llvm_name = "vop3p", .description = "Has VOP3P packed instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.vscnt)] = .{ .llvm_name = "vscnt", .description = "Has separate store vscnt counter", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.wavefrontsize16)] = .{ .llvm_name = "wavefrontsize16", .description = "The number of threads per wavefront", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.wavefrontsize32)] = .{ .llvm_name = "wavefrontsize32", .description = "The number of threads per wavefront", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.wavefrontsize64)] = .{ .llvm_name = "wavefrontsize64", .description = "The number of threads per wavefront", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.xnack)] = .{ .llvm_name = "xnack", .description = "Enable XNACK support", .dependencies = featureSet(&[_]Feature{}), }; 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 bonaire = Cpu{ .name = "bonaire", .llvm_name = "bonaire", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const carrizo = Cpu{ .name = "carrizo", .llvm_name = "carrizo", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .unpacked_d16_vmem, .volcanic_islands, .xnack, }), }; pub const fiji = Cpu{ .name = "fiji", .llvm_name = "fiji", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const generic = Cpu{ .name = "generic", .llvm_name = "generic", .features = featureSet(&[_]Feature{ .wavefrontsize64, }), }; pub const generic_hsa = Cpu{ .name = "generic_hsa", .llvm_name = "generic-hsa", .features = featureSet(&[_]Feature{ .flat_address_space, .wavefrontsize64, }), }; pub const gfx1010 = Cpu{ .name = "gfx1010", .llvm_name = "gfx1010", .features = featureSet(&[_]Feature{ .code_object_v3, .dl_insts, .flat_segment_offset_bug, .gfx10, .inst_fwd_prefetch_bug, .lds_branch_vmem_war_hazard, .lds_misaligned_bug, .ldsbankcount32, .no_xnack_support, .nsa_encoding, .nsa_to_vmem_bug, .offset_3f_bug, .scalar_atomics, .scalar_flat_scratch_insts, .scalar_stores, .smem_to_vector_write_hazard, .vcmpx_exec_war_hazard, .vcmpx_permlane_hazard, .vmem_to_scalar_write_hazard, .wavefrontsize32, }), }; pub const gfx1011 = Cpu{ .name = "gfx1011", .llvm_name = "gfx1011", .features = featureSet(&[_]Feature{ .code_object_v3, .dl_insts, .dot1_insts, .dot2_insts, .dot5_insts, .dot6_insts, .flat_segment_offset_bug, .gfx10, .inst_fwd_prefetch_bug, .lds_branch_vmem_war_hazard, .ldsbankcount32, .no_xnack_support, .nsa_encoding, .nsa_to_vmem_bug, .offset_3f_bug, .scalar_atomics, .scalar_flat_scratch_insts, .scalar_stores, .smem_to_vector_write_hazard, .vcmpx_exec_war_hazard, .vcmpx_permlane_hazard, .vmem_to_scalar_write_hazard, .wavefrontsize32, }), }; pub const gfx1012 = Cpu{ .name = "gfx1012", .llvm_name = "gfx1012", .features = featureSet(&[_]Feature{ .code_object_v3, .dl_insts, .dot1_insts, .dot2_insts, .dot5_insts, .dot6_insts, .flat_segment_offset_bug, .gfx10, .inst_fwd_prefetch_bug, .lds_branch_vmem_war_hazard, .lds_misaligned_bug, .ldsbankcount32, .no_xnack_support, .nsa_encoding, .nsa_to_vmem_bug, .offset_3f_bug, .scalar_atomics, .scalar_flat_scratch_insts, .scalar_stores, .smem_to_vector_write_hazard, .vcmpx_exec_war_hazard, .vcmpx_permlane_hazard, .vmem_to_scalar_write_hazard, .wavefrontsize32, }), }; pub const gfx600 = Cpu{ .name = "gfx600", .llvm_name = "gfx600", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const gfx601 = Cpu{ .name = "gfx601", .llvm_name = "gfx601", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const gfx700 = Cpu{ .name = "gfx700", .llvm_name = "gfx700", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const gfx701 = Cpu{ .name = "gfx701", .llvm_name = "gfx701", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const gfx702 = Cpu{ .name = "gfx702", .llvm_name = "gfx702", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .ldsbankcount16, .no_xnack_support, .sea_islands, }), }; pub const gfx703 = Cpu{ .name = "gfx703", .llvm_name = "gfx703", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount16, .no_xnack_support, .sea_islands, }), }; pub const gfx704 = Cpu{ .name = "gfx704", .llvm_name = "gfx704", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const gfx801 = Cpu{ .name = "gfx801", .llvm_name = "gfx801", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .unpacked_d16_vmem, .volcanic_islands, .xnack, }), }; pub const gfx802 = Cpu{ .name = "gfx802", .llvm_name = "gfx802", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sgpr_init_bug, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const gfx803 = Cpu{ .name = "gfx803", .llvm_name = "gfx803", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const gfx810 = Cpu{ .name = "gfx810", .llvm_name = "gfx810", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount16, .volcanic_islands, .xnack, }), }; pub const gfx900 = Cpu{ .name = "gfx900", .llvm_name = "gfx900", .features = featureSet(&[_]Feature{ .code_object_v3, .gfx9, .ldsbankcount32, .mad_mix_insts, .no_sram_ecc_support, .no_xnack_support, }), }; pub const gfx902 = Cpu{ .name = "gfx902", .llvm_name = "gfx902", .features = featureSet(&[_]Feature{ .code_object_v3, .gfx9, .ldsbankcount32, .mad_mix_insts, .no_sram_ecc_support, .xnack, }), }; pub const gfx904 = Cpu{ .name = "gfx904", .llvm_name = "gfx904", .features = featureSet(&[_]Feature{ .code_object_v3, .fma_mix_insts, .gfx9, .ldsbankcount32, .no_sram_ecc_support, .no_xnack_support, }), }; pub const gfx906 = Cpu{ .name = "gfx906", .llvm_name = "gfx906", .features = featureSet(&[_]Feature{ .code_object_v3, .dl_insts, .dot1_insts, .dot2_insts, .fma_mix_insts, .gfx9, .half_rate_64_ops, .ldsbankcount32, .no_xnack_support, }), }; pub const gfx908 = Cpu{ .name = "gfx908", .llvm_name = "gfx908", .features = featureSet(&[_]Feature{ .atomic_fadd_insts, .code_object_v3, .dl_insts, .dot1_insts, .dot2_insts, .dot3_insts, .dot4_insts, .dot5_insts, .dot6_insts, .fma_mix_insts, .gfx9, .half_rate_64_ops, .ldsbankcount32, .mai_insts, .pk_fmac_f16_inst, .sram_ecc, }), }; pub const gfx909 = Cpu{ .name = "gfx909", .llvm_name = "gfx909", .features = featureSet(&[_]Feature{ .code_object_v3, .gfx9, .ldsbankcount32, .mad_mix_insts, .xnack, }), }; pub const hainan = Cpu{ .name = "hainan", .llvm_name = "hainan", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const hawaii = Cpu{ .name = "hawaii", .llvm_name = "hawaii", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const iceland = Cpu{ .name = "iceland", .llvm_name = "iceland", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sgpr_init_bug, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const kabini = Cpu{ .name = "kabini", .llvm_name = "kabini", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount16, .no_xnack_support, .sea_islands, }), }; pub const kaveri = Cpu{ .name = "kaveri", .llvm_name = "kaveri", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sea_islands, }), }; pub const mullins = Cpu{ .name = "mullins", .llvm_name = "mullins", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount16, .no_xnack_support, .sea_islands, }), }; pub const oland = Cpu{ .name = "oland", .llvm_name = "oland", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const pitcairn = Cpu{ .name = "pitcairn", .llvm_name = "pitcairn", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const polaris10 = Cpu{ .name = "polaris10", .llvm_name = "polaris10", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const polaris11 = Cpu{ .name = "polaris11", .llvm_name = "polaris11", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const stoney = Cpu{ .name = "stoney", .llvm_name = "stoney", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount16, .volcanic_islands, .xnack, }), }; pub const tahiti = Cpu{ .name = "tahiti", .llvm_name = "tahiti", .features = featureSet(&[_]Feature{ .code_object_v3, .fast_fmaf, .half_rate_64_ops, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; pub const tonga = Cpu{ .name = "tonga", .llvm_name = "tonga", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .sgpr_init_bug, .unpacked_d16_vmem, .volcanic_islands, }), }; pub const verde = Cpu{ .name = "verde", .llvm_name = "verde", .features = featureSet(&[_]Feature{ .code_object_v3, .ldsbankcount32, .no_xnack_support, .southern_islands, }), }; }; /// All amdgpu 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.bonaire, &cpu.carrizo, &cpu.fiji, &cpu.generic, &cpu.generic_hsa, &cpu.gfx1010, &cpu.gfx1011, &cpu.gfx1012, &cpu.gfx600, &cpu.gfx601, &cpu.gfx700, &cpu.gfx701, &cpu.gfx702, &cpu.gfx703, &cpu.gfx704, &cpu.gfx801, &cpu.gfx802, &cpu.gfx803, &cpu.gfx810, &cpu.gfx900, &cpu.gfx902, &cpu.gfx904, &cpu.gfx906, &cpu.gfx908, &cpu.gfx909, &cpu.hainan, &cpu.hawaii, &cpu.iceland, &cpu.kabini, &cpu.kaveri, &cpu.mullins, &cpu.oland, &cpu.pitcairn, &cpu.polaris10, &cpu.polaris11, &cpu.stoney, &cpu.tahiti, &cpu.tonga, &cpu.verde, };
lib/std/target/amdgpu.zig